code
stringlengths 31
1.05M
| apis
list | extract_api
stringlengths 97
1.91M
|
---|---|---|
from typing import AnyStr, ByteString, Callable, List, Sequence, TypeVar, Union
import numpy as np
ReturnType = TypeVar("ReturnType")
dtype_dict = {
"float": "FLOAT",
"double": "DOUBLE",
"float32": "FLOAT",
"float64": "DOUBLE",
"int8": "INT8",
"int16": "INT16",
"int32": "INT32",
"int64": "INT64",
"uint8": "UINT8",
"uint16": "UINT16",
"uint32": "UINT32",
"uint64": "UINT64",
"bool": "BOOL",
"str": "STRING",
}
allowed_devices = {"CPU", "GPU"}
allowed_backends = {"TF", "TFLITE", "TORCH", "ONNX"}
def numpy2blob(tensor: np.ndarray) -> tuple:
"""Convert the numpy input from user to `Tensor`."""
try:
if tensor.dtype.num == np.dtype("str").num:
dtype = dtype_dict["str"]
blob = "".join([string + "\0" for string in tensor.flat])
else:
dtype = dtype_dict[str(tensor.dtype)]
blob = tensor.tobytes()
except KeyError:
raise TypeError(f"RedisAI doesn't support tensors of type {tensor.dtype}")
shape = tensor.shape
return dtype, shape, blob
def blob2numpy(
value: ByteString, shape: Union[list, tuple], dtype: str, mutable: bool
) -> np.ndarray:
"""Convert `BLOB` result from RedisAI to `np.ndarray`."""
mm = {"FLOAT": "float32", "DOUBLE": "float64"}
dtype = mm.get(dtype, dtype.lower())
if dtype == 'string':
a = np.array(value.decode().split('\0')[:-1], dtype='str')
elif mutable:
a = np.fromstring(value, dtype=dtype)
else:
a = np.frombuffer(value, dtype=dtype)
return a.reshape(shape)
def list2dict(lst):
"""Convert the list from RedisAI to a dict."""
if len(lst) % 2 != 0:
raise RuntimeError("Can't unpack the list: {}".format(lst))
out = {}
for i in range(0, len(lst), 2):
key = lst[i].decode().lower()
val = lst[i + 1]
if key != "blob" and isinstance(val, bytes):
val = val.decode()
out[key] = val
return out
def recursive_bytetransform(arr: List[AnyStr], target: Callable[..., ReturnType]) -> list[ReturnType]:
"""
Recurse value, replacing each element of b'' with the appropriate element.
Function returns the same array after inplace operation which updates `arr`
"""
for ix in range(len(arr)):
obj = arr[ix]
if isinstance(obj, list):
recursive_bytetransform(obj, target)
else:
arr[ix] = target(obj)
return arr
def listify(inp: Union[str, Sequence[str]]) -> Sequence[str]:
"""Wrap the ``inp`` with a list if it's not a list already."""
return (inp,) if not isinstance(inp, (list, tuple)) else inp
|
[
"typing.TypeVar",
"numpy.dtype",
"numpy.frombuffer",
"numpy.fromstring"
] |
[((114, 135), 'typing.TypeVar', 'TypeVar', (['"""ReturnType"""'], {}), "('ReturnType')\n", (121, 135), False, 'from typing import AnyStr, ByteString, Callable, List, Sequence, TypeVar, Union\n'), ((1477, 1510), 'numpy.fromstring', 'np.fromstring', (['value'], {'dtype': 'dtype'}), '(value, dtype=dtype)\n', (1490, 1510), True, 'import numpy as np\n'), ((1533, 1566), 'numpy.frombuffer', 'np.frombuffer', (['value'], {'dtype': 'dtype'}), '(value, dtype=dtype)\n', (1546, 1566), True, 'import numpy as np\n'), ((701, 716), 'numpy.dtype', 'np.dtype', (['"""str"""'], {}), "('str')\n", (709, 716), True, 'import numpy as np\n')]
|
import numpy as np
from path import Path
import scipy.misc
from collections import Counter
import matplotlib.pyplot as plt
class KittiRawLoader(object):
def __init__(self,
dataset_dir,
static_frames_file=None,
img_height=128,
img_width=416,
min_speed=2,
get_gt=False):
dir_path = Path(__file__).realpath().dirname()
test_scene_file = dir_path/'test_scenes.txt'
self.from_speed = static_frames_file is None
if static_frames_file is not None:
static_frames_file = Path(static_frames_file)
self.collect_static_frames(static_frames_file)
with open(test_scene_file, 'r') as f:
test_scenes = f.readlines()
self.test_scenes = [t[:-1] for t in test_scenes]
self.dataset_dir = Path(dataset_dir)
self.img_height = img_height
self.img_width = img_width
self.cam_ids = ['02', '03']
#self.date_list = ['2011_09_26', '2011_09_28', '2011_09_29', '2011_09_30', '2011_10_03']
self.date_list = ['2011_09_26', '2011_09_28', '2011_09_29', '2011_09_30']
self.min_speed = min_speed
self.get_gt = get_gt
self.collect_train_folders()#make self.scenes
#public
def collect_scenes(self, drive):#drive 当前路径
train_scenes = []
for c in self.cam_ids:
oxts = sorted((drive/'oxts'/'data').files('*.txt'))#list
scene_data = {'cid': c, 'dir': drive, 'speed': [], 'frame_id': [], 'rel_path': drive.name + '_' + c}
for n, f in enumerate(oxts):
metadata = np.genfromtxt(f)
speed = metadata[8:11]
scene_data['speed'].append(speed)
scene_data['frame_id'].append('{:010d}'.format(n))
sample = self.load_image(scene_data, 0)
if sample is None:
return []
scene_data['P_rect'] = self.get_P_rect(scene_data, sample[1], sample[2])
scene_data['intrinsics'] = scene_data['P_rect'][:,:3]
train_scenes.append(scene_data)
return train_scenes
#public
#generator using yield rather than return
def get_scene_imgs(self, scene_data):
def construct_sample(scene_data, i, frame_id):
sample = [self.load_image(scene_data, i)[0], frame_id]
if self.get_gt:
sample.append(self.generate_depth_map(scene_data, i))
return sample
if self.from_speed:
cum_speed = np.zeros(3)
for i, speed in enumerate(scene_data['speed']):
cum_speed += speed
speed_mag = np.linalg.norm(cum_speed)
if speed_mag > self.min_speed:
frame_id = scene_data['frame_id'][i]
yield construct_sample(scene_data, i, frame_id)
cum_speed *= 0
else: # from static frame file
drive = str(scene_data['dir'].name)
for (i,frame_id) in enumerate(scene_data['frame_id']):
if (drive not in self.static_frames.keys()) or (frame_id not in self.static_frames[drive]):
yield construct_sample(scene_data, i, frame_id)
#private
def collect_static_frames(self, static_frames_file):
with open(static_frames_file, 'r') as f:
frames = f.readlines()
self.static_frames = {}
for fr in frames:
if fr == '\n':
continue
date, drive, frame_id = fr.split(' ')
curr_fid = '%.10d' % (np.int(frame_id[:-1]))
if drive not in self.static_frames.keys():
self.static_frames[drive] = []
self.static_frames[drive].append(curr_fid)
#private
def collect_train_folders(self):
self.scenes = []
for date in self.date_list:
drive_set = (self.dataset_dir/date).dirs()
for dr in drive_set:
if dr.name[:-5] not in self.test_scenes:
self.scenes.append(dr)
#private
def get_P_rect(self, scene_data, zoom_x, zoom_y):
#print(zoom_x, zoom_y)
calib_file = scene_data['dir'].parent/'calib_cam_to_cam.txt'
filedata = self.read_raw_calib_file(calib_file)
P_rect = np.reshape(filedata['P_rect_' + scene_data['cid']], (3, 4))
P_rect[0] *= zoom_x
P_rect[1] *= zoom_y
return P_rect
def load_image(self, scene_data, tgt_idx):
img_file = scene_data['dir']/'image_{}'.format(scene_data['cid'])/'data'/scene_data['frame_id'][tgt_idx]+'.png'
if not img_file.isfile():
return None
img = scipy.misc.imread(img_file)
zoom_y = self.img_height/img.shape[0]
zoom_x = self.img_width/img.shape[1]
img = scipy.misc.imresize(img, (self.img_height, self.img_width))
return img, zoom_x, zoom_y
def read_raw_calib_file(self, filepath):
# From https://github.com/utiasSTARS/pykitti/blob/master/pykitti/utils.py
"""Read in a calibration file and parse into a dictionary."""
data = {}
with open(filepath, 'r') as f:
for line in f.readlines():
key, value = line.split(':', 1)
# The only non-float values in these files are dates, which
# we don't care about anyway
try:
data[key] = np.array([float(x) for x in value.split()])
except ValueError:
pass
return data
#called by get_scene_imgs
def generate_depth_map(self, scene_data, tgt_idx):
# compute projection matrix velodyne->image plane
def sub2ind(matrixSize, rowSub, colSub):
m, n = matrixSize
return rowSub * (n-1) + colSub - 1
R_cam2rect = np.eye(4)
calib_dir = scene_data['dir'].parent
cam2cam = self.read_raw_calib_file(calib_dir/'calib_cam_to_cam.txt')
velo2cam = self.read_raw_calib_file(calib_dir/'calib_velo_to_cam.txt')
velo2cam = np.hstack((velo2cam['R'].reshape(3,3), velo2cam['T'][..., np.newaxis]))
velo2cam = np.vstack((velo2cam, np.array([0, 0, 0, 1.0])))
P_rect = scene_data['P_rect']
R_cam2rect[:3,:3] = cam2cam['R_rect_00'].reshape(3,3)
P_velo2im = np.dot(np.dot(P_rect, R_cam2rect), velo2cam)
velo_file_name = scene_data['dir']/'velodyne_points'/'data'/'{}.bin'.format(scene_data['frame_id'][tgt_idx])
# load velodyne points and remove all behind image plane (approximation)
# each row of the velodyne data is forward, left, up, reflectance
velo = np.fromfile(velo_file_name, dtype=np.float32).reshape(-1, 4)
velo[:,3] = 1
velo = velo[velo[:, 0] >= 0, :]
# project the points to the camera
velo_pts_im = np.dot(P_velo2im, velo.T).T
velo_pts_im[:, :2] = velo_pts_im[:,:2] / velo_pts_im[:,-1:]
# check if in bounds
# use minus 1 to get the exact same value as KITTI matlab code
velo_pts_im[:, 0] = np.round(velo_pts_im[:,0]) - 1
velo_pts_im[:, 1] = np.round(velo_pts_im[:,1]) - 1
val_inds = (velo_pts_im[:, 0] >= 0) & (velo_pts_im[:, 1] >= 0)
val_inds = val_inds & (velo_pts_im[:,0] < self.img_width) & (velo_pts_im[:,1] < self.img_height)
velo_pts_im = velo_pts_im[val_inds, :]
# project to image
depth = np.zeros((self.img_height, self.img_width)).astype(np.float32)
depth[velo_pts_im[:, 1].astype(np.int), velo_pts_im[:, 0].astype(np.int)] = velo_pts_im[:, 2]
# find the duplicate points and choose the closest depth
inds = sub2ind(depth.shape, velo_pts_im[:, 1], velo_pts_im[:, 0])
dupe_inds = [item for item, count in Counter(inds).items() if count > 1]
for dd in dupe_inds:
pts = np.where(inds == dd)[0]
x_loc = int(velo_pts_im[pts[0], 0])
y_loc = int(velo_pts_im[pts[0], 1])
depth[y_loc, x_loc] = velo_pts_im[pts, 2].min()
depth[depth < 0] = 0
return depth
|
[
"numpy.eye",
"numpy.fromfile",
"collections.Counter",
"numpy.zeros",
"numpy.genfromtxt",
"path.Path",
"numpy.linalg.norm",
"numpy.reshape",
"numpy.int",
"numpy.array",
"numpy.where",
"numpy.dot",
"numpy.round"
] |
[((869, 886), 'path.Path', 'Path', (['dataset_dir'], {}), '(dataset_dir)\n', (873, 886), False, 'from path import Path\n'), ((4336, 4395), 'numpy.reshape', 'np.reshape', (["filedata['P_rect_' + scene_data['cid']]", '(3, 4)'], {}), "(filedata['P_rect_' + scene_data['cid']], (3, 4))\n", (4346, 4395), True, 'import numpy as np\n'), ((5884, 5893), 'numpy.eye', 'np.eye', (['(4)'], {}), '(4)\n', (5890, 5893), True, 'import numpy as np\n'), ((614, 638), 'path.Path', 'Path', (['static_frames_file'], {}), '(static_frames_file)\n', (618, 638), False, 'from path import Path\n'), ((2567, 2578), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (2575, 2578), True, 'import numpy as np\n'), ((6382, 6408), 'numpy.dot', 'np.dot', (['P_rect', 'R_cam2rect'], {}), '(P_rect, R_cam2rect)\n', (6388, 6408), True, 'import numpy as np\n'), ((6898, 6923), 'numpy.dot', 'np.dot', (['P_velo2im', 'velo.T'], {}), '(P_velo2im, velo.T)\n', (6904, 6923), True, 'import numpy as np\n'), ((7123, 7150), 'numpy.round', 'np.round', (['velo_pts_im[:, 0]'], {}), '(velo_pts_im[:, 0])\n', (7131, 7150), True, 'import numpy as np\n'), ((7182, 7209), 'numpy.round', 'np.round', (['velo_pts_im[:, 1]'], {}), '(velo_pts_im[:, 1])\n', (7190, 7209), True, 'import numpy as np\n'), ((1662, 1678), 'numpy.genfromtxt', 'np.genfromtxt', (['f'], {}), '(f)\n', (1675, 1678), True, 'import numpy as np\n'), ((2702, 2727), 'numpy.linalg.norm', 'np.linalg.norm', (['cum_speed'], {}), '(cum_speed)\n', (2716, 2727), True, 'import numpy as np\n'), ((3616, 3637), 'numpy.int', 'np.int', (['frame_id[:-1]'], {}), '(frame_id[:-1])\n', (3622, 3637), True, 'import numpy as np\n'), ((6227, 6251), 'numpy.array', 'np.array', (['[0, 0, 0, 1.0]'], {}), '([0, 0, 0, 1.0])\n', (6235, 6251), True, 'import numpy as np\n'), ((6709, 6754), 'numpy.fromfile', 'np.fromfile', (['velo_file_name'], {'dtype': 'np.float32'}), '(velo_file_name, dtype=np.float32)\n', (6720, 6754), True, 'import numpy as np\n'), ((7481, 7524), 'numpy.zeros', 'np.zeros', (['(self.img_height, self.img_width)'], {}), '((self.img_height, self.img_width))\n', (7489, 7524), True, 'import numpy as np\n'), ((7914, 7934), 'numpy.where', 'np.where', (['(inds == dd)'], {}), '(inds == dd)\n', (7922, 7934), True, 'import numpy as np\n'), ((395, 409), 'path.Path', 'Path', (['__file__'], {}), '(__file__)\n', (399, 409), False, 'from path import Path\n'), ((7831, 7844), 'collections.Counter', 'Counter', (['inds'], {}), '(inds)\n', (7838, 7844), False, 'from collections import Counter\n')]
|
import json
import logging
import numpy as np
import pathlib
import pickle
import random
from sklearn.preprocessing import LabelEncoder
import torch
import torch.utils.data
class TranscribedDataset():
le = None
sos = '<sos>'
eos = '<eos>'
pad = '<pad>'
unk = '<unk>'
@classmethod
def init_vocabulary(cls, transcriptions):
cls.le = LabelEncoder()
tokens = [cls.sos, cls.eos, cls.unk, cls.pad] + \
[c for t in transcriptions for c in t]
cls.le.fit(tokens)
@classmethod
def get_label_encoder(cls):
if cls.le is None:
raise ValueError('Vocabulary not initialized.')
return cls.le
@classmethod
def get_token_id(cls, token):
return cls.get_label_encoder().transform([token])[0]
@classmethod
def vocabulary_size(cls):
return len(cls.get_label_encoder().classes_)
@classmethod
def caption2tensor(cls, capt):
le = cls.get_label_encoder()
capt = [c if c in le.classes_ else cls.unk for c in capt]
capt = [cls.sos] + capt + [cls.eos]
return torch.Tensor(le.transform(capt))
class Flickr8KData(torch.utils.data.Dataset, TranscribedDataset):
@classmethod
def init_vocabulary(cls, dataset):
transcriptions = [sd[2] for sd in dataset.split_data]
TranscribedDataset.init_vocabulary(transcriptions)
def __init__(self, root, feature_fname, meta_fname, split='train', language='en',
downsampling_factor=None):
self.root = root
self.split = split
self.feature_fname = feature_fname
self.language = language
if language == 'en':
self.text_key = 'raw'
elif language == 'jp':
self.text_key = 'raw_jp'
else:
raise ValueError('Language {} not supported.'.format(language))
self.root = root
self.split = split
self.language = language
root_path = pathlib.Path(root)
# Loading label encoder
module_path = pathlib.Path(__file__).parent
with open(module_path / 'label_encoders.pkl', 'rb') as f:
self.__class__.le = pickle.load(f)[language]
# Loading metadata
with open(root_path / meta_fname) as fmeta:
metadata = json.load(fmeta)['images']
# Loading mapping from image id to list of caption id
self.image_captions = {}
with open(root_path / 'flickr_audio' / 'wav2capt.txt') as fwav2capt:
for line in fwav2capt:
audio_id, image_id, text_id = line.split()
text_id = int(text_id[1:])
self.image_captions[image_id] = self.image_captions.get(image_id, []) + [(text_id, audio_id)]
# Creating image, caption pairs
self.split_data = []
for image in metadata:
if image['split'] == self.split:
fname = image['filename']
for text_id, audio_id in self.image_captions[fname]:
# In the reduced dataset containing only sentences with
# translations, removed sentences are replaced by 'None' to
# keep the index of the sentence fixed, so that we can
# still retrieve them based on text_id.
# TODO: find a nicer way to handle this
if image['sentences'][text_id] is not None:
if self.text_key in image['sentences'][text_id]:
self.split_data.append((
fname,
audio_id,
image['sentences'][text_id][self.text_key]))
# Downsampling
if downsampling_factor is not None:
num_examples = int(len(self.split_data) // downsampling_factor)
self.split_data = random.sample(self.split_data, num_examples)
# image and audio feature data
image = torch.load(root_path / 'resnet_features.pt')
self.image = dict(zip(image['filenames'], image['features']))
audio = torch.load(root_path / feature_fname)
self.audio = dict(zip(audio['filenames'], audio['features']))
def __getitem__(self, index):
sd = self.split_data[index]
image = self.image[sd[0]]
audio = self.audio[sd[1]]
text = self.caption2tensor(sd[2])
return dict(image_id=sd[0],
audio_id=sd[1],
image=image,
text=text,
audio=audio,
gloss=sd[2])
def __len__(self):
return len(self.split_data)
def get_config(self):
return dict(feature_fname=self.feature_fname,
label_encoder=self.get_label_encoder(),
language=self.language)
def evaluation(self):
"""Returns image features, audio features, caption features, and a
boolean array specifying whether a caption goes with an image."""
audio = []
text = []
image = []
matches = []
image2idx = {}
for sd in self.split_data:
# Add image
if sd[0] in image2idx:
image_idx = image2idx[sd[0]]
else:
image_idx = len(image)
image2idx[sd[0]] = image_idx
image.append(self.image[sd[0]])
# Add audio and text
audio.append(self.audio[sd[1]])
text.append(sd[2])
matches.append((len(audio) - 1, image_idx))
correct = torch.zeros(len(audio), len(image)).bool()
for i, j in matches:
correct[i, j] = True
return dict(image=image, audio=audio, text=text, correct=correct)
def is_slt(self):
return self.language != 'en'
def split_sentences(self, sentences):
if self.language == 'jp':
return sentences
else:
return [s.split() for s in sentences]
class LibriSpeechData(torch.utils.data.Dataset, TranscribedDataset):
@classmethod
def init_vocabulary(cls, dataset):
transcriptions = [m['trn'] for m in dataset.metadata]
TranscribedDataset.init_vocabulary(transcriptions)
def __init__(self, root, feature_fname, meta_fname, split='train',
downsampling_factor=None):
# 'val' set in flickr8k corresponds to 'dev' in librispeech
if split == 'val':
split = 'dev'
self.root = root
self.split = split
self.feature_fname = feature_fname
root_path = pathlib.Path(root)
with open(root_path / meta_fname) as fmeta:
self.metadata = json.load(fmeta)
self.num_lines = self.metadata[-1]['audio_end']
if downsampling_factor is not None:
num_examples = len(self.metadata) // downsampling_factor
self.metadata = random.sample(self.metadata, num_examples)
# filter examples based on split
meta = []
for ex in self.metadata:
if ex['split'] == self.split:
meta.append(ex)
self.metadata = meta
# load audio features
self.audio = np.memmap(root_path / feature_fname, dtype='float64',
mode='r', shape=(self.num_lines, 39))
def __getitem__(self, index):
sd = self.metadata[index]
audio = torch.from_numpy(self.audio[sd['audio_start']:sd['audio_end']])
text = self.caption2tensor(sd['trn'])
return dict(audio_id=sd['fileid'], text=text, audio=audio)
def __len__(self):
return len(self.metadata)
def get_config(self):
return dict(feature_fname=self.feature_fname,
label_encoder=self.get_label_encoder())
def evaluation(self):
"""Returns audio features with corresponding caption"""
audio = []
text = []
for ex in self.metadata:
text.append(ex['trn'])
a = torch.from_numpy(self.audio[ex['audio_start']:ex['audio_end']])
audio.append(a)
return dict(audio=audio, text=text)
def batch_audio(audios, max_frames=2048):
"""Merge audio captions. Truncate to max_frames. Pad with 0s."""
mfcc_lengths = [len(cap[:max_frames, :]) for cap in audios]
mfcc = torch.zeros(len(audios), max(mfcc_lengths), audios[0].size(1))
for i, cap in enumerate(audios):
end = mfcc_lengths[i]
mfcc[i, :end] = cap[:end]
return mfcc.permute(0, 2, 1), torch.tensor(mfcc_lengths)
def batch_text(texts):
"""Merge captions (from tuple of 1D tensor to 2D tensor). Pad with
pad token."""
char_lengths = [len(cap) for cap in texts]
chars = torch.Tensor(len(texts), max(char_lengths)).long()
chars.fill_(Flickr8KData.get_token_id(Flickr8KData.pad))
for i, cap in enumerate(texts):
end = char_lengths[i]
chars[i, :end] = cap[:end]
return chars, torch.tensor(char_lengths)
def batch_image(images):
return torch.stack(images, 0)
def collate_fn(data, max_frames=2048):
images, texts, audios = zip(* [(datum['image'],
datum['text'],
datum['audio']) for datum in data])
# Merge images (from tuple of 3D tensor to 4D tensor).
images = batch_image(images)
mfcc, mfcc_lengths = batch_audio(audios, max_frames=max_frames)
chars, char_lengths = batch_text(texts)
return dict(image=images, audio=mfcc, text=chars, audio_len=mfcc_lengths,
text_len=char_lengths)
def collate_fn_speech(data, max_frames=2048):
texts, audios = zip(* [(datum['text'],
datum['audio']) for datum in data])
mfcc, mfcc_lengths = batch_audio(audios, max_frames=max_frames)
chars, char_lengths = batch_text(texts)
return dict(audio=mfcc, text=chars, audio_len=mfcc_lengths,
text_len=char_lengths)
def flickr8k_loader(root, meta_fname, language, feature_fname,
split='train', batch_size=32, shuffle=False,
max_frames=2048,
downsampling_factor=None):
return torch.utils.data.DataLoader(
dataset=Flickr8KData(root=root,
feature_fname=feature_fname,
meta_fname=meta_fname,
split=split,
language=language,
downsampling_factor=downsampling_factor),
batch_size=batch_size,
shuffle=shuffle,
num_workers=0,
collate_fn=lambda x: collate_fn(x, max_frames=max_frames))
def librispeech_loader(root, meta_fname, feature_fname,
split='train', batch_size=32, shuffle=False,
max_frames=2048,
downsampling_factor=None):
return torch.utils.data.DataLoader(
dataset=LibriSpeechData(root=root,
feature_fname=feature_fname,
meta_fname=meta_fname,
split=split,
downsampling_factor=downsampling_factor),
batch_size=batch_size,
shuffle=shuffle,
num_workers=0,
collate_fn=lambda x: collate_fn_speech(x, max_frames=max_frames))
|
[
"json.load",
"torch.stack",
"random.sample",
"torch.load",
"sklearn.preprocessing.LabelEncoder",
"pathlib.Path",
"pickle.load",
"numpy.memmap",
"torch.tensor",
"torch.from_numpy"
] |
[((9024, 9046), 'torch.stack', 'torch.stack', (['images', '(0)'], {}), '(images, 0)\n', (9035, 9046), False, 'import torch\n'), ((370, 384), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (382, 384), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((1977, 1995), 'pathlib.Path', 'pathlib.Path', (['root'], {}), '(root)\n', (1989, 1995), False, 'import pathlib\n'), ((3981, 4025), 'torch.load', 'torch.load', (["(root_path / 'resnet_features.pt')"], {}), "(root_path / 'resnet_features.pt')\n", (3991, 4025), False, 'import torch\n'), ((4112, 4149), 'torch.load', 'torch.load', (['(root_path / feature_fname)'], {}), '(root_path / feature_fname)\n', (4122, 4149), False, 'import torch\n'), ((6604, 6622), 'pathlib.Path', 'pathlib.Path', (['root'], {}), '(root)\n', (6616, 6622), False, 'import pathlib\n'), ((7210, 7306), 'numpy.memmap', 'np.memmap', (['(root_path / feature_fname)'], {'dtype': '"""float64"""', 'mode': '"""r"""', 'shape': '(self.num_lines, 39)'}), "(root_path / feature_fname, dtype='float64', mode='r', shape=(self\n .num_lines, 39))\n", (7219, 7306), True, 'import numpy as np\n'), ((7418, 7481), 'torch.from_numpy', 'torch.from_numpy', (["self.audio[sd['audio_start']:sd['audio_end']]"], {}), "(self.audio[sd['audio_start']:sd['audio_end']])\n", (7434, 7481), False, 'import torch\n'), ((8528, 8554), 'torch.tensor', 'torch.tensor', (['mfcc_lengths'], {}), '(mfcc_lengths)\n', (8540, 8554), False, 'import torch\n'), ((8959, 8985), 'torch.tensor', 'torch.tensor', (['char_lengths'], {}), '(char_lengths)\n', (8971, 8985), False, 'import torch\n'), ((2050, 2072), 'pathlib.Path', 'pathlib.Path', (['__file__'], {}), '(__file__)\n', (2062, 2072), False, 'import pathlib\n'), ((3880, 3924), 'random.sample', 'random.sample', (['self.split_data', 'num_examples'], {}), '(self.split_data, num_examples)\n', (3893, 3924), False, 'import random\n'), ((6703, 6719), 'json.load', 'json.load', (['fmeta'], {}), '(fmeta)\n', (6712, 6719), False, 'import json\n'), ((6921, 6963), 'random.sample', 'random.sample', (['self.metadata', 'num_examples'], {}), '(self.metadata, num_examples)\n', (6934, 6963), False, 'import random\n'), ((8006, 8069), 'torch.from_numpy', 'torch.from_numpy', (["self.audio[ex['audio_start']:ex['audio_end']]"], {}), "(self.audio[ex['audio_start']:ex['audio_end']])\n", (8022, 8069), False, 'import torch\n'), ((2178, 2192), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (2189, 2192), False, 'import pickle\n'), ((2305, 2321), 'json.load', 'json.load', (['fmeta'], {}), '(fmeta)\n', (2314, 2321), False, 'import json\n')]
|
import os
import csv
import six
import pandas as pd
import numpy as np
from ..core import STReader, SortOrder, find_conversion
from ..core import csv_headers, col_population, pop_na, col_timestamps, col_node_ids
# TODO: Won't work with a non-population column csv file. Update so that if there is no populations then it will
# do a lookup by node_id only.
def write_csv(path, spiketrain_reader, mode='w', sort_order=SortOrder.none, include_header=True,
include_population=True, units='ms', **kwargs):
path_dir = os.path.dirname(path)
if path_dir and not os.path.exists(path_dir):
os.makedirs(path_dir)
conv_factor = find_conversion(spiketrain_reader.units, units)
with open(path, mode=mode) as f:
if include_population:
# Saves the Population column
csv_writer = csv.writer(f, delimiter=' ')
if include_header:
csv_writer.writerow(csv_headers)
for spk in spiketrain_reader.spikes(sort_order=sort_order):
csv_writer.writerow([spk[0]*conv_factor, spk[1], spk[2]])
else:
# Don't write the Population column
csv_writer = csv.writer(f, delimiter=' ')
if include_header:
csv_writer.writerow([c for c in csv_headers if c != col_population])
for spk in spiketrain_reader.spikes(sort_order=sort_order):
csv_writer.writerow([spk[0]*conv_factor, spk[2]])
class CSVSTReader(STReader):
def __init__(self, path, sep=' ', **kwargs):
self._n_spikes = None
self._populations = None
try:
# check to see if file contains headers
with open(path, 'r') as csvfile:
sniffer = csv.Sniffer()
has_headers = sniffer.has_header(csvfile.read(1024))
except Exception:
has_headers = True
self._spikes_df = pd.read_csv(path, sep=sep, header=0 if has_headers else None)
if not has_headers:
self._spikes_df.columns = csv_headers[0::2]
if col_population not in self._spikes_df.columns:
pop_name = kwargs.get(col_population, pop_na)
self._spikes_df[col_population] = pop_name
# TODO: Check all the necessary columns exits
self._spikes_df = self._spikes_df[csv_headers]
@property
def populations(self):
if self._populations is None:
self._populations = self._spikes_df['population'].unique()
return self._populations
def to_dataframe(self, node_ids=None, populations=None, time_window=None, sort_order=SortOrder.none, **kwargs):
selected = self._spikes_df.copy()
mask = True
if populations is not None:
if isinstance(populations, six.string_types) or np.isscalar(populations):
mask &= selected[col_population] == populations
else:
mask &= selected[col_population].isin(populations)
if node_ids is not None:
node_ids = [node_ids] if np.isscalar(node_ids) else node_ids
mask &= selected[col_node_ids].isin(node_ids)
if time_window is not None:
mask &= (selected[col_timestamps] >= time_window[0]) & (selected[col_timestamps] <= time_window[1])
if isinstance(mask, pd.Series):
selected = selected[mask]
if sort_order == SortOrder.by_time:
selected.sort_values(by=col_timestamps, inplace=True)
elif sort_order == SortOrder.by_id:
selected.sort_values(by=col_node_ids, inplace=True)
selected.index = pd.RangeIndex(len(selected.index))
return selected
def get_times(self, node_id, population=None, time_window=None, **kwargs):
selected = self._spikes_df.copy()
mask = (selected[col_node_ids] == node_id)
if population is not None:
mask &= (selected[col_population] == population)
if time_window is not None:
mask &= (selected[col_timestamps] >= time_window[0]) & (selected[col_timestamps] <= time_window[1])
return np.array(self._spikes_df[mask][col_timestamps])
def nodes(self, populations=None):
selected = self._spikes_df.copy()
mask = True
if populations is not None:
if isinstance(populations, six.string_types) or np.isscalar(populations):
mask = selected[col_population] == populations
else:
mask = selected[col_population].isin(populations)
if isinstance(mask, pd.Series):
selected = selected[mask]
return list(selected.groupby(by=[col_population, col_node_ids]).indices.keys())
def n_spikes(self, population=None):
return len(self.to_dataframe(populations=population))
def time_range(self, populations=None):
selected = self._spikes_df.copy()
if populations is not None:
if isinstance(populations, six.string_types) or np.isscalar(populations):
mask = selected[col_population] == populations
else:
mask = selected[col_population].isin(populations)
selected = selected[mask]
return selected[col_timestamps].agg([np.min, np.max]).values
def spikes(self, node_ids=None, populations=None, time_window=None, sort_order=SortOrder.none, **kwargs):
selected = self._spikes_df.copy()
mask = True
if populations is not None:
if isinstance(populations, six.string_types) or np.isscalar(populations):
mask &= selected[col_population] == populations
else:
mask &= selected[col_population].isin(populations)
if node_ids is not None:
node_ids = [node_ids] if np.isscalar(node_ids) else node_ids
mask &= selected[col_node_ids].isin(node_ids)
if time_window is not None:
mask &= (selected[col_timestamps] >= time_window[0]) & (selected[col_timestamps] <= time_window[1])
if isinstance(mask, pd.Series):
selected = selected[mask]
if sort_order == SortOrder.by_time:
selected.sort_values(by=col_timestamps, inplace=True)
elif sort_order == SortOrder.by_id:
selected.sort_values(by=col_node_ids, inplace=True)
indicies = selected.index.values
for indx in indicies:
yield tuple(self._spikes_df.iloc[indx])
def __len__(self):
if self._n_spikes is None:
self._n_spikes = len(self._spikes_df)
return self._n_spikes
|
[
"os.makedirs",
"csv.writer",
"pandas.read_csv",
"numpy.isscalar",
"os.path.dirname",
"os.path.exists",
"csv.Sniffer",
"numpy.array"
] |
[((536, 557), 'os.path.dirname', 'os.path.dirname', (['path'], {}), '(path)\n', (551, 557), False, 'import os\n'), ((616, 637), 'os.makedirs', 'os.makedirs', (['path_dir'], {}), '(path_dir)\n', (627, 637), False, 'import os\n'), ((1913, 1974), 'pandas.read_csv', 'pd.read_csv', (['path'], {'sep': 'sep', 'header': '(0 if has_headers else None)'}), '(path, sep=sep, header=0 if has_headers else None)\n', (1924, 1974), True, 'import pandas as pd\n'), ((4110, 4157), 'numpy.array', 'np.array', (['self._spikes_df[mask][col_timestamps]'], {}), '(self._spikes_df[mask][col_timestamps])\n', (4118, 4157), True, 'import numpy as np\n'), ((582, 606), 'os.path.exists', 'os.path.exists', (['path_dir'], {}), '(path_dir)\n', (596, 606), False, 'import os\n'), ((840, 868), 'csv.writer', 'csv.writer', (['f'], {'delimiter': '""" """'}), "(f, delimiter=' ')\n", (850, 868), False, 'import csv\n'), ((1183, 1211), 'csv.writer', 'csv.writer', (['f'], {'delimiter': '""" """'}), "(f, delimiter=' ')\n", (1193, 1211), False, 'import csv\n'), ((1746, 1759), 'csv.Sniffer', 'csv.Sniffer', ([], {}), '()\n', (1757, 1759), False, 'import csv\n'), ((2803, 2827), 'numpy.isscalar', 'np.isscalar', (['populations'], {}), '(populations)\n', (2814, 2827), True, 'import numpy as np\n'), ((3049, 3070), 'numpy.isscalar', 'np.isscalar', (['node_ids'], {}), '(node_ids)\n', (3060, 3070), True, 'import numpy as np\n'), ((4356, 4380), 'numpy.isscalar', 'np.isscalar', (['populations'], {}), '(populations)\n', (4367, 4380), True, 'import numpy as np\n'), ((4983, 5007), 'numpy.isscalar', 'np.isscalar', (['populations'], {}), '(populations)\n', (4994, 5007), True, 'import numpy as np\n'), ((5535, 5559), 'numpy.isscalar', 'np.isscalar', (['populations'], {}), '(populations)\n', (5546, 5559), True, 'import numpy as np\n'), ((5781, 5802), 'numpy.isscalar', 'np.isscalar', (['node_ids'], {}), '(node_ids)\n', (5792, 5802), True, 'import numpy as np\n')]
|
"""MIT License
Copyright (c) 2022 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""
import numpy as np
import cv2
import matplotlib.pyplot as plt
class Estimator:
def __init__(self,enhance=False,leftProjMat=[],rightProjMat=[]):
"""
to_enchance = To enchange images before processing
left_C_mat = Left camera matrix
left_T_vec = Left camera translation vector
right_T_vec = Right camera translation vector
"""
self.to_enhance = enhance
# Decomposing the Projection Matrixs
self.left_C_mat, _,self.left_T_vec, _, _, _, _ = cv2.decomposeProjectionMatrix(leftProjMat)
_, _,self.right_T_vec, _, _, _, _ = cv2.decomposeProjectionMatrix(rightProjMat)
def enhance(self,image):
"""
To preprocess the image with differnt algorithms
# Gaussian Blur to remove the noise
# Gamma Equilization
# Histogram filter to equilize the lights
"""
image = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
smoothen_image = cv2.GaussianBlur(image,(5,5),0.1)
gamma=0.75
lookUpTable = np.empty((1,256), np.uint8)
for i in range(256):
lookUpTable[0,i] = np.clip(pow(i / 255.0, gamma) * 255.0, 0, 255)
gamma_equilized_image = cv2.LUT(smoothen_image, lookUpTable)
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(4,4))
histogram_filtered_image = clahe.apply(gamma_equilized_image)
return histogram_filtered_image
def estimate(self,rightimage ,leftimage,depth=False):
"""
Using Stereo SGBM to calculate disparity map and
traditional approach to calculate depth
Input:
leftimage = Left image matrix
rightimage = Right image matrix
depth = To calculate depth
Output:
Disparity map and depth map of the input image
"""
if self.to_enhance:
leftimage = self.enhance(leftimage)
rightimage = self.enhance(rightimage)
# Calculating Depth Map using Stereo SGBM
stereo = cv2.StereoSGBM_create(numDisparities=16*6,
blockSize=15,P1=4000,P2=15000,
mode=cv2.STEREO_SGBM_MODE_SGBM_3WAY)
disparity_map = stereo.compute(leftimage,rightimage)
if depth:
disparity = disparity_map
f = self.left_C_mat[0][0]
b = self.right_T_vec[0] - self.left_T_vec[0]
# Avoid instability and division by zero
disparity_map[disparity_map == 0.0] = 0.1
disparity_map[disparity_map == -1.0] = 0.1
depth_map = np.ones(disparity_map.shape)
depth_map = f * b / (disparity_map+0.00000001)
return disparity,depth_map
return disparity_map[:,95:]
|
[
"cv2.GaussianBlur",
"cv2.cvtColor",
"numpy.empty",
"numpy.ones",
"cv2.LUT",
"cv2.createCLAHE",
"cv2.decomposeProjectionMatrix",
"cv2.StereoSGBM_create"
] |
[((1590, 1632), 'cv2.decomposeProjectionMatrix', 'cv2.decomposeProjectionMatrix', (['leftProjMat'], {}), '(leftProjMat)\n', (1619, 1632), False, 'import cv2\n'), ((1677, 1720), 'cv2.decomposeProjectionMatrix', 'cv2.decomposeProjectionMatrix', (['rightProjMat'], {}), '(rightProjMat)\n', (1706, 1720), False, 'import cv2\n'), ((2009, 2048), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (2021, 2048), False, 'import cv2\n'), ((2073, 2109), 'cv2.GaussianBlur', 'cv2.GaussianBlur', (['image', '(5, 5)', '(0.1)'], {}), '(image, (5, 5), 0.1)\n', (2089, 2109), False, 'import cv2\n'), ((2157, 2185), 'numpy.empty', 'np.empty', (['(1, 256)', 'np.uint8'], {}), '((1, 256), np.uint8)\n', (2165, 2185), True, 'import numpy as np\n'), ((2324, 2360), 'cv2.LUT', 'cv2.LUT', (['smoothen_image', 'lookUpTable'], {}), '(smoothen_image, lookUpTable)\n', (2331, 2360), False, 'import cv2\n'), ((2386, 2437), 'cv2.createCLAHE', 'cv2.createCLAHE', ([], {'clipLimit': '(2.0)', 'tileGridSize': '(4, 4)'}), '(clipLimit=2.0, tileGridSize=(4, 4))\n', (2401, 2437), False, 'import cv2\n'), ((3169, 3288), 'cv2.StereoSGBM_create', 'cv2.StereoSGBM_create', ([], {'numDisparities': '(16 * 6)', 'blockSize': '(15)', 'P1': '(4000)', 'P2': '(15000)', 'mode': 'cv2.STEREO_SGBM_MODE_SGBM_3WAY'}), '(numDisparities=16 * 6, blockSize=15, P1=4000, P2=\n 15000, mode=cv2.STEREO_SGBM_MODE_SGBM_3WAY)\n', (3190, 3288), False, 'import cv2\n'), ((3772, 3800), 'numpy.ones', 'np.ones', (['disparity_map.shape'], {}), '(disparity_map.shape)\n', (3779, 3800), True, 'import numpy as np\n')]
|
# coding: utf-8
import os
import shutil
import pickle
import librosa
import argparse
import pandas as pd
import numpy as np
from glob import glob
from tqdm import tqdm
from PIL import Image
from facenet_pytorch import MTCNN, InceptionResnetV1
import torch
from transformers import BertTokenizer, BertModel
from torch.utils.data import Dataset, DataLoader
class MDataPreLoader(Dataset):
def __init__(self, args):
self.working_dir = args.working_dir
self.df = args.df
self.annotation_dict = {
"Negative": 0,
"Neutral": 1,
"Positive": 2
}
# toolkits path
self.openface2Path = args.openface2Path
# bert
tokenizer_class = BertTokenizer
if args.language == 'cn':
self.pretrainedBertPath = 'pretrained_model/bert_cn'
self.tokenizer = tokenizer_class.from_pretrained('pretrained_model/bert_cn')
else:
self.pretrainedBertPath = 'pretrained_model/bert_en'
self.tokenizer = tokenizer_class.from_pretrained('pretrained_model/bert_en', do_lower_case=True)
def __len__(self):
return len(self.df)
def __getVideoEmbedding(self, video_path, tmp_dir, pool_size=3):
faces_feature_dir = os.path.join(tmp_dir, 'Faces')
os.mkdir(faces_feature_dir)
cmd = self.openface2Path + ' -f ' + video_path + ' -out_dir ' + faces_feature_dir
os.system(cmd)
# read features
features, local_features = [], []
df_path = glob(os.path.join(faces_feature_dir, '*.csv'))
if len(df_path) > 0:
df_path = df_path[0]
df = pd.read_csv(df_path)
for i in range(len(df)):
local_features.append(np.array(df.loc[i][df.columns[5:]]))
if (i + 1) % pool_size == 0:
features.append(np.array(local_features).mean(axis=0))
local_features = []
if len(local_features) != 0:
features.append(np.array(local_features).mean(axis=0))
return np.array(features)
def __getAudioEmbedding(self, video_path, audio_path):
# use ffmpeg to extract audio
cmd = 'ffmpeg -i ' + video_path + ' -f wav -vn ' + \
audio_path + ' -loglevel quiet'
os.system(cmd)
# get features
y, sr = librosa.load(audio_path)
# using librosa to get audio features (f0, mfcc, cqt)
hop_length = 512 # hop_length smaller, seq_len larger
f0 = librosa.feature.zero_crossing_rate(y, hop_length=hop_length).T # (seq_len, 1)
mfcc = librosa.feature.mfcc(y=y, sr=sr, hop_length=hop_length, htk=True).T # (seq_len, 20)
cqt = librosa.feature.chroma_cqt(y=y, sr=sr, hop_length=hop_length).T # (seq_len, 12)
return np.concatenate([f0, mfcc, cqt], axis=-1)
def __getTextEmbedding(self, text):
# directory is fine
tokenizer = BertTokenizer.from_pretrained(self.pretrainedBertPath)
model = BertModel.from_pretrained(self.pretrainedBertPath)
# add_special_tokens will add start and end token
input_ids = torch.tensor([tokenizer.encode(text, add_special_tokens=True)])
with torch.no_grad():
last_hidden_states = model(input_ids)[0] # Models outputs are now tuples
return last_hidden_states.squeeze().numpy()
def __preTextforBert(self, text):
tokens_a = self.tokenizer.tokenize(text,invertable=True)
tokens = ["[CLS]"] + tokens_a + ["[SEP]"]
segment_ids = [0] * len(tokens)
input_ids = self.tokenizer.convert_tokens_to_ids(tokens)
input_mask = [1] * len(input_ids)
input_ids = np.expand_dims(input_ids, 1)
input_mask = np.expand_dims(input_mask, 1)
segment_ids = np.expand_dims(segment_ids, 1)
text_bert = np.concatenate([input_ids, input_mask, segment_ids], axis=1)
return text_bert
def __getitem__(self, index):
tmp_dir = os.path.join(self.working_dir, f'Processed/tmp-{index}')
if not os.path.exists(tmp_dir):
os.makedirs(tmp_dir)
video_id, clip_id, text, label, annotation, mode, _ = self.df.loc[index]
cur_id = video_id + '$_$' + clip_id
# video
video_path = os.path.join(self.working_dir, 'Raw', video_id, clip_id + '.mp4')
embedding_V = self.__getVideoEmbedding(video_path, tmp_dir)
seq_V = embedding_V.shape[0]
# audio
audio_path = os.path.join(tmp_dir, 'tmp.wav')
embedding_A = self.__getAudioEmbedding(video_path, audio_path)
seq_A = embedding_A.shape[0]
# text
embedding_T = self.__getTextEmbedding(text)
text_bert = self.__preTextforBert(text)
seq_T = embedding_T.shape[0]
ret = {
'id': cur_id,
'audio': embedding_A,
'vision': embedding_V,
'raw_text': text,
'text': embedding_T,
'text_bert': text_bert,
'audio_lengths': seq_A,
'vision_lengths': seq_V,
'annotations': annotation,
'classification_labels': self.annotation_dict[annotation],
'regression_labels': label,
'mode': mode
}
# clear tmp dir to save space
shutil.rmtree(tmp_dir)
return ret
class MDataPre():
def __init__(self, args):
self.working_dir = args.working_dir
# padding
self.padding_mode = 'zeros'
self.padding_location = 'back'
def __padding(self, feature, MAX_LEN):
"""
mode:
zero: padding with 0
normal: padding with normal distribution
location: front / back
"""
assert self.padding_mode in ['zeros', 'normal']
assert self.padding_location in ['front', 'back']
length = feature.shape[0]
if length >= MAX_LEN:
return feature[:MAX_LEN, :]
if self.padding_mode == "zeros":
pad = np.zeros([MAX_LEN - length, feature.shape[-1]])
elif self.padding_mode == "normal":
mean, std = feature.mean(), feature.std()
pad = np.random.normal(mean, std, (MAX_LEN-length, feature.shape[1]))
feature = np.concatenate([pad, feature], axis=0) if(self.padding_location == "front") else \
np.concatenate((feature, pad), axis=0)
return feature
def __paddingSequence(self, sequences):
if len(sequences) == 0:
return sequences
feature_dim = sequences[0].shape[-1]
lens = [s.shape[0] for s in sequences]
# confirm length using (mean + std)
final_length = int(np.mean(lens) + 3 * np.std(lens))
# padding sequences to final_length
final_sequence = np.zeros([len(sequences), final_length, feature_dim])
for i, s in enumerate(sequences):
if len(s) != 0:
final_sequence[i] = self.__padding(s, final_length)
return final_sequence
def __collate_fn(self, batch):
ret = {k: [] for k in batch[0].keys()}
for b in batch:
for k,v in b.items():
ret[k].append(v)
return ret
def run(self):
output_path = os.path.join(self.working_dir, 'Processed/features.pkl')
# load last point
if os.path.exists(output_path):
with open(output_path, 'rb') as f:
data = pickle.load(f)
last_row_idx = len(data['id'])
else:
data = {"id": [],
"raw_text": [],
"audio": [],
"vision": [],
"text": [],
"text_bert": [],
"audio_lengths": [],
"vision_lengths": [],
"annotations": [],
"classification_labels": [],
"regression_labels": [],
"mode": []}
last_row_idx = 0
args.df = pd.read_csv(os.path.join(self.working_dir, 'label.csv'), dtype={'clip_id': str, 'video_id': str, 'text': str})
args.df = args.df[last_row_idx:]
dataloader = DataLoader(MDataPreLoader(args),
batch_size=64,
num_workers=8,
shuffle=False,
collate_fn=self.__collate_fn)
isEnd = False
try:
with tqdm(dataloader) as td:
for batch_data in td:
for k, v in batch_data.items():
data[k].extend(v)
isEnd = True
except Exception as e:
print(e)
finally:
try:
if isEnd:
# padding
for item in ['audio', 'vision', 'text', 'text_bert']:
data[item] = self.__paddingSequence(data[item])
# data['mode'] = list(args.df['mode'])
# split train, valid, test
inx_dict = {
mode + '_index': [i for i, v in enumerate(data['mode']) if v == mode]
for mode in ['train', 'valid', 'test']
}
data.pop('mode')
final_data = {k: {} for k in ['train', 'valid', 'test']}
for mode in ['train', 'valid', 'test']:
indexes = inx_dict[mode + '_index']
for item in data.keys():
if isinstance(data[item], list):
final_data[mode][item] = [data[item][v] for v in indexes]
else:
final_data[mode][item] = data[item][indexes]
data = final_data
except Exception as e:
print(e)
finally:
with open(output_path, 'wb') as wf:
pickle.dump(data, wf, protocol = 4)
print('Features are saved in %s!' %output_path)
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('--working_dir', type=str, default='/home/sharing/disk3/dataset/multimodal-sentiment-dataset/StandardDatasets/MOSEI',
help='path to datasets')
parser.add_argument('--language', type=str, default="en",
help='en / cn')
parser.add_argument('--openface2Path', type=str, default="/home/iyuge2/ToolKits/OpenFace/build/bin/FeatureExtraction",
help='path to FeatureExtraction tool in openface2')
return parser.parse_args()
if __name__ == "__main__":
args = parse_args()
dp = MDataPre(args)
dp.run()
|
[
"os.mkdir",
"pickle.dump",
"argparse.ArgumentParser",
"pandas.read_csv",
"numpy.mean",
"pickle.load",
"numpy.random.normal",
"shutil.rmtree",
"torch.no_grad",
"librosa.feature.mfcc",
"os.path.join",
"numpy.std",
"os.path.exists",
"transformers.BertModel.from_pretrained",
"librosa.feature.zero_crossing_rate",
"librosa.feature.chroma_cqt",
"tqdm.tqdm",
"os.system",
"librosa.load",
"transformers.BertTokenizer.from_pretrained",
"numpy.concatenate",
"os.makedirs",
"numpy.zeros",
"numpy.expand_dims",
"numpy.array"
] |
[((10167, 10192), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (10190, 10192), False, 'import argparse\n'), ((1269, 1299), 'os.path.join', 'os.path.join', (['tmp_dir', '"""Faces"""'], {}), "(tmp_dir, 'Faces')\n", (1281, 1299), False, 'import os\n'), ((1308, 1335), 'os.mkdir', 'os.mkdir', (['faces_feature_dir'], {}), '(faces_feature_dir)\n', (1316, 1335), False, 'import os\n'), ((1434, 1448), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (1443, 1448), False, 'import os\n'), ((2079, 2097), 'numpy.array', 'np.array', (['features'], {}), '(features)\n', (2087, 2097), True, 'import numpy as np\n'), ((2313, 2327), 'os.system', 'os.system', (['cmd'], {}), '(cmd)\n', (2322, 2327), False, 'import os\n'), ((2367, 2391), 'librosa.load', 'librosa.load', (['audio_path'], {}), '(audio_path)\n', (2379, 2391), False, 'import librosa\n'), ((2816, 2856), 'numpy.concatenate', 'np.concatenate', (['[f0, mfcc, cqt]'], {'axis': '(-1)'}), '([f0, mfcc, cqt], axis=-1)\n', (2830, 2856), True, 'import numpy as np\n'), ((2950, 3004), 'transformers.BertTokenizer.from_pretrained', 'BertTokenizer.from_pretrained', (['self.pretrainedBertPath'], {}), '(self.pretrainedBertPath)\n', (2979, 3004), False, 'from transformers import BertTokenizer, BertModel\n'), ((3021, 3071), 'transformers.BertModel.from_pretrained', 'BertModel.from_pretrained', (['self.pretrainedBertPath'], {}), '(self.pretrainedBertPath)\n', (3046, 3071), False, 'from transformers import BertTokenizer, BertModel\n'), ((3719, 3747), 'numpy.expand_dims', 'np.expand_dims', (['input_ids', '(1)'], {}), '(input_ids, 1)\n', (3733, 3747), True, 'import numpy as np\n'), ((3769, 3798), 'numpy.expand_dims', 'np.expand_dims', (['input_mask', '(1)'], {}), '(input_mask, 1)\n', (3783, 3798), True, 'import numpy as np\n'), ((3821, 3851), 'numpy.expand_dims', 'np.expand_dims', (['segment_ids', '(1)'], {}), '(segment_ids, 1)\n', (3835, 3851), True, 'import numpy as np\n'), ((3873, 3933), 'numpy.concatenate', 'np.concatenate', (['[input_ids, input_mask, segment_ids]'], {'axis': '(1)'}), '([input_ids, input_mask, segment_ids], axis=1)\n', (3887, 3933), True, 'import numpy as np\n'), ((4013, 4069), 'os.path.join', 'os.path.join', (['self.working_dir', 'f"""Processed/tmp-{index}"""'], {}), "(self.working_dir, f'Processed/tmp-{index}')\n", (4025, 4069), False, 'import os\n'), ((4305, 4370), 'os.path.join', 'os.path.join', (['self.working_dir', '"""Raw"""', 'video_id', "(clip_id + '.mp4')"], {}), "(self.working_dir, 'Raw', video_id, clip_id + '.mp4')\n", (4317, 4370), False, 'import os\n'), ((4513, 4545), 'os.path.join', 'os.path.join', (['tmp_dir', '"""tmp.wav"""'], {}), "(tmp_dir, 'tmp.wav')\n", (4525, 4545), False, 'import os\n'), ((5321, 5343), 'shutil.rmtree', 'shutil.rmtree', (['tmp_dir'], {}), '(tmp_dir)\n', (5334, 5343), False, 'import shutil\n'), ((7284, 7340), 'os.path.join', 'os.path.join', (['self.working_dir', '"""Processed/features.pkl"""'], {}), "(self.working_dir, 'Processed/features.pkl')\n", (7296, 7340), False, 'import os\n'), ((7378, 7405), 'os.path.exists', 'os.path.exists', (['output_path'], {}), '(output_path)\n', (7392, 7405), False, 'import os\n'), ((1538, 1578), 'os.path.join', 'os.path.join', (['faces_feature_dir', '"""*.csv"""'], {}), "(faces_feature_dir, '*.csv')\n", (1550, 1578), False, 'import os\n'), ((1659, 1679), 'pandas.read_csv', 'pd.read_csv', (['df_path'], {}), '(df_path)\n', (1670, 1679), True, 'import pandas as pd\n'), ((2529, 2589), 'librosa.feature.zero_crossing_rate', 'librosa.feature.zero_crossing_rate', (['y'], {'hop_length': 'hop_length'}), '(y, hop_length=hop_length)\n', (2563, 2589), False, 'import librosa\n'), ((2622, 2687), 'librosa.feature.mfcc', 'librosa.feature.mfcc', ([], {'y': 'y', 'sr': 'sr', 'hop_length': 'hop_length', 'htk': '(True)'}), '(y=y, sr=sr, hop_length=hop_length, htk=True)\n', (2642, 2687), False, 'import librosa\n'), ((2720, 2781), 'librosa.feature.chroma_cqt', 'librosa.feature.chroma_cqt', ([], {'y': 'y', 'sr': 'sr', 'hop_length': 'hop_length'}), '(y=y, sr=sr, hop_length=hop_length)\n', (2746, 2781), False, 'import librosa\n'), ((3227, 3242), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (3240, 3242), False, 'import torch\n'), ((4085, 4108), 'os.path.exists', 'os.path.exists', (['tmp_dir'], {}), '(tmp_dir)\n', (4099, 4108), False, 'import os\n'), ((4122, 4142), 'os.makedirs', 'os.makedirs', (['tmp_dir'], {}), '(tmp_dir)\n', (4133, 4142), False, 'import os\n'), ((6040, 6087), 'numpy.zeros', 'np.zeros', (['[MAX_LEN - length, feature.shape[-1]]'], {}), '([MAX_LEN - length, feature.shape[-1]])\n', (6048, 6087), True, 'import numpy as np\n'), ((6287, 6325), 'numpy.concatenate', 'np.concatenate', (['[pad, feature]'], {'axis': '(0)'}), '([pad, feature], axis=0)\n', (6301, 6325), True, 'import numpy as np\n'), ((6388, 6426), 'numpy.concatenate', 'np.concatenate', (['(feature, pad)'], {'axis': '(0)'}), '((feature, pad), axis=0)\n', (6402, 6426), True, 'import numpy as np\n'), ((8061, 8104), 'os.path.join', 'os.path.join', (['self.working_dir', '"""label.csv"""'], {}), "(self.working_dir, 'label.csv')\n", (8073, 8104), False, 'import os\n'), ((6204, 6269), 'numpy.random.normal', 'np.random.normal', (['mean', 'std', '(MAX_LEN - length, feature.shape[1])'], {}), '(mean, std, (MAX_LEN - length, feature.shape[1]))\n', (6220, 6269), True, 'import numpy as np\n'), ((6719, 6732), 'numpy.mean', 'np.mean', (['lens'], {}), '(lens)\n', (6726, 6732), True, 'import numpy as np\n'), ((7477, 7491), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7488, 7491), False, 'import pickle\n'), ((8511, 8527), 'tqdm.tqdm', 'tqdm', (['dataloader'], {}), '(dataloader)\n', (8515, 8527), False, 'from tqdm import tqdm\n'), ((1755, 1790), 'numpy.array', 'np.array', (['df.loc[i][df.columns[5:]]'], {}), '(df.loc[i][df.columns[5:]])\n', (1763, 1790), True, 'import numpy as np\n'), ((6739, 6751), 'numpy.std', 'np.std', (['lens'], {}), '(lens)\n', (6745, 6751), True, 'import numpy as np\n'), ((10034, 10067), 'pickle.dump', 'pickle.dump', (['data', 'wf'], {'protocol': '(4)'}), '(data, wf, protocol=4)\n', (10045, 10067), False, 'import pickle\n'), ((2025, 2049), 'numpy.array', 'np.array', (['local_features'], {}), '(local_features)\n', (2033, 2049), True, 'import numpy as np\n'), ((1873, 1897), 'numpy.array', 'np.array', (['local_features'], {}), '(local_features)\n', (1881, 1897), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 18 18:05:40 2018
Dataset Object
CHECK MAX DISBALANCE OPN REPLICATION FOR MULTICLASS
@author: ereyes
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
class Dataset(object):
"""
Constructor
"""
def __init__(self, data_array, data_label, batch_size):
self.batch_counter = -1
self.batch_counter_eval = -1
self.batch_size = batch_size
self.data_array = data_array
self.data_label = data_label
def _merge_with_dataset(self, array, labels):
self.data_label = np.concatenate((self.data_label, labels))
self.data_array = np.concatenate((self.data_array, array))
def get_batch_images(self):
batch, _ = self.get_batch()
return batch
def _check_first_call(self, counter):
if counter == -1:
return 0
return counter
def get_batch(self):
self.batch_counter = self._check_first_call(self.batch_counter)
if self.batch_counter + self.batch_size < self.data_array.shape[0]:
batch_image = self.data_array[
self.batch_counter:self.batch_counter + self.batch_size,
...]
batch_label = self.data_label[
self.batch_counter:self.batch_counter + self.batch_size,
...]
self.batch_counter += self.batch_size
# print(get_batch.batch_counter)
else:
self.batch_counter = 0
self.shuffle_data()
batch_image = self.data_array[
self.batch_counter:self.batch_counter + self.batch_size,
...]
batch_label = self.data_label[
self.batch_counter:self.batch_counter + self.batch_size,
...]
self.batch_counter += self.batch_size
return batch_image, batch_label
def get_batch_eval(self):
self.batch_counter_eval = self._check_first_call(self.batch_counter_eval)
# print(self.batch_counter_eval)
if self.batch_counter_eval + self.batch_size < self.data_array.shape[0]:
batch_image = self.data_array[
self.batch_counter_eval:self.batch_counter_eval + self.batch_size,
...]
batch_label = self.data_label[
self.batch_counter_eval:self.batch_counter_eval + self.batch_size,
...]
self.batch_counter_eval += self.batch_size
# print(get_batch.batch_counter)
else:
left_samples = self.data_array.shape[0] - self.batch_counter_eval
batch_image = self.data_array[
self.batch_counter_eval:self.batch_counter_eval + left_samples,
...]
batch_label = self.data_label[
self.batch_counter_eval:self.batch_counter_eval + left_samples,
...]
self.batch_counter_eval = 0
return batch_image, batch_label
def shuffle_data(self):
idx = np.arange(self.data_array.shape[0])
np.random.shuffle(idx)
self.data_array = self.data_array[idx, ...]
self.data_label = self.data_label[idx, ...]
# TODO: change both values for uique functions (AVOID CODE REPLICATION)
# TODO: recursively? replicate_data should be?
# TODO: min_lbl_count changes on very iteration, it should stay the same or shuffle
# of replicate_data cannot be
def balance_data_by_replication(self):
max_disbalance = self.get_max_disbalance()
max_lbl_count, min_lbl_count = self.get_max_min_label_count()
max_lbl, min_lbl = self.get_max_min_label()
if max_disbalance == 0:
return
while max_disbalance != 0:
if min_lbl_count > max_disbalance:
self.replicate_data(min_lbl, max_disbalance)
# max_disbalance = 0
else:
self.replicate_data(min_lbl, min_lbl_count)
# max_disbalance -= min_lbl_count
max_disbalance = self.get_max_disbalance() #
self.balance_data_by_replication()
return
def get_max_disbalance(self):
max_label_count, min_label_count = self.get_max_min_label_count()
return max_label_count - min_label_count
def get_max_min_label_count(self):
max_label, min_label = self.get_max_min_label()
max_label_count = np.where(self.data_label == max_label)[0].shape[0]
min_label_count = np.where(self.data_label == min_label)[0].shape[0]
return max_label_count, min_label_count
def get_max_min_label(self):
labels = np.unique(self.data_label)
labels_count = []
for j in range(labels.shape[0]):
label_j_count = np.where(self.data_label == labels[j])[0].shape[0]
labels_count.append(label_j_count)
labels_count = np.array(labels_count)
max_label = labels[np.where(labels_count == np.max(labels_count))[0][0]]
min_label = labels[np.where(labels_count == np.min(labels_count))[0][0]]
return max_label, min_label
def replicate_data(self, label, samples_number):
# print("%i samples replicated of class %i" %(samples_number,label))
label_idx = np.where(self.data_label == label)[0]
# np.random.shuffle(label_idx)
label_idx = label_idx[0:samples_number]
replicated_data_array = self.data_array[label_idx, ...]
self._merge_with_dataset(replicated_data_array, label)
def get_array_from_label(self, label):
label_idx = np.where(self.data_label == label)[0]
return self.data_array[label_idx]
|
[
"numpy.random.shuffle",
"numpy.concatenate",
"numpy.max",
"numpy.where",
"numpy.array",
"numpy.arange",
"numpy.min",
"numpy.unique"
] |
[((2965, 3000), 'numpy.arange', 'np.arange', (['self.data_array.shape[0]'], {}), '(self.data_array.shape[0])\n', (2974, 3000), True, 'import numpy as np\n'), ((3003, 3025), 'numpy.random.shuffle', 'np.random.shuffle', (['idx'], {}), '(idx)\n', (3020, 3025), True, 'import numpy as np\n'), ((4385, 4411), 'numpy.unique', 'np.unique', (['self.data_label'], {}), '(self.data_label)\n', (4394, 4411), True, 'import numpy as np\n'), ((4596, 4618), 'numpy.array', 'np.array', (['labels_count'], {}), '(labels_count)\n', (4604, 4618), True, 'import numpy as np\n'), ((647, 688), 'numpy.concatenate', 'np.concatenate', (['(self.data_label, labels)'], {}), '((self.data_label, labels))\n', (661, 688), True, 'import numpy as np\n'), ((711, 751), 'numpy.concatenate', 'np.concatenate', (['(self.data_array, array)'], {}), '((self.data_array, array))\n', (725, 751), True, 'import numpy as np\n'), ((4936, 4970), 'numpy.where', 'np.where', (['(self.data_label == label)'], {}), '(self.data_label == label)\n', (4944, 4970), True, 'import numpy as np\n'), ((5219, 5253), 'numpy.where', 'np.where', (['(self.data_label == label)'], {}), '(self.data_label == label)\n', (5227, 5253), True, 'import numpy as np\n'), ((4178, 4216), 'numpy.where', 'np.where', (['(self.data_label == max_label)'], {}), '(self.data_label == max_label)\n', (4186, 4216), True, 'import numpy as np\n'), ((4249, 4287), 'numpy.where', 'np.where', (['(self.data_label == min_label)'], {}), '(self.data_label == min_label)\n', (4257, 4287), True, 'import numpy as np\n'), ((4488, 4526), 'numpy.where', 'np.where', (['(self.data_label == labels[j])'], {}), '(self.data_label == labels[j])\n', (4496, 4526), True, 'import numpy as np\n'), ((4666, 4686), 'numpy.max', 'np.max', (['labels_count'], {}), '(labels_count)\n', (4672, 4686), True, 'import numpy as np\n'), ((4741, 4761), 'numpy.min', 'np.min', (['labels_count'], {}), '(labels_count)\n', (4747, 4761), True, 'import numpy as np\n')]
|
import networkx as nx
import matplotlib.pyplot as plt
import pylab
import pickle
import numpy as np
import common
def draw_transition_table(transition_table, cluster_centers, meanscreen, tsne ,color, black_edges=None, red_edges=None, title=None):
G = nx.DiGraph()
edge_colors = []
if red_edges is not None:
for e in red_edges:
G.add_edges_from([e], weight=np.round(transition_table[e[0],e[1]]*100)/100)
edge_colors.append('red')
if black_edges is not None:
if red_edges is not None:
black_edges = list(set(black_edges)-set(red_edges))
for e in black_edges:
G.add_edges_from([e], weight=np.round(transition_table[e[0],e[1]]*100)/100)
edge_colors.append('black')
edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)])
node_labels = {node:node for node in G.nodes()};
counter=0
for key in node_labels.keys():
node_labels[key] = counter
counter+=1
if title is None:
fig = plt.figure('SMDP')
fig.clear()
else:
fig = plt.figure(title)
plt.scatter(tsne[:,0],tsne[:,1],s= np.ones(tsne.shape[0])*2,facecolor=color, edgecolor='none')
pos = cluster_centers[:,0:2]
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,label_pos=0.65,font_size=9)
nx.draw_networkx_labels(G, pos, labels=node_labels,font_color='w',font_size=8)
nx.draw(G,pos,cmap=plt.cm.brg,edge_color=edge_colors)
######Present images on nodes
ax = plt.subplot(111)
plt.axis('off')
trans = ax.transData.transform
trans2 = fig.transFigure.inverted().transform
cut = 1.01
xmax = cut * max(tsne[:,0])
ymax = cut * max(tsne[:,1])
xmin = cut * min(tsne[:,0])
ymin = cut * min(tsne[:,1])
plt.xlim(xmin, xmax)
plt.ylim(ymin, ymax)
h = 70.0
w = 70.0
counter= 0
for node in G:
xx, yy = trans(pos[node])
# axes coordinates
xa, ya = trans2((xx, yy))
# this is the image size
piesize_1 = (300.0 / (h*80))
piesize_2 = (300.0 / (w*80))
p2_2 = piesize_2 / 2
p2_1 = piesize_1 / 2
a = plt.axes([xa - p2_2, ya - p2_1, piesize_2, piesize_1])
G.node[node]['image'] = meanscreen[counter]
#display it
a.imshow(G.node[node]['image'])
a.set_title(node_labels[counter])
#turn off the axis from minor plot
a.axis('off')
counter+=1
plt.draw()
def draw_transition_table_no_image(transition_table,cluster_centers):
G = nx.DiGraph()
G2 = nx.DiGraph()
# print transition_table.sum(axis=1)
transition_table = (transition_table.transpose()/transition_table.sum(axis=1)).transpose()
transition_table[np.isnan(transition_table)]=0
# print(transition_table)
# transition_table = (transition_table.transpose()/transition_table.sum(axis=1)).transpose()
# print transition_table
# print transition_table.sum(axis=0)
# assert(np.all(transition_table.sum(axis=0)!=0))
transition_table[transition_table<0.1]=0
pos = cluster_centers[:,0:2]
m,n = transition_table.shape
for i in range(m):
for j in range(n):
if transition_table[i,j]!=0:
G.add_edges_from([(i, j)], weight=np.round(transition_table[i,j]*100)/100)
G2.add_edges_from([(i, j)], weight=np.round(transition_table[i,j]*100)/100)
values = cluster_centers[:,2]
red_edges = []
edges_sizes =[]
for i in range(n):
trans = transition_table[i,:]
indices = (trans!=0)
index = np.argmax(cluster_centers[indices,2])
counter = 0
for j in range(len(indices)):
if indices[j]:
if counter == index:
ind = j
break
else:
counter+=1
edges_sizes.append(ind)
red_edges.append((i,ind))
# print(red_edges)
# sizes = 3000*cluster_centers[:,3]
sizes = np.ones_like(values)*500
edge_labels=dict([((u,v,),d['weight']) for u,v,d in G.edges(data=True)])
edge_colors = ['black' for edge in G.edges()]
# edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]
node_labels = {node:node for node in G.nodes()};
counter=0
for key in node_labels.keys():
# node_labels[key] = np.round(100*cluster_centers[counter,3])/100
node_labels[key] = counter
counter+=1
fig = plt.figure()
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels,label_pos=0.65,font_size=9)
nx.draw_networkx_labels(G, pos, labels=node_labels,font_color='w',font_size=8)
nx.draw(G,pos, node_color = values,cmap=plt.cm.brg, node_size=np.round(sizes),edge_color=edge_colors,edge_cmap=plt.cm.Reds)
######Present images on nodes
# plt.show()
#
def test():
gamename = 'breakout' #breakout pacman
transition_table = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'transition_table.bin'))
cluster_centers = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'cluster_centers.bin'))
cluster_std = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'cluster_std.bin'))
cluster_med = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'cluster_med.bin'))
cluster_min = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'cluster_min.bin'))
cluster_max = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'cluster_max.bin'))
meanscreen = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'meanscreen.bin'))
cluster_time = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'cluster_time.bin'))
tsne = common.load_hdf5('lowd_activations', 'data/' + 'breakout' + '/'+'120k/')
q_hdf5 = common.load_hdf5('qvals', 'data/' + 'breakout' + '/'+'120k/')
num_frames = 120000
V = np.zeros(shape=(num_frames))
for i in range(0,num_frames):
V[i] = max(q_hdf5[i])
V = V/V.max()
draw_transition_table(transition_table,cluster_centers,meanscreen,cluster_time,tsne,V)
plt.show()
# test()
# stdscreen = pickle.load(file('/home/tom/git/graying_the_box/data/'+gamename+'/120k' + '/knn/' + 'stdscreen.bin'))
# #
# a = 1
# b = 0
# c = 0
# screen = a*meanscreen + c*stdscreen
# facecolor = self.color,
# edgecolor='none',picker=5)
# draw_transition_table_no_image(transition_table,cluster_centers)
# transition_table = pickle.load(file('/home/tom/git/graying_the_box/data/seaquest/120k' + '/knn/' + 'transition_table.bin'))
# transition_table[transition_table<0.1]=0
# cluster_centers = pickle.load(file('/home/tom/git/graying_the_box/data/seaquest/120k' + '/knn/' + 'cluster_centers.bin'))
# pos2 = np.zeros(shape=(cluster_centers.shape[0],2))
# pos2[:,0] = cluster_time[:,0]
# pos2[:,1] = cluster_centers[:,1]
# plt.figure()
# nx.draw_networkx_edge_labels(G2,pos2,edge_labels=edge_labels,label_pos=0.8,font_size=8)
# nx.draw_networkx_labels(G2, pos2, labels=node_labels,font_color='w',font_size=8)
# nx.draw(G2,pos2, node_color = values,cmap=plt.cm.brg, node_size=np.round(sizes),edge_color=edge_colors,edge_cmap=plt.cm.Reds)
|
[
"numpy.argmax",
"matplotlib.pyplot.axes",
"numpy.ones",
"numpy.isnan",
"matplotlib.pyplot.figure",
"networkx.draw_networkx_labels",
"networkx.draw_networkx_edge_labels",
"numpy.round",
"matplotlib.pyplot.draw",
"common.load_hdf5",
"matplotlib.pyplot.show",
"numpy.ones_like",
"matplotlib.pyplot.ylim",
"networkx.draw",
"networkx.DiGraph",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.xlim",
"numpy.zeros",
"matplotlib.pyplot.axis"
] |
[((257, 269), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (267, 269), True, 'import networkx as nx\n'), ((1258, 1353), 'networkx.draw_networkx_edge_labels', 'nx.draw_networkx_edge_labels', (['G', 'pos'], {'edge_labels': 'edge_labels', 'label_pos': '(0.65)', 'font_size': '(9)'}), '(G, pos, edge_labels=edge_labels, label_pos=\n 0.65, font_size=9)\n', (1286, 1353), True, 'import networkx as nx\n'), ((1349, 1434), 'networkx.draw_networkx_labels', 'nx.draw_networkx_labels', (['G', 'pos'], {'labels': 'node_labels', 'font_color': '"""w"""', 'font_size': '(8)'}), "(G, pos, labels=node_labels, font_color='w', font_size=8\n )\n", (1372, 1434), True, 'import networkx as nx\n'), ((1432, 1488), 'networkx.draw', 'nx.draw', (['G', 'pos'], {'cmap': 'plt.cm.brg', 'edge_color': 'edge_colors'}), '(G, pos, cmap=plt.cm.brg, edge_color=edge_colors)\n', (1439, 1488), True, 'import networkx as nx\n'), ((1531, 1547), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(111)'], {}), '(111)\n', (1542, 1547), True, 'import matplotlib.pyplot as plt\n'), ((1552, 1567), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1560, 1567), True, 'import matplotlib.pyplot as plt\n'), ((1800, 1820), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xmin', 'xmax'], {}), '(xmin, xmax)\n', (1808, 1820), True, 'import matplotlib.pyplot as plt\n'), ((1825, 1845), 'matplotlib.pyplot.ylim', 'plt.ylim', (['ymin', 'ymax'], {}), '(ymin, ymax)\n', (1833, 1845), True, 'import matplotlib.pyplot as plt\n'), ((2478, 2488), 'matplotlib.pyplot.draw', 'plt.draw', ([], {}), '()\n', (2486, 2488), True, 'import matplotlib.pyplot as plt\n'), ((2569, 2581), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (2579, 2581), True, 'import networkx as nx\n'), ((2591, 2603), 'networkx.DiGraph', 'nx.DiGraph', ([], {}), '()\n', (2601, 2603), True, 'import networkx as nx\n'), ((4504, 4516), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (4514, 4516), True, 'import matplotlib.pyplot as plt\n'), ((4521, 4616), 'networkx.draw_networkx_edge_labels', 'nx.draw_networkx_edge_labels', (['G', 'pos'], {'edge_labels': 'edge_labels', 'label_pos': '(0.65)', 'font_size': '(9)'}), '(G, pos, edge_labels=edge_labels, label_pos=\n 0.65, font_size=9)\n', (4549, 4616), True, 'import networkx as nx\n'), ((4612, 4697), 'networkx.draw_networkx_labels', 'nx.draw_networkx_labels', (['G', 'pos'], {'labels': 'node_labels', 'font_color': '"""w"""', 'font_size': '(8)'}), "(G, pos, labels=node_labels, font_color='w', font_size=8\n )\n", (4635, 4697), True, 'import networkx as nx\n'), ((5935, 6009), 'common.load_hdf5', 'common.load_hdf5', (['"""lowd_activations"""', "('data/' + 'breakout' + '/' + '120k/')"], {}), "('lowd_activations', 'data/' + 'breakout' + '/' + '120k/')\n", (5951, 6009), False, 'import common\n'), ((6021, 6084), 'common.load_hdf5', 'common.load_hdf5', (['"""qvals"""', "('data/' + 'breakout' + '/' + '120k/')"], {}), "('qvals', 'data/' + 'breakout' + '/' + '120k/')\n", (6037, 6084), False, 'import common\n'), ((6125, 6151), 'numpy.zeros', 'np.zeros', ([], {'shape': 'num_frames'}), '(shape=num_frames)\n', (6133, 6151), True, 'import numpy as np\n'), ((6332, 6342), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6340, 6342), True, 'import matplotlib.pyplot as plt\n'), ((1040, 1058), 'matplotlib.pyplot.figure', 'plt.figure', (['"""SMDP"""'], {}), "('SMDP')\n", (1050, 1058), True, 'import matplotlib.pyplot as plt\n'), ((1103, 1120), 'matplotlib.pyplot.figure', 'plt.figure', (['title'], {}), '(title)\n', (1113, 1120), True, 'import matplotlib.pyplot as plt\n'), ((2181, 2235), 'matplotlib.pyplot.axes', 'plt.axes', (['[xa - p2_2, ya - p2_1, piesize_2, piesize_1]'], {}), '([xa - p2_2, ya - p2_1, piesize_2, piesize_1])\n', (2189, 2235), True, 'import matplotlib.pyplot as plt\n'), ((2763, 2789), 'numpy.isnan', 'np.isnan', (['transition_table'], {}), '(transition_table)\n', (2771, 2789), True, 'import numpy as np\n'), ((3611, 3649), 'numpy.argmax', 'np.argmax', (['cluster_centers[indices, 2]'], {}), '(cluster_centers[indices, 2])\n', (3620, 3649), True, 'import numpy as np\n'), ((4019, 4039), 'numpy.ones_like', 'np.ones_like', (['values'], {}), '(values)\n', (4031, 4039), True, 'import numpy as np\n'), ((4757, 4772), 'numpy.round', 'np.round', (['sizes'], {}), '(sizes)\n', (4765, 4772), True, 'import numpy as np\n'), ((1161, 1183), 'numpy.ones', 'np.ones', (['tsne.shape[0]'], {}), '(tsne.shape[0])\n', (1168, 1183), True, 'import numpy as np\n'), ((391, 435), 'numpy.round', 'np.round', (['(transition_table[e[0], e[1]] * 100)'], {}), '(transition_table[e[0], e[1]] * 100)\n', (399, 435), True, 'import numpy as np\n'), ((679, 723), 'numpy.round', 'np.round', (['(transition_table[e[0], e[1]] * 100)'], {}), '(transition_table[e[0], e[1]] * 100)\n', (687, 723), True, 'import numpy as np\n'), ((3298, 3336), 'numpy.round', 'np.round', (['(transition_table[i, j] * 100)'], {}), '(transition_table[i, j] * 100)\n', (3306, 3336), True, 'import numpy as np\n'), ((3390, 3428), 'numpy.round', 'np.round', (['(transition_table[i, j] * 100)'], {}), '(transition_table[i, j] * 100)\n', (3398, 3428), True, 'import numpy as np\n')]
|
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2020 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# pylint: disable=import-error,no-name-in-module,no-member
from test.utils import LinearOpr
import megengine as mge
import megengine.module as M
import numpy as np
from megengine.core.tensor import dtype
from megengine.core.tensor.dtype import _builtin_quant_dtypes
from megengine.module.quant_dequant import QuantStub
from megengine.quantization.quantize import quantize_qat
from megengine.quantization.utils import create_qparams
from megengine.traced_module.fake_quant import FakeQuantize
from .test_caffe import _test_convert_result
from .tm_utils import get_traced_module
max_err = 1e-6
def get_qat_net(inp_dtype, net, num_inp=1, shape=(1, 16, 32, 32)):
qat_net = quantize_qat(net)
inps = []
for _ in range(num_inp):
data1 = mge.tensor(np.random.random(shape)) * 16
data1 = data1.astype(inp_dtype)
inp1 = mge.tensor(dtype.convert_from_qint8(data1.numpy()))
inp1.qparams.scale = mge.tensor(dtype.get_scale(inp_dtype))
inp1.qparams.dtype_meta = dtype._builtin_quant_dtypes["qint8"]
inps.append(inp1)
return qat_net, inps
def get_qat_inputs_quint8(inp_dtype, num_inp=1, shape=(1, 16, 384, 512)):
inps = []
for _ in range(num_inp):
data1 = mge.tensor(np.random.random(shape)) * 16
data1 = data1.astype(inp_dtype)
inp1 = mge.tensor(dtype.convert_from_quint8(data1.numpy()))
inp1.qparams.scale = mge.tensor(dtype.get_scale(inp_dtype))
inp1.qparams.zero_point = mge.tensor(dtype.get_zero_point(inp_dtype))
inp1.qparams.dtype_meta = dtype._builtin_quant_dtypes["quint8"]
inps.append(inp1)
return inps
def test_linear():
net = LinearOpr()
inp_dtype = dtype.qint8(16.0 / 128.0)
qat_net, inps = get_qat_net(inp_dtype, net, shape=(10, 100))
traced_module, tm_result = get_traced_module(qat_net, inps[0])
inp = inps[0].astype(inp_dtype)
_test_convert_result(inp, traced_module, tm_result, max_err, require_quantize=False)
def test_add():
class ElemwiseOpr(M.Module):
def __init__(self,):
super().__init__()
self.data = np.ones((2, 3, 224, 224)).astype(np.float32)
self.data1 = np.random.random((1, 3, 1, 1)).astype(np.float32)
self.add1 = M.Elemwise("add")
self.add2 = M.Elemwise("add")
self.add3 = M.Elemwise("add")
scale = mge.tensor((16.0 / 128.0))
self.quant_stub = QuantStub()
self.quant_stub.act_fake_quant = FakeQuantize(
_builtin_quant_dtypes["qint8"]
)
self.quant_stub.act_fake_quant.set_qparams(
create_qparams(
dtype_meta=_builtin_quant_dtypes["qint8"],
scale=scale,
zero_point=None,
)
)
self.quant_stub1 = QuantStub()
self.quant_stub1.act_fake_quant = FakeQuantize(
_builtin_quant_dtypes["qint8"]
)
self.quant_stub1.act_fake_quant.set_qparams(
create_qparams(
dtype_meta=_builtin_quant_dtypes["qint8"],
scale=scale,
zero_point=None,
)
)
def forward(self, a):
n = self.quant_stub(mge.tensor(np.float32(10)))
data1 = self.quant_stub1(mge.tensor(self.data1))
x = self.add1(a, n)
y = self.add2(a, data1)
z = self.add3(x, y)
return z
net = ElemwiseOpr()
inp_dtype = dtype.qint8(16.0 / 128.0)
qat_net, inps = get_qat_net(inp_dtype, net, shape=(1, 3, 1, 1))
traced_module, tm_result = get_traced_module(qat_net, inps[0])
print(traced_module.flatten().graph)
inp = inps[0].astype(inp_dtype)
_test_convert_result(
inp,
traced_module,
tm_result,
max_err,
require_quantize=False,
split_conv_relu=True,
)
def test_det_model():
net = mge.load("models_fire_det.fix_batch.fuse_scale_cpu.pkl")
inp_dtype = dtype.qint8(16.0 / 128.0)
qat_net, inps = get_qat_net(inp_dtype, net, shape=(1, 3, 512, 512))
traced_module, tm_result = get_traced_module(qat_net, inps[0])
inp = inps[0].astype(inp_dtype)
_test_convert_result(inp, traced_module, tm_result, max_err, require_quantize=False)
def test_snpe_model_8f():
model = "8w16f_backbone.tm"
net = mge.load(model)
print(net.flatten().graph)
inp_dtype = dtype.quint8(16.0 / 128.0, 128)
inps = get_qat_inputs_quint8(inp_dtype, num_inp=2, shape=(1, 16, 384, 512))
tm_result = dict(zip(net.graph.outputs, net(*inps)))
_test_convert_result(
inps,
net,
tm_result,
max_err,
input_data_type="quint8",
input_scales=inps[0].qparams.scale,
input_zero_points=inps[0].qparams.zero_point,
require_quantize=False,
param_fake_quant=True,
split_conv_relu=True,
input_name=["inp", "prev"],
)
|
[
"megengine.core.tensor.dtype.get_scale",
"megengine.quantization.quantize.quantize_qat",
"megengine.tensor",
"numpy.float32",
"numpy.ones",
"megengine.core.tensor.dtype.get_zero_point",
"megengine.core.tensor.dtype.qint8",
"test.utils.LinearOpr",
"megengine.core.tensor.dtype.quint8",
"megengine.module.quant_dequant.QuantStub",
"numpy.random.random",
"megengine.quantization.utils.create_qparams",
"megengine.module.Elemwise",
"megengine.traced_module.fake_quant.FakeQuantize",
"megengine.load"
] |
[((1033, 1050), 'megengine.quantization.quantize.quantize_qat', 'quantize_qat', (['net'], {}), '(net)\n', (1045, 1050), False, 'from megengine.quantization.quantize import quantize_qat\n'), ((2023, 2034), 'test.utils.LinearOpr', 'LinearOpr', ([], {}), '()\n', (2032, 2034), False, 'from test.utils import LinearOpr\n'), ((2051, 2076), 'megengine.core.tensor.dtype.qint8', 'dtype.qint8', (['(16.0 / 128.0)'], {}), '(16.0 / 128.0)\n', (2062, 2076), False, 'from megengine.core.tensor import dtype\n'), ((3910, 3935), 'megengine.core.tensor.dtype.qint8', 'dtype.qint8', (['(16.0 / 128.0)'], {}), '(16.0 / 128.0)\n', (3921, 3935), False, 'from megengine.core.tensor import dtype\n'), ((4348, 4404), 'megengine.load', 'mge.load', (['"""models_fire_det.fix_batch.fuse_scale_cpu.pkl"""'], {}), "('models_fire_det.fix_batch.fuse_scale_cpu.pkl')\n", (4356, 4404), True, 'import megengine as mge\n'), ((4421, 4446), 'megengine.core.tensor.dtype.qint8', 'dtype.qint8', (['(16.0 / 128.0)'], {}), '(16.0 / 128.0)\n', (4432, 4446), False, 'from megengine.core.tensor import dtype\n'), ((4781, 4796), 'megengine.load', 'mge.load', (['model'], {}), '(model)\n', (4789, 4796), True, 'import megengine as mge\n'), ((4844, 4875), 'megengine.core.tensor.dtype.quint8', 'dtype.quint8', (['(16.0 / 128.0)', '(128)'], {}), '(16.0 / 128.0, 128)\n', (4856, 4875), False, 'from megengine.core.tensor import dtype\n'), ((1298, 1324), 'megengine.core.tensor.dtype.get_scale', 'dtype.get_scale', (['inp_dtype'], {}), '(inp_dtype)\n', (1313, 1324), False, 'from megengine.core.tensor import dtype\n'), ((1772, 1798), 'megengine.core.tensor.dtype.get_scale', 'dtype.get_scale', (['inp_dtype'], {}), '(inp_dtype)\n', (1787, 1798), False, 'from megengine.core.tensor import dtype\n'), ((1845, 1876), 'megengine.core.tensor.dtype.get_zero_point', 'dtype.get_zero_point', (['inp_dtype'], {}), '(inp_dtype)\n', (1865, 1876), False, 'from megengine.core.tensor import dtype\n'), ((2613, 2630), 'megengine.module.Elemwise', 'M.Elemwise', (['"""add"""'], {}), "('add')\n", (2623, 2630), True, 'import megengine.module as M\n'), ((2655, 2672), 'megengine.module.Elemwise', 'M.Elemwise', (['"""add"""'], {}), "('add')\n", (2665, 2672), True, 'import megengine.module as M\n'), ((2697, 2714), 'megengine.module.Elemwise', 'M.Elemwise', (['"""add"""'], {}), "('add')\n", (2707, 2714), True, 'import megengine.module as M\n'), ((2736, 2760), 'megengine.tensor', 'mge.tensor', (['(16.0 / 128.0)'], {}), '(16.0 / 128.0)\n', (2746, 2760), True, 'import megengine as mge\n'), ((2793, 2804), 'megengine.module.quant_dequant.QuantStub', 'QuantStub', ([], {}), '()\n', (2802, 2804), False, 'from megengine.module.quant_dequant import QuantStub\n'), ((2850, 2894), 'megengine.traced_module.fake_quant.FakeQuantize', 'FakeQuantize', (["_builtin_quant_dtypes['qint8']"], {}), "(_builtin_quant_dtypes['qint8'])\n", (2862, 2894), False, 'from megengine.traced_module.fake_quant import FakeQuantize\n'), ((3209, 3220), 'megengine.module.quant_dequant.QuantStub', 'QuantStub', ([], {}), '()\n', (3218, 3220), False, 'from megengine.module.quant_dequant import QuantStub\n'), ((3267, 3311), 'megengine.traced_module.fake_quant.FakeQuantize', 'FakeQuantize', (["_builtin_quant_dtypes['qint8']"], {}), "(_builtin_quant_dtypes['qint8'])\n", (3279, 3311), False, 'from megengine.traced_module.fake_quant import FakeQuantize\n'), ((1121, 1144), 'numpy.random.random', 'np.random.random', (['shape'], {}), '(shape)\n', (1137, 1144), True, 'import numpy as np\n'), ((1594, 1617), 'numpy.random.random', 'np.random.random', (['shape'], {}), '(shape)\n', (1610, 1617), True, 'import numpy as np\n'), ((2997, 3088), 'megengine.quantization.utils.create_qparams', 'create_qparams', ([], {'dtype_meta': "_builtin_quant_dtypes['qint8']", 'scale': 'scale', 'zero_point': 'None'}), "(dtype_meta=_builtin_quant_dtypes['qint8'], scale=scale,\n zero_point=None)\n", (3011, 3088), False, 'from megengine.quantization.utils import create_qparams\n'), ((3415, 3506), 'megengine.quantization.utils.create_qparams', 'create_qparams', ([], {'dtype_meta': "_builtin_quant_dtypes['qint8']", 'scale': 'scale', 'zero_point': 'None'}), "(dtype_meta=_builtin_quant_dtypes['qint8'], scale=scale,\n zero_point=None)\n", (3429, 3506), False, 'from megengine.quantization.utils import create_qparams\n'), ((3724, 3746), 'megengine.tensor', 'mge.tensor', (['self.data1'], {}), '(self.data1)\n', (3734, 3746), True, 'import megengine as mge\n'), ((2469, 2494), 'numpy.ones', 'np.ones', (['(2, 3, 224, 224)'], {}), '((2, 3, 224, 224))\n', (2476, 2494), True, 'import numpy as np\n'), ((2539, 2569), 'numpy.random.random', 'np.random.random', (['(1, 3, 1, 1)'], {}), '((1, 3, 1, 1))\n', (2555, 2569), True, 'import numpy as np\n'), ((3670, 3684), 'numpy.float32', 'np.float32', (['(10)'], {}), '(10)\n', (3680, 3684), True, 'import numpy as np\n')]
|
# System
import os
import sys
from pprint import pprint as pp
import argparse
import logging
import multiprocessing as mp
from functools import partial
from time import time
import shutil
# Externals
import yaml
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from torch_scatter import scatter_add
import scipy as sp
from sklearn.cluster import DBSCAN
# Locals
# sys.path.append('GraphLearning/src')
from GraphLearning.src.trainers import get_trainer
from Seeding.src.utils.data_utils import load_config_dir, load_summaries, get_seed_data_loader
if torch.cuda.is_available():
DEVICE='cuda'
else:
DEVICE='cpu'
def load_triplets(test_loader, filelist):
graph_dataset = test_loader.dataset
graph_indices = np.array([g.i for g in graph_dataset])
filelist = np.array(filelist)
graph_names = filelist[graph_indices]
return graph_dataset, graph_names
def save_triplet_hitlist(triplet_data, threshold, output_dir):
e, graph_name, o = triplet_data
g_ID = np.load(graph_name[:-4] + "_ID.npz", allow_pickle=True)["I"]
triplet_preds = np.hstack([g_ID[:,e[0,o > threshold]], g_ID[:,e[1,o > threshold]]]).T
# triplet_IDs = np.hstack([g_ID[:,e[0,:]].T, g_ID[:,e[1,:]].T])[:,[0,1,3]]
# triplet_preds = triplet_IDs[o > threshold]
o_preds = np.hstack([o[o > threshold], o[o > threshold]]).T
# print(triplet_preds.shape, o_preds.shape)
triplet_list = np.c_[triplet_preds.astype(np.int64), o_preds]
filename = os.path.join(output_dir, os.path.splitext(os.path.basename(graph_name))[0])
np.save(filename, triplet_list)
def get_edge_scores(load_path, triplet_artifacts, n_tasks, task):
"""
- Takes config info for triplet training dataset (different from doublet training dataset),
- Runs the dataset through the trained doublet network,
- Returns edge scores with same indices as edge network input
"""
# Load configs
config = load_config_dir(triplet_artifacts)
logging.info('Inferring triplets on model configuration:')
logging.info(config)
# Find the best epoch
summaries = load_summaries(config)
best_idx = summaries.valid_loss.idxmin()
summaries.loc[[best_idx]]
# Build the trainer and load best checkpoint
task_gpu = 0 if DEVICE=='cuda' else None
trainer = get_trainer(output_dir=config['output_dir'], gpu=task_gpu, **config['trainer'])
trainer.build_model(optimizer_config=config['optimizer'], **config['model'])
best_epoch = summaries.epoch.loc[best_idx]
trainer.load_checkpoint(checkpoint_id=best_epoch)
logging.info("With weight system:")
logging.info(trainer.model)
logging.info("On device:")
logging.info(trainer.device)
# Load the test dataset
test_loader, filelist = get_seed_data_loader(load_path, n_tasks, task)
# Apply the model
test_preds, test_targets = trainer.device_predict(test_loader)
print("Graph prediction complete")
#GET Hit ID data here and GRAPH NAMES
graph_dataset, graph_names = load_triplets(test_loader, filelist)
return test_preds, graph_dataset, graph_names
def combine_event(event_name, split_names):
""" Concatenates the triplet list of each subgraph """
total_triplets = np.empty((0,3))
for i in np.where(split_names[:,0] == event_name)[0]:
triplet_list = np.load(str(split_names[i,0]) + "_" + str(split_names[i,1]), allow_pickle=True)
total_triplets = np.append(total_triplets, triplet_list, axis=0)
return total_triplets
def cluster(e_csr_bi, epsilon):
clustering = DBSCAN(eps=epsilon, metric="precomputed", min_samples=1).fit_predict(e_csr_bi)
track_labels = np.vstack([np.unique(e_csr_bi.tocoo().row), clustering[np.unique(e_csr_bi.tocoo().row)]])
track_labels = pd.DataFrame(track_labels.T)
track_labels.columns = ["hit_id", "track_id"]
# Add TrackML scoring here and print
return track_labels
def convert_to_bidirectional(e_csr):
# Invert to treat score as an inverse distance
e_csr.data = 1 - e_csr.data
e_csr_bi = sp.sparse.coo_matrix((np.hstack([e_csr.tocoo().data, e_csr.tocoo().data]),
np.hstack([np.vstack([e_csr.tocoo().row, e_csr.tocoo().col]),
np.vstack([e_csr.tocoo().col, e_csr.tocoo().row])])))
return e_csr_bi
def triplets_to_doublets(triplet_edges, triplet_scores, label_cut):
e_doublet_coo = sp.sparse.coo_matrix((triplet_edges.max()+1, triplet_edges.max()+1))
dok = sp.sparse.dok_matrix((e_doublet_coo.shape), dtype=e_doublet_coo.dtype)
dok._update(zip(zip(triplet_edges[:,0], triplet_edges[:,1]), [1]*triplet_edges.shape[0])) # Could be converted to actual scores
e_csr = dok.tocsr()
return e_csr
def save_labels(track_labels, event_name, output_dir):
label_filename = os.path.join(output_dir, event_name)
np.save(label_filename, track_labels)
# def recombine_triplet_graphs(split_names, graph_dataset, test_preds, n_phi_segments):
# # for file_base in np.unique(split_names[:,0]):
# # Needs to load data as in combine_event()
# total_e = np.empty((2,0), dtype="int64")
# total_o = np.empty(0, dtype="float64")
# total_hid = np.empty((2,0), dtype="int64")
# total_pid = np.empty((1,0), dtype="int64")
# total_X = np.empty((0,7), dtype="float64")
# for i in np.where(split_names[:,0] == file_base)[0]:
# e_trip = graph_dataset[i].edge_index.numpy()
# scores = test_preds[i].numpy()
# hid = np.load(split_names[i,0] + "_" + split_names[i,1] + "_ID.npz", allow_pickle=True)["I"]
# pid = np.load(split_names[i,0] + "_" + split_names[i,1] + "_ID.npz", allow_pickle=True)["pid"]
# total_e = np.append(total_e, e_trip + total_hid.shape[1], axis=1)
# total_o = np.append(total_o, scores)
# total_hid = np.append(total_hid, hid, axis=1)
# total_pid = np.append(total_pid, pid)
# X = graph_dataset[i].x.numpy()
# X[:,1] = X[:,1] - n_phi_segments + 1 + delta*int(split_names[i,1]) #Is this right??
# X[X[:,1] < (-n_phi_segments), 1] += 2*n_phi_segments
# X[X[:,1] > n_phi_segments, 1] -= 2*n_phi_segments
# X[:,1] = X[:,1] / n_phi_segments # Renormalise
# X[:,4] = X[:,4] - n_phi_segments + 1 + delta*int(split_names[i,1]) #Is this right??
# X[X[:,4] < (-n_phi_segments), 1] += 2*n_phi_segments
# X[X[:,4] > n_phi_segments, 1] -= 2*n_phi_segments
# X[:,4] = X[:,4] / n_phi_segments # Renormalise
# total_X = np.vstack([total_X, graph_dataset[i].x.numpy()])
# return total_X, total_e, total_o, total_hid, total_pid
def process_event(event_name, split_names, output_dir, label_cut, epsilon):
# Recombine triplet graphs by loading all files in event
total_triplets = combine_event(event_name, split_names)
triplet_edges = total_triplets[:,:2].T.astype(dtype='int64')
triplet_scores = total_triplets[:,2].T
# Convert triplets to doublets
e_csr = triplets_to_doublets(triplet_edges, triplet_scores, label_cut)
# Cluster and produce track list
e_csr_bi = convert_to_bidirectional(e_csr)
# Save track labels
track_labels = cluster(e_csr_bi, epsilon)
save_labels(track_labels, event_name, output_dir)
def process_data(save_path, load_path, triplet_artifacts, label_threshold, epsilon, n_tasks, task):
logging.info("Running inference on triplet graphs")
# Calculate edge scores from best doublet model checkpoint
edge_scores, graph_dataset, graph_names = get_edge_scores(load_path, triplet_artifacts, n_tasks, task)
triplet_data = np.array([[gi.edge_index.numpy(), graph_name, oi.numpy()] for gi, graph_name, oi in zip(graph_dataset, graph_names, edge_scores)])
logging.info("Inference complete")
# SAVE TRIPLET HITLIST
temp_dir = os.path.join(save_path, "temp")
if not os.path.exists(temp_dir):
os.makedirs(temp_dir, exist_ok=True)
with mp.Pool(processes=None) as pool:
process_fn = partial(save_triplet_hitlist, threshold=label_threshold, output_dir=temp_dir)
pool.map(process_fn, triplet_data)
logging.info("All files saved")
if task == 0:
# IS THIS THE CORRECT LENGTH???
triplet_data_length = len(triplet_data)
while(len(os.listdir(temp_dir)) < triplet_data_length):
print("Waiting")
time.sleep(10) # Want to wait until all files a
# RELOAD FILELIST AND SPLIT
filelist = os.listdir(temp_dir)
split_names = np.array([[os.path.join(temp_dir,file[:-6]), file[-5:]] for file in filelist])
event_names = np.unique(split_names[:,0])
with mp.Pool(processes=None) as pool:
process_fn = partial(process_event, split_names = split_names, output_dir=save_path, label_cut=label_threshold, epsilon=epsilon)
pool.map(process_fn, event_names)
if os.path.exists(temp_dir):
shutil.rmtree(temp_dir, ignore_errors=False)
def main(args, force=False):
""" Main function """
tic = time()
save_path = os.path.join(args.data_storage_path, 'labels')
load_path = os.path.join(args.data_storage_path, 'triplet_graphs')
artifact_path = os.path.join(args.artifact_storage_path, 'triplet_gnn')
os.makedirs(save_path, exist_ok=True)
# Setup logging
log_format = '%(asctime)s %(levelname)s %(message)s'
log_level = logging.DEBUG #if args.verbose else logging.INFO
logging.basicConfig(level=log_level, format=log_format)
logging.info('Initialising')
process_data(save_path, load_path, artifact_path, args.label_threshold, args.epsilon, args.n_tasks, args.task)
logging.info('Processing finished')
if __name__ == '__main__':
main()
|
[
"numpy.load",
"numpy.empty",
"GraphLearning.src.trainers.get_trainer",
"shutil.rmtree",
"os.path.join",
"numpy.unique",
"sklearn.cluster.DBSCAN",
"pandas.DataFrame",
"os.path.exists",
"numpy.append",
"scipy.sparse.dok_matrix",
"Seeding.src.utils.data_utils.load_summaries",
"functools.partial",
"numpy.save",
"os.path.basename",
"numpy.hstack",
"torch.cuda.is_available",
"multiprocessing.Pool",
"os.listdir",
"Seeding.src.utils.data_utils.load_config_dir",
"os.makedirs",
"logging.basicConfig",
"Seeding.src.utils.data_utils.get_seed_data_loader",
"time.time",
"logging.info",
"numpy.where",
"numpy.array",
"time.time.sleep"
] |
[((579, 604), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (602, 604), False, 'import torch\n'), ((755, 793), 'numpy.array', 'np.array', (['[g.i for g in graph_dataset]'], {}), '([g.i for g in graph_dataset])\n', (763, 793), True, 'import numpy as np\n'), ((809, 827), 'numpy.array', 'np.array', (['filelist'], {}), '(filelist)\n', (817, 827), True, 'import numpy as np\n'), ((1607, 1638), 'numpy.save', 'np.save', (['filename', 'triplet_list'], {}), '(filename, triplet_list)\n', (1614, 1638), True, 'import numpy as np\n'), ((1977, 2011), 'Seeding.src.utils.data_utils.load_config_dir', 'load_config_dir', (['triplet_artifacts'], {}), '(triplet_artifacts)\n', (1992, 2011), False, 'from Seeding.src.utils.data_utils import load_config_dir, load_summaries, get_seed_data_loader\n'), ((2016, 2074), 'logging.info', 'logging.info', (['"""Inferring triplets on model configuration:"""'], {}), "('Inferring triplets on model configuration:')\n", (2028, 2074), False, 'import logging\n'), ((2079, 2099), 'logging.info', 'logging.info', (['config'], {}), '(config)\n', (2091, 2099), False, 'import logging\n'), ((2143, 2165), 'Seeding.src.utils.data_utils.load_summaries', 'load_summaries', (['config'], {}), '(config)\n', (2157, 2165), False, 'from Seeding.src.utils.data_utils import load_config_dir, load_summaries, get_seed_data_loader\n'), ((2350, 2429), 'GraphLearning.src.trainers.get_trainer', 'get_trainer', ([], {'output_dir': "config['output_dir']", 'gpu': 'task_gpu'}), "(output_dir=config['output_dir'], gpu=task_gpu, **config['trainer'])\n", (2361, 2429), False, 'from GraphLearning.src.trainers import get_trainer\n'), ((2618, 2653), 'logging.info', 'logging.info', (['"""With weight system:"""'], {}), "('With weight system:')\n", (2630, 2653), False, 'import logging\n'), ((2658, 2685), 'logging.info', 'logging.info', (['trainer.model'], {}), '(trainer.model)\n', (2670, 2685), False, 'import logging\n'), ((2690, 2716), 'logging.info', 'logging.info', (['"""On device:"""'], {}), "('On device:')\n", (2702, 2716), False, 'import logging\n'), ((2721, 2749), 'logging.info', 'logging.info', (['trainer.device'], {}), '(trainer.device)\n', (2733, 2749), False, 'import logging\n'), ((2808, 2854), 'Seeding.src.utils.data_utils.get_seed_data_loader', 'get_seed_data_loader', (['load_path', 'n_tasks', 'task'], {}), '(load_path, n_tasks, task)\n', (2828, 2854), False, 'from Seeding.src.utils.data_utils import load_config_dir, load_summaries, get_seed_data_loader\n'), ((3283, 3299), 'numpy.empty', 'np.empty', (['(0, 3)'], {}), '((0, 3))\n', (3291, 3299), True, 'import numpy as np\n'), ((3830, 3858), 'pandas.DataFrame', 'pd.DataFrame', (['track_labels.T'], {}), '(track_labels.T)\n', (3842, 3858), True, 'import pandas as pd\n'), ((4685, 4753), 'scipy.sparse.dok_matrix', 'sp.sparse.dok_matrix', (['e_doublet_coo.shape'], {'dtype': 'e_doublet_coo.dtype'}), '(e_doublet_coo.shape, dtype=e_doublet_coo.dtype)\n', (4705, 4753), True, 'import scipy as sp\n'), ((5016, 5052), 'os.path.join', 'os.path.join', (['output_dir', 'event_name'], {}), '(output_dir, event_name)\n', (5028, 5052), False, 'import os\n'), ((5062, 5099), 'numpy.save', 'np.save', (['label_filename', 'track_labels'], {}), '(label_filename, track_labels)\n', (5069, 5099), True, 'import numpy as np\n'), ((7632, 7683), 'logging.info', 'logging.info', (['"""Running inference on triplet graphs"""'], {}), "('Running inference on triplet graphs')\n", (7644, 7683), False, 'import logging\n'), ((8019, 8053), 'logging.info', 'logging.info', (['"""Inference complete"""'], {}), "('Inference complete')\n", (8031, 8053), False, 'import logging\n'), ((8105, 8136), 'os.path.join', 'os.path.join', (['save_path', '"""temp"""'], {}), "(save_path, 'temp')\n", (8117, 8136), False, 'import os\n'), ((8412, 8443), 'logging.info', 'logging.info', (['"""All files saved"""'], {}), "('All files saved')\n", (8424, 8443), False, 'import logging\n'), ((9384, 9390), 'time.time', 'time', ([], {}), '()\n', (9388, 9390), False, 'from time import time\n'), ((9412, 9458), 'os.path.join', 'os.path.join', (['args.data_storage_path', '"""labels"""'], {}), "(args.data_storage_path, 'labels')\n", (9424, 9458), False, 'import os\n'), ((9475, 9529), 'os.path.join', 'os.path.join', (['args.data_storage_path', '"""triplet_graphs"""'], {}), "(args.data_storage_path, 'triplet_graphs')\n", (9487, 9529), False, 'import os\n'), ((9557, 9612), 'os.path.join', 'os.path.join', (['args.artifact_storage_path', '"""triplet_gnn"""'], {}), "(args.artifact_storage_path, 'triplet_gnn')\n", (9569, 9612), False, 'import os\n'), ((9618, 9655), 'os.makedirs', 'os.makedirs', (['save_path'], {'exist_ok': '(True)'}), '(save_path, exist_ok=True)\n', (9629, 9655), False, 'import os\n'), ((9807, 9862), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'log_level', 'format': 'log_format'}), '(level=log_level, format=log_format)\n', (9826, 9862), False, 'import logging\n'), ((9867, 9895), 'logging.info', 'logging.info', (['"""Initialising"""'], {}), "('Initialising')\n", (9879, 9895), False, 'import logging\n'), ((10018, 10053), 'logging.info', 'logging.info', (['"""Processing finished"""'], {}), "('Processing finished')\n", (10030, 10053), False, 'import logging\n'), ((1034, 1089), 'numpy.load', 'np.load', (["(graph_name[:-4] + '_ID.npz')"], {'allow_pickle': '(True)'}), "(graph_name[:-4] + '_ID.npz', allow_pickle=True)\n", (1041, 1089), True, 'import numpy as np\n'), ((1120, 1191), 'numpy.hstack', 'np.hstack', (['[g_ID[:, e[0, o > threshold]], g_ID[:, e[1, o > threshold]]]'], {}), '([g_ID[:, e[0, o > threshold]], g_ID[:, e[1, o > threshold]]])\n', (1129, 1191), True, 'import numpy as np\n'), ((1337, 1384), 'numpy.hstack', 'np.hstack', (['[o[o > threshold], o[o > threshold]]'], {}), '([o[o > threshold], o[o > threshold]])\n', (1346, 1384), True, 'import numpy as np\n'), ((3312, 3353), 'numpy.where', 'np.where', (['(split_names[:, 0] == event_name)'], {}), '(split_names[:, 0] == event_name)\n', (3320, 3353), True, 'import numpy as np\n'), ((3485, 3532), 'numpy.append', 'np.append', (['total_triplets', 'triplet_list'], {'axis': '(0)'}), '(total_triplets, triplet_list, axis=0)\n', (3494, 3532), True, 'import numpy as np\n'), ((8148, 8172), 'os.path.exists', 'os.path.exists', (['temp_dir'], {}), '(temp_dir)\n', (8162, 8172), False, 'import os\n'), ((8182, 8218), 'os.makedirs', 'os.makedirs', (['temp_dir'], {'exist_ok': '(True)'}), '(temp_dir, exist_ok=True)\n', (8193, 8218), False, 'import os\n'), ((8228, 8251), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': 'None'}), '(processes=None)\n', (8235, 8251), True, 'import multiprocessing as mp\n'), ((8282, 8359), 'functools.partial', 'partial', (['save_triplet_hitlist'], {'threshold': 'label_threshold', 'output_dir': 'temp_dir'}), '(save_triplet_hitlist, threshold=label_threshold, output_dir=temp_dir)\n', (8289, 8359), False, 'from functools import partial\n'), ((8787, 8807), 'os.listdir', 'os.listdir', (['temp_dir'], {}), '(temp_dir)\n', (8797, 8807), False, 'import os\n'), ((8935, 8963), 'numpy.unique', 'np.unique', (['split_names[:, 0]'], {}), '(split_names[:, 0])\n', (8944, 8963), True, 'import numpy as np\n'), ((9221, 9245), 'os.path.exists', 'os.path.exists', (['temp_dir'], {}), '(temp_dir)\n', (9235, 9245), False, 'import os\n'), ((3623, 3679), 'sklearn.cluster.DBSCAN', 'DBSCAN', ([], {'eps': 'epsilon', 'metric': '"""precomputed"""', 'min_samples': '(1)'}), "(eps=epsilon, metric='precomputed', min_samples=1)\n", (3629, 3679), False, 'from sklearn.cluster import DBSCAN\n'), ((8675, 8689), 'time.time.sleep', 'time.sleep', (['(10)'], {}), '(10)\n', (8685, 8689), False, 'from time import time\n'), ((8977, 9000), 'multiprocessing.Pool', 'mp.Pool', ([], {'processes': 'None'}), '(processes=None)\n', (8984, 9000), True, 'import multiprocessing as mp\n'), ((9035, 9152), 'functools.partial', 'partial', (['process_event'], {'split_names': 'split_names', 'output_dir': 'save_path', 'label_cut': 'label_threshold', 'epsilon': 'epsilon'}), '(process_event, split_names=split_names, output_dir=save_path,\n label_cut=label_threshold, epsilon=epsilon)\n', (9042, 9152), False, 'from functools import partial\n'), ((9259, 9303), 'shutil.rmtree', 'shutil.rmtree', (['temp_dir'], {'ignore_errors': '(False)'}), '(temp_dir, ignore_errors=False)\n', (9272, 9303), False, 'import shutil\n'), ((1569, 1597), 'os.path.basename', 'os.path.basename', (['graph_name'], {}), '(graph_name)\n', (1585, 1597), False, 'import os\n'), ((8588, 8608), 'os.listdir', 'os.listdir', (['temp_dir'], {}), '(temp_dir)\n', (8598, 8608), False, 'import os\n'), ((8841, 8874), 'os.path.join', 'os.path.join', (['temp_dir', 'file[:-6]'], {}), '(temp_dir, file[:-6])\n', (8853, 8874), False, 'import os\n')]
|
# Import required stuff
from cvxpy import *
import numpy as np
import matplotlib.pyplot as plt
# In this problem, we need both y.txt and beta.txt, so read them from input files.
# Please note that the path has to be changed accordingly before running.
with open('/home/akilesh/Desktop/Akilesh_opt/y.txt') as f:
y = []
for line in f:
line = line.split() # to deal with blank
if line: # lines (ie skip them)
line = [float(i) for i in line]
y.append(line)
with open('/home/akilesh/Desktop/Akilesh_opt/beta0.txt') as f:
betaorg = []
for line in f:
line = line.split() # to deal with blank
if line: # lines (ie skip them)
line = [float(i) for i in line]
betaorg.append(line)
# Define 100 logarithmically spaced values from 10^1 to 10^-2.
lvals = np.logspace(-2, 1, 100)
mseList = [] # List for storing MSEs as we vary the lambda.
changepointsList = [] # List for storing changepoint as we vary the lambda.
lvalsList = [] # List for storing beta computed as we vary the lambda.
for val in lvals:
# As in prev problem, beta is the variable.
beta = Variable(1, 100)
error = sum_squares(y - beta)
error = error/2
obj = Minimize(error + val*tv(beta))
prob = Problem(obj)
prob.solve()
# to compute mse for a particular lambda.
# Threshold is defined as 10^-8.
mse = 0
thresh = 0.00000001
changepoints = 0
# Iterate over points
for i in range(0, 100):
req = (beta[i].value - betaorg[i][0])
a = abs(req).value
# Compute MSE.
mse = mse + req ** 2
# If abs. value is greater than thresh
if(a > thresh):
changepoints = changepoints + 1
# Appending stuff to corresponding list
mse = mse / 100
mseList.append(mse)
changepointsList.append(changepoints)
lvalsList.append(val)
#print(mseList)
# For plotting - mse vs lambda.
plt.subplot(211)
plt.plot(lvalsList, mseList)
plt.xlabel('lambda ')
plt.ylabel('mse')
plt.title(' mse vs lambda ')
# For plotting - changepoints vs lambda.
plt.subplot(212)
plt.plot(lvalsList, changepointsList)
plt.xlabel('lambda ')
plt.ylabel(' changepoints')
plt.title(' changepoints vs lambda ')
plt.tight_layout()
plt.show()
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.logspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.tight_layout"
] |
[((865, 888), 'numpy.logspace', 'np.logspace', (['(-2)', '(1)', '(100)'], {}), '(-2, 1, 100)\n', (876, 888), True, 'import numpy as np\n'), ((1869, 1885), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(211)'], {}), '(211)\n', (1880, 1885), True, 'import matplotlib.pyplot as plt\n'), ((1886, 1914), 'matplotlib.pyplot.plot', 'plt.plot', (['lvalsList', 'mseList'], {}), '(lvalsList, mseList)\n', (1894, 1914), True, 'import matplotlib.pyplot as plt\n'), ((1915, 1936), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""lambda """'], {}), "('lambda ')\n", (1925, 1936), True, 'import matplotlib.pyplot as plt\n'), ((1937, 1954), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""mse"""'], {}), "('mse')\n", (1947, 1954), True, 'import matplotlib.pyplot as plt\n'), ((1955, 1983), 'matplotlib.pyplot.title', 'plt.title', (['""" mse vs lambda """'], {}), "(' mse vs lambda ')\n", (1964, 1983), True, 'import matplotlib.pyplot as plt\n'), ((2026, 2042), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(212)'], {}), '(212)\n', (2037, 2042), True, 'import matplotlib.pyplot as plt\n'), ((2043, 2080), 'matplotlib.pyplot.plot', 'plt.plot', (['lvalsList', 'changepointsList'], {}), '(lvalsList, changepointsList)\n', (2051, 2080), True, 'import matplotlib.pyplot as plt\n'), ((2081, 2102), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""lambda """'], {}), "('lambda ')\n", (2091, 2102), True, 'import matplotlib.pyplot as plt\n'), ((2103, 2130), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['""" changepoints"""'], {}), "(' changepoints')\n", (2113, 2130), True, 'import matplotlib.pyplot as plt\n'), ((2131, 2168), 'matplotlib.pyplot.title', 'plt.title', (['""" changepoints vs lambda """'], {}), "(' changepoints vs lambda ')\n", (2140, 2168), True, 'import matplotlib.pyplot as plt\n'), ((2170, 2188), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2186, 2188), True, 'import matplotlib.pyplot as plt\n'), ((2189, 2199), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2197, 2199), True, 'import matplotlib.pyplot as plt\n')]
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import logging
from decimal import Decimal
from functools import partial
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Union
import geohash as geohash_lib
import numpy as np
import pandas as pd
from flask_babel import gettext as _
from geopy.point import Point
from pandas import DataFrame, NamedAgg, Series, Timestamp
from superset.constants import NULL_STRING, PandasAxis, PandasPostprocessingCompare
from superset.exceptions import QueryObjectValidationError
from superset.utils.core import (
DTTM_ALIAS,
PostProcessingBoxplotWhiskerType,
PostProcessingContributionOrientation,
TIME_COMPARISION,
)
NUMPY_FUNCTIONS = {
"average": np.average,
"argmin": np.argmin,
"argmax": np.argmax,
"count": np.ma.count,
"count_nonzero": np.count_nonzero,
"cumsum": np.cumsum,
"cumprod": np.cumprod,
"max": np.max,
"mean": np.mean,
"median": np.median,
"nansum": np.nansum,
"nanmin": np.nanmin,
"nanmax": np.nanmax,
"nanmean": np.nanmean,
"nanmedian": np.nanmedian,
"nanpercentile": np.nanpercentile,
"min": np.min,
"percentile": np.percentile,
"prod": np.prod,
"product": np.product,
"std": np.std,
"sum": np.sum,
"var": np.var,
}
DENYLIST_ROLLING_FUNCTIONS = (
"count",
"corr",
"cov",
"kurt",
"max",
"mean",
"median",
"min",
"std",
"skew",
"sum",
"var",
"quantile",
)
ALLOWLIST_CUMULATIVE_FUNCTIONS = (
"cummax",
"cummin",
"cumprod",
"cumsum",
)
PROPHET_TIME_GRAIN_MAP = {
"PT1S": "S",
"PT1M": "min",
"PT5M": "5min",
"PT10M": "10min",
"PT15M": "15min",
"PT30M": "30min",
"PT1H": "H",
"P1D": "D",
"P1W": "W",
"P1M": "M",
"P3M": "Q",
"P1Y": "A",
"1969-12-28T00:00:00Z/P1W": "W",
"1969-12-29T00:00:00Z/P1W": "W",
"P1W/1970-01-03T00:00:00Z": "W",
"P1W/1970-01-04T00:00:00Z": "W",
}
def _flatten_column_after_pivot(
column: Union[float, Timestamp, str, Tuple[str, ...]],
aggregates: Dict[str, Dict[str, Any]],
) -> str:
"""
Function for flattening column names into a single string. This step is necessary
to be able to properly serialize a DataFrame. If the column is a string, return
element unchanged. For multi-element columns, join column elements with a comma,
with the exception of pivots made with a single aggregate, in which case the
aggregate column name is omitted.
:param column: single element from `DataFrame.columns`
:param aggregates: aggregates
:return:
"""
if not isinstance(column, tuple):
column = (column,)
if len(aggregates) == 1 and len(column) > 1:
# drop aggregate for single aggregate pivots with multiple groupings
# from column name (aggregates always come first in column name)
column = column[1:]
return ", ".join([str(col) for col in column])
def validate_column_args(*argnames: str) -> Callable[..., Any]:
def wrapper(func: Callable[..., Any]) -> Callable[..., Any]:
def wrapped(df: DataFrame, **options: Any) -> Any:
if options.get("is_pivot_df"):
# skip validation when pivot Dataframe
return func(df, **options)
columns = df.columns.tolist()
for name in argnames:
if name in options and not all(
elem in columns for elem in options.get(name) or []
):
raise QueryObjectValidationError(
_("Referenced columns not available in DataFrame.")
)
return func(df, **options)
return wrapped
return wrapper
def _get_aggregate_funcs(
df: DataFrame, aggregates: Dict[str, Dict[str, Any]],
) -> Dict[str, NamedAgg]:
"""
Converts a set of aggregate config objects into functions that pandas can use as
aggregators. Currently only numpy aggregators are supported.
:param df: DataFrame on which to perform aggregate operation.
:param aggregates: Mapping from column name to aggregate config.
:return: Mapping from metric name to function that takes a single input argument.
"""
agg_funcs: Dict[str, NamedAgg] = {}
for name, agg_obj in aggregates.items():
column = agg_obj.get("column", name)
if column not in df:
raise QueryObjectValidationError(
_(
"Column referenced by aggregate is undefined: %(column)s",
column=column,
)
)
if "operator" not in agg_obj:
raise QueryObjectValidationError(
_("Operator undefined for aggregator: %(name)s", name=name,)
)
operator = agg_obj["operator"]
if callable(operator):
aggfunc = operator
else:
func = NUMPY_FUNCTIONS.get(operator)
if not func:
raise QueryObjectValidationError(
_("Invalid numpy function: %(operator)s", operator=operator,)
)
options = agg_obj.get("options", {})
aggfunc = partial(func, **options)
agg_funcs[name] = NamedAgg(column=column, aggfunc=aggfunc)
return agg_funcs
def _append_columns(
base_df: DataFrame, append_df: DataFrame, columns: Dict[str, str]
) -> DataFrame:
"""
Function for adding columns from one DataFrame to another DataFrame. Calls the
assign method, which overwrites the original column in `base_df` if the column
already exists, and appends the column if the name is not defined.
:param base_df: DataFrame which to use as the base
:param append_df: DataFrame from which to select data.
:param columns: columns on which to append, mapping source column to
target column. For instance, `{'y': 'y'}` will replace the values in
column `y` in `base_df` with the values in `y` in `append_df`,
while `{'y': 'y2'}` will add a column `y2` to `base_df` based
on values in column `y` in `append_df`, leaving the original column `y`
in `base_df` unchanged.
:return: new DataFrame with combined data from `base_df` and `append_df`
"""
return base_df.assign(
**{target: append_df[source] for source, target in columns.items()}
)
@validate_column_args("index", "columns")
def pivot( # pylint: disable=too-many-arguments,too-many-locals
df: DataFrame,
index: List[str],
aggregates: Dict[str, Dict[str, Any]],
columns: Optional[List[str]] = None,
metric_fill_value: Optional[Any] = None,
column_fill_value: Optional[str] = NULL_STRING,
drop_missing_columns: Optional[bool] = True,
combine_value_with_metric: bool = False,
marginal_distributions: Optional[bool] = None,
marginal_distribution_name: Optional[str] = None,
flatten_columns: bool = True,
reset_index: bool = True,
) -> DataFrame:
"""
Perform a pivot operation on a DataFrame.
:param df: Object on which pivot operation will be performed
:param index: Columns to group by on the table index (=rows)
:param columns: Columns to group by on the table columns
:param metric_fill_value: Value to replace missing values with
:param column_fill_value: Value to replace missing pivot columns with. By default
replaces missing values with "<NULL>". Set to `None` to remove columns
with missing values.
:param drop_missing_columns: Do not include columns whose entries are all missing
:param combine_value_with_metric: Display metrics side by side within each column,
as opposed to each column being displayed side by side for each metric.
:param aggregates: A mapping from aggregate column name to the the aggregate
config.
:param marginal_distributions: Add totals for row/column. Default to False
:param marginal_distribution_name: Name of row/column with marginal distribution.
Default to 'All'.
:param flatten_columns: Convert column names to strings
:param reset_index: Convert index to column
:return: A pivot table
:raises QueryObjectValidationError: If the request in incorrect
"""
if not index:
raise QueryObjectValidationError(
_("Pivot operation requires at least one index")
)
if not aggregates:
raise QueryObjectValidationError(
_("Pivot operation must include at least one aggregate")
)
if columns and column_fill_value:
df[columns] = df[columns].fillna(value=column_fill_value)
aggregate_funcs = _get_aggregate_funcs(df, aggregates)
# TODO (villebro): Pandas 1.0.3 doesn't yet support NamedAgg in pivot_table.
# Remove once/if support is added.
aggfunc = {na.column: na.aggfunc for na in aggregate_funcs.values()}
# When dropna = False, the pivot_table function will calculate cartesian-product
# for MultiIndex.
# https://github.com/apache/superset/issues/15956
# https://github.com/pandas-dev/pandas/issues/18030
series_set = set()
if not drop_missing_columns and columns:
for row in df[columns].itertuples():
for metric in aggfunc.keys():
series_set.add(str(tuple([metric]) + tuple(row[1:])))
df = df.pivot_table(
values=aggfunc.keys(),
index=index,
columns=columns,
aggfunc=aggfunc,
fill_value=metric_fill_value,
dropna=drop_missing_columns,
margins=marginal_distributions,
margins_name=marginal_distribution_name,
)
if not drop_missing_columns and len(series_set) > 0 and not df.empty:
for col in df.columns:
series = str(col)
if series not in series_set:
df = df.drop(col, axis=PandasAxis.COLUMN)
if combine_value_with_metric:
df = df.stack(0).unstack()
# Make index regular column
if flatten_columns:
df.columns = [
_flatten_column_after_pivot(col, aggregates) for col in df.columns
]
# return index as regular column
if reset_index:
df.reset_index(level=0, inplace=True)
return df
@validate_column_args("groupby")
def aggregate(
df: DataFrame, groupby: List[str], aggregates: Dict[str, Dict[str, Any]]
) -> DataFrame:
"""
Apply aggregations to a DataFrame.
:param df: Object to aggregate.
:param groupby: columns to aggregate
:param aggregates: A mapping from metric column to the function used to
aggregate values.
:raises QueryObjectValidationError: If the request in incorrect
"""
aggregates = aggregates or {}
aggregate_funcs = _get_aggregate_funcs(df, aggregates)
if groupby:
df_groupby = df.groupby(by=groupby)
else:
df_groupby = df.groupby(lambda _: True)
return df_groupby.agg(**aggregate_funcs).reset_index(drop=not groupby)
@validate_column_args("columns")
def sort(df: DataFrame, columns: Dict[str, bool]) -> DataFrame:
"""
Sort a DataFrame.
:param df: DataFrame to sort.
:param columns: columns by by which to sort. The key specifies the column name,
value specifies if sorting in ascending order.
:return: Sorted DataFrame
:raises QueryObjectValidationError: If the request in incorrect
"""
return df.sort_values(by=list(columns.keys()), ascending=list(columns.values()))
@validate_column_args("columns")
def rolling( # pylint: disable=too-many-arguments
df: DataFrame,
rolling_type: str,
columns: Optional[Dict[str, str]] = None,
window: Optional[int] = None,
rolling_type_options: Optional[Dict[str, Any]] = None,
center: bool = False,
win_type: Optional[str] = None,
min_periods: Optional[int] = None,
is_pivot_df: bool = False,
) -> DataFrame:
"""
Apply a rolling window on the dataset. See the Pandas docs for further details:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.rolling.html
:param df: DataFrame on which the rolling period will be based.
:param columns: columns on which to perform rolling, mapping source column to
target column. For instance, `{'y': 'y'}` will replace the column `y` with
the rolling value in `y`, while `{'y': 'y2'}` will add a column `y2` based
on rolling values calculated from `y`, leaving the original column `y`
unchanged.
:param rolling_type: Type of rolling window. Any numpy function will work.
:param window: Size of the window.
:param rolling_type_options: Optional options to pass to rolling method. Needed
for e.g. quantile operation.
:param center: Should the label be at the center of the window.
:param win_type: Type of window function.
:param min_periods: The minimum amount of periods required for a row to be included
in the result set.
:param is_pivot_df: Dataframe is pivoted or not
:return: DataFrame with the rolling columns
:raises QueryObjectValidationError: If the request in incorrect
"""
rolling_type_options = rolling_type_options or {}
columns = columns or {}
if is_pivot_df:
df_rolling = df
else:
df_rolling = df[columns.keys()]
kwargs: Dict[str, Union[str, int]] = {}
if window is None:
raise QueryObjectValidationError(_("Undefined window for rolling operation"))
if window == 0:
raise QueryObjectValidationError(_("Window must be > 0"))
kwargs["window"] = window
if min_periods is not None:
kwargs["min_periods"] = min_periods
if center is not None:
kwargs["center"] = center
if win_type is not None:
kwargs["win_type"] = win_type
df_rolling = df_rolling.rolling(**kwargs)
if rolling_type not in DENYLIST_ROLLING_FUNCTIONS or not hasattr(
df_rolling, rolling_type
):
raise QueryObjectValidationError(
_("Invalid rolling_type: %(type)s", type=rolling_type)
)
try:
df_rolling = getattr(df_rolling, rolling_type)(**rolling_type_options)
except TypeError as ex:
raise QueryObjectValidationError(
_(
"Invalid options for %(rolling_type)s: %(options)s",
rolling_type=rolling_type,
options=rolling_type_options,
)
) from ex
if is_pivot_df:
agg_in_pivot_df = df.columns.get_level_values(0).drop_duplicates().to_list()
agg: Dict[str, Dict[str, Any]] = {col: {} for col in agg_in_pivot_df}
df_rolling.columns = [
_flatten_column_after_pivot(col, agg) for col in df_rolling.columns
]
df_rolling.reset_index(level=0, inplace=True)
else:
df_rolling = _append_columns(df, df_rolling, columns)
if min_periods:
df_rolling = df_rolling[min_periods:]
return df_rolling
@validate_column_args("columns", "drop", "rename")
def select(
df: DataFrame,
columns: Optional[List[str]] = None,
exclude: Optional[List[str]] = None,
rename: Optional[Dict[str, str]] = None,
) -> DataFrame:
"""
Only select a subset of columns in the original dataset. Can be useful for
removing unnecessary intermediate results, renaming and reordering columns.
:param df: DataFrame on which the rolling period will be based.
:param columns: Columns which to select from the DataFrame, in the desired order.
If left undefined, all columns will be selected. If columns are
renamed, the original column name should be referenced here.
:param exclude: columns to exclude from selection. If columns are renamed, the new
column name should be referenced here.
:param rename: columns which to rename, mapping source column to target column.
For instance, `{'y': 'y2'}` will rename the column `y` to
`y2`.
:return: Subset of columns in original DataFrame
:raises QueryObjectValidationError: If the request in incorrect
"""
df_select = df.copy(deep=False)
if columns:
df_select = df_select[columns]
if exclude:
df_select = df_select.drop(exclude, axis=1)
if rename is not None:
df_select = df_select.rename(columns=rename)
return df_select
@validate_column_args("columns")
def diff(
df: DataFrame,
columns: Dict[str, str],
periods: int = 1,
axis: PandasAxis = PandasAxis.ROW,
) -> DataFrame:
"""
Calculate row-by-row or column-by-column difference for select columns.
:param df: DataFrame on which the diff will be based.
:param columns: columns on which to perform diff, mapping source column to
target column. For instance, `{'y': 'y'}` will replace the column `y` with
the diff value in `y`, while `{'y': 'y2'}` will add a column `y2` based
on diff values calculated from `y`, leaving the original column `y`
unchanged.
:param periods: periods to shift for calculating difference.
:param axis: 0 for row, 1 for column. default 0.
:return: DataFrame with diffed columns
:raises QueryObjectValidationError: If the request in incorrect
"""
df_diff = df[columns.keys()]
df_diff = df_diff.diff(periods=periods, axis=axis)
return _append_columns(df, df_diff, columns)
@validate_column_args("source_columns", "compare_columns")
def compare( # pylint: disable=too-many-arguments
df: DataFrame,
source_columns: List[str],
compare_columns: List[str],
compare_type: Optional[PandasPostprocessingCompare],
drop_original_columns: Optional[bool] = False,
precision: Optional[int] = 4,
) -> DataFrame:
"""
Calculate column-by-column changing for select columns.
:param df: DataFrame on which the compare will be based.
:param source_columns: Main query columns
:param compare_columns: Columns being compared
:param compare_type: Type of compare. Choice of `absolute`, `percentage` or `ratio`
:param drop_original_columns: Whether to remove the source columns and
compare columns.
:param precision: Round a change rate to a variable number of decimal places.
:return: DataFrame with compared columns.
:raises QueryObjectValidationError: If the request in incorrect.
"""
if len(source_columns) != len(compare_columns):
raise QueryObjectValidationError(
_("`compare_columns` must have the same length as `source_columns`.")
)
if compare_type not in tuple(PandasPostprocessingCompare):
raise QueryObjectValidationError(
_("`compare_type` must be `difference`, `percentage` or `ratio`")
)
if len(source_columns) == 0:
return df
for s_col, c_col in zip(source_columns, compare_columns):
if compare_type == PandasPostprocessingCompare.DIFF:
diff_series = df[s_col] - df[c_col]
elif compare_type == PandasPostprocessingCompare.PCT:
diff_series = (
((df[s_col] - df[c_col]) / df[c_col]).astype(float).round(precision)
)
else:
# compare_type == "ratio"
diff_series = (df[s_col] / df[c_col]).astype(float).round(precision)
diff_df = diff_series.to_frame(
name=TIME_COMPARISION.join([compare_type, s_col, c_col])
)
df = pd.concat([df, diff_df], axis=1)
if drop_original_columns:
df = df.drop(source_columns + compare_columns, axis=1)
return df
@validate_column_args("columns")
def cum(
df: DataFrame,
operator: str,
columns: Optional[Dict[str, str]] = None,
is_pivot_df: bool = False,
) -> DataFrame:
"""
Calculate cumulative sum/product/min/max for select columns.
:param df: DataFrame on which the cumulative operation will be based.
:param columns: columns on which to perform a cumulative operation, mapping source
column to target column. For instance, `{'y': 'y'}` will replace the column
`y` with the cumulative value in `y`, while `{'y': 'y2'}` will add a column
`y2` based on cumulative values calculated from `y`, leaving the original
column `y` unchanged.
:param operator: cumulative operator, e.g. `sum`, `prod`, `min`, `max`
:param is_pivot_df: Dataframe is pivoted or not
:return: DataFrame with cumulated columns
"""
columns = columns or {}
if is_pivot_df:
df_cum = df
else:
df_cum = df[columns.keys()]
operation = "cum" + operator
if operation not in ALLOWLIST_CUMULATIVE_FUNCTIONS or not hasattr(
df_cum, operation
):
raise QueryObjectValidationError(
_("Invalid cumulative operator: %(operator)s", operator=operator)
)
if is_pivot_df:
df_cum = getattr(df_cum, operation)()
agg_in_pivot_df = df.columns.get_level_values(0).drop_duplicates().to_list()
agg: Dict[str, Dict[str, Any]] = {col: {} for col in agg_in_pivot_df}
df_cum.columns = [
_flatten_column_after_pivot(col, agg) for col in df_cum.columns
]
df_cum.reset_index(level=0, inplace=True)
else:
df_cum = _append_columns(df, getattr(df_cum, operation)(), columns)
return df_cum
def geohash_decode(
df: DataFrame, geohash: str, longitude: str, latitude: str
) -> DataFrame:
"""
Decode a geohash column into longitude and latitude
:param df: DataFrame containing geohash data
:param geohash: Name of source column containing geohash location.
:param longitude: Name of new column to be created containing longitude.
:param latitude: Name of new column to be created containing latitude.
:return: DataFrame with decoded longitudes and latitudes
"""
try:
lonlat_df = DataFrame()
lonlat_df["latitude"], lonlat_df["longitude"] = zip(
*df[geohash].apply(geohash_lib.decode)
)
return _append_columns(
df, lonlat_df, {"latitude": latitude, "longitude": longitude}
)
except ValueError as ex:
raise QueryObjectValidationError(_("Invalid geohash string")) from ex
def geohash_encode(
df: DataFrame, geohash: str, longitude: str, latitude: str,
) -> DataFrame:
"""
Encode longitude and latitude into geohash
:param df: DataFrame containing longitude and latitude data
:param geohash: Name of new column to be created containing geohash location.
:param longitude: Name of source column containing longitude.
:param latitude: Name of source column containing latitude.
:return: DataFrame with decoded longitudes and latitudes
"""
try:
encode_df = df[[latitude, longitude]]
encode_df.columns = ["latitude", "longitude"]
encode_df["geohash"] = encode_df.apply(
lambda row: geohash_lib.encode(row["latitude"], row["longitude"]), axis=1,
)
return _append_columns(df, encode_df, {"geohash": geohash})
except ValueError as ex:
raise QueryObjectValidationError(_("Invalid longitude/latitude")) from ex
def geodetic_parse(
df: DataFrame,
geodetic: str,
longitude: str,
latitude: str,
altitude: Optional[str] = None,
) -> DataFrame:
"""
Parse a column containing a geodetic point string
[Geopy](https://geopy.readthedocs.io/en/stable/#geopy.point.Point).
:param df: DataFrame containing geodetic point data
:param geodetic: Name of source column containing geodetic point string.
:param longitude: Name of new column to be created containing longitude.
:param latitude: Name of new column to be created containing latitude.
:param altitude: Name of new column to be created containing altitude.
:return: DataFrame with decoded longitudes and latitudes
"""
def _parse_location(location: str) -> Tuple[float, float, float]:
"""
Parse a string containing a geodetic point and return latitude, longitude
and altitude
"""
point = Point(location)
return point[0], point[1], point[2]
try:
geodetic_df = DataFrame()
(
geodetic_df["latitude"],
geodetic_df["longitude"],
geodetic_df["altitude"],
) = zip(*df[geodetic].apply(_parse_location))
columns = {"latitude": latitude, "longitude": longitude}
if altitude:
columns["altitude"] = altitude
return _append_columns(df, geodetic_df, columns)
except ValueError as ex:
raise QueryObjectValidationError(_("Invalid geodetic string")) from ex
@validate_column_args("columns")
def contribution(
df: DataFrame,
orientation: Optional[
PostProcessingContributionOrientation
] = PostProcessingContributionOrientation.COLUMN,
columns: Optional[List[str]] = None,
rename_columns: Optional[List[str]] = None,
) -> DataFrame:
"""
Calculate cell contibution to row/column total for numeric columns.
Non-numeric columns will be kept untouched.
If `columns` are specified, only calculate contributions on selected columns.
:param df: DataFrame containing all-numeric data (temporal column ignored)
:param columns: Columns to calculate values from.
:param rename_columns: The new labels for the calculated contribution columns.
The original columns will not be removed.
:param orientation: calculate by dividing cell with row/column total
:return: DataFrame with contributions.
"""
contribution_df = df.copy()
numeric_df = contribution_df.select_dtypes(include=["number", Decimal])
# verify column selections
if columns:
numeric_columns = numeric_df.columns.tolist()
for col in columns:
if col not in numeric_columns:
raise QueryObjectValidationError(
_(
'Column "%(column)s" is not numeric or does not '
"exists in the query results.",
column=col,
)
)
columns = columns or numeric_df.columns
rename_columns = rename_columns or columns
if len(rename_columns) != len(columns):
raise QueryObjectValidationError(
_("`rename_columns` must have the same length as `columns`.")
)
# limit to selected columns
numeric_df = numeric_df[columns]
axis = 0 if orientation == PostProcessingContributionOrientation.COLUMN else 1
numeric_df = numeric_df / numeric_df.values.sum(axis=axis, keepdims=True)
contribution_df[rename_columns] = numeric_df
return contribution_df
def _prophet_parse_seasonality(
input_value: Optional[Union[bool, int]]
) -> Union[bool, str, int]:
if input_value is None:
return "auto"
if isinstance(input_value, bool):
return input_value
try:
return int(input_value)
except ValueError:
return input_value
def _prophet_fit_and_predict( # pylint: disable=too-many-arguments
df: DataFrame,
confidence_interval: float,
yearly_seasonality: Union[bool, str, int],
weekly_seasonality: Union[bool, str, int],
daily_seasonality: Union[bool, str, int],
periods: int,
freq: str,
) -> DataFrame:
"""
Fit a prophet model and return a DataFrame with predicted results.
"""
try:
# pylint: disable=import-error,import-outside-toplevel
from prophet import Prophet
prophet_logger = logging.getLogger("prophet.plot")
prophet_logger.setLevel(logging.CRITICAL)
prophet_logger.setLevel(logging.NOTSET)
except ModuleNotFoundError as ex:
raise QueryObjectValidationError(_("`prophet` package not installed")) from ex
model = Prophet(
interval_width=confidence_interval,
yearly_seasonality=yearly_seasonality,
weekly_seasonality=weekly_seasonality,
daily_seasonality=daily_seasonality,
)
if df["ds"].dt.tz:
df["ds"] = df["ds"].dt.tz_convert(None)
model.fit(df)
future = model.make_future_dataframe(periods=periods, freq=freq)
forecast = model.predict(future)[["ds", "yhat", "yhat_lower", "yhat_upper"]]
return forecast.join(df.set_index("ds"), on="ds").set_index(["ds"])
def prophet( # pylint: disable=too-many-arguments
df: DataFrame,
time_grain: str,
periods: int,
confidence_interval: float,
yearly_seasonality: Optional[Union[bool, int]] = None,
weekly_seasonality: Optional[Union[bool, int]] = None,
daily_seasonality: Optional[Union[bool, int]] = None,
) -> DataFrame:
"""
Add forecasts to each series in a timeseries dataframe, along with confidence
intervals for the prediction. For each series, the operation creates three
new columns with the column name suffixed with the following values:
- `__yhat`: the forecast for the given date
- `__yhat_lower`: the lower bound of the forecast for the given date
- `__yhat_upper`: the upper bound of the forecast for the given date
:param df: DataFrame containing all-numeric data (temporal column ignored)
:param time_grain: Time grain used to specify time period increments in prediction
:param periods: Time periods (in units of `time_grain`) to predict into the future
:param confidence_interval: Width of predicted confidence interval
:param yearly_seasonality: Should yearly seasonality be applied.
An integer value will specify Fourier order of seasonality.
:param weekly_seasonality: Should weekly seasonality be applied.
An integer value will specify Fourier order of seasonality, `None` will
automatically detect seasonality.
:param daily_seasonality: Should daily seasonality be applied.
An integer value will specify Fourier order of seasonality, `None` will
automatically detect seasonality.
:return: DataFrame with contributions, with temporal column at beginning if present
"""
# validate inputs
if not time_grain:
raise QueryObjectValidationError(_("Time grain missing"))
if time_grain not in PROPHET_TIME_GRAIN_MAP:
raise QueryObjectValidationError(
_("Unsupported time grain: %(time_grain)s", time_grain=time_grain,)
)
freq = PROPHET_TIME_GRAIN_MAP[time_grain]
# check type at runtime due to marhsmallow schema not being able to handle
# union types
if not periods or periods < 0 or not isinstance(periods, int):
raise QueryObjectValidationError(_("Periods must be a positive integer value"))
if not confidence_interval or confidence_interval <= 0 or confidence_interval >= 1:
raise QueryObjectValidationError(
_("Confidence interval must be between 0 and 1 (exclusive)")
)
if DTTM_ALIAS not in df.columns:
raise QueryObjectValidationError(_("DataFrame must include temporal column"))
if len(df.columns) < 2:
raise QueryObjectValidationError(_("DataFrame include at least one series"))
target_df = DataFrame()
for column in [column for column in df.columns if column != DTTM_ALIAS]:
fit_df = _prophet_fit_and_predict(
df=df[[DTTM_ALIAS, column]].rename(columns={DTTM_ALIAS: "ds", column: "y"}),
confidence_interval=confidence_interval,
yearly_seasonality=_prophet_parse_seasonality(yearly_seasonality),
weekly_seasonality=_prophet_parse_seasonality(weekly_seasonality),
daily_seasonality=_prophet_parse_seasonality(daily_seasonality),
periods=periods,
freq=freq,
)
new_columns = [
f"{column}__yhat",
f"{column}__yhat_lower",
f"{column}__yhat_upper",
f"{column}",
]
fit_df.columns = new_columns
if target_df.empty:
target_df = fit_df
else:
for new_column in new_columns:
target_df = target_df.assign(**{new_column: fit_df[new_column]})
target_df.reset_index(level=0, inplace=True)
return target_df.rename(columns={"ds": DTTM_ALIAS})
def boxplot(
df: DataFrame,
groupby: List[str],
metrics: List[str],
whisker_type: PostProcessingBoxplotWhiskerType,
percentiles: Optional[
Union[List[Union[int, float]], Tuple[Union[int, float], Union[int, float]]]
] = None,
) -> DataFrame:
"""
Calculate boxplot statistics. For each metric, the operation creates eight
new columns with the column name suffixed with the following values:
- `__mean`: the mean
- `__median`: the median
- `__max`: the maximum value excluding outliers (see whisker type)
- `__min`: the minimum value excluding outliers (see whisker type)
- `__q1`: the median
- `__q1`: the first quartile (25th percentile)
- `__q3`: the third quartile (75th percentile)
- `__count`: count of observations
- `__outliers`: the values that fall outside the minimum/maximum value
(see whisker type)
:param df: DataFrame containing all-numeric data (temporal column ignored)
:param groupby: The categories to group by (x-axis)
:param metrics: The metrics for which to calculate the distribution
:param whisker_type: The confidence level type
:return: DataFrame with boxplot statistics per groupby
"""
def quartile1(series: Series) -> float:
return np.nanpercentile(series, 25, interpolation="midpoint")
def quartile3(series: Series) -> float:
return np.nanpercentile(series, 75, interpolation="midpoint")
if whisker_type == PostProcessingBoxplotWhiskerType.TUKEY:
def whisker_high(series: Series) -> float:
upper_outer_lim = quartile3(series) + 1.5 * (
quartile3(series) - quartile1(series)
)
return series[series <= upper_outer_lim].max()
def whisker_low(series: Series) -> float:
lower_outer_lim = quartile1(series) - 1.5 * (
quartile3(series) - quartile1(series)
)
return series[series >= lower_outer_lim].min()
elif whisker_type == PostProcessingBoxplotWhiskerType.PERCENTILE:
if (
not isinstance(percentiles, (list, tuple))
or len(percentiles) != 2
or not isinstance(percentiles[0], (int, float))
or not isinstance(percentiles[1], (int, float))
or percentiles[0] >= percentiles[1]
):
raise QueryObjectValidationError(
_(
"percentiles must be a list or tuple with two numeric values, "
"of which the first is lower than the second value"
)
)
low, high = percentiles[0], percentiles[1]
def whisker_high(series: Series) -> float:
return np.nanpercentile(series, high)
def whisker_low(series: Series) -> float:
return np.nanpercentile(series, low)
else:
whisker_high = np.max
whisker_low = np.min
def outliers(series: Series) -> Set[float]:
above = series[series > whisker_high(series)]
below = series[series < whisker_low(series)]
return above.tolist() + below.tolist()
operators: Dict[str, Callable[[Any], Any]] = {
"mean": np.mean,
"median": np.median,
"max": whisker_high,
"min": whisker_low,
"q1": quartile1,
"q3": quartile3,
"count": np.ma.count,
"outliers": outliers,
}
aggregates: Dict[str, Dict[str, Union[str, Callable[..., Any]]]] = {
f"{metric}__{operator_name}": {"column": metric, "operator": operator}
for operator_name, operator in operators.items()
for metric in metrics
}
return aggregate(df, groupby=groupby, aggregates=aggregates)
def resample(
df: DataFrame,
rule: str,
method: str,
time_column: str,
fill_value: Optional[Union[float, int]] = None,
) -> DataFrame:
"""
resample a timeseries dataframe.
:param df: DataFrame to resample.
:param rule: The offset string representing target conversion.
:param method: How to fill the NaN value after resample.
:param time_column: existing columns in DataFrame.
:param fill_value: What values do fill missing.
:return: DataFrame after resample
:raises QueryObjectValidationError: If the request in incorrect
"""
df = df.set_index(time_column)
if method == "asfreq" and fill_value is not None:
df = df.resample(rule).asfreq(fill_value=fill_value)
else:
df = getattr(df.resample(rule), method)()
return df.reset_index()
|
[
"pandas.DataFrame",
"functools.partial",
"numpy.nanpercentile",
"pandas.NamedAgg",
"flask_babel.gettext",
"geopy.point.Point",
"geohash.encode",
"prophet.Prophet",
"superset.utils.core.TIME_COMPARISION.join",
"pandas.concat",
"logging.getLogger"
] |
[((28618, 28785), 'prophet.Prophet', 'Prophet', ([], {'interval_width': 'confidence_interval', 'yearly_seasonality': 'yearly_seasonality', 'weekly_seasonality': 'weekly_seasonality', 'daily_seasonality': 'daily_seasonality'}), '(interval_width=confidence_interval, yearly_seasonality=\n yearly_seasonality, weekly_seasonality=weekly_seasonality,\n daily_seasonality=daily_seasonality)\n', (28625, 28785), False, 'from prophet import Prophet\n'), ((31909, 31920), 'pandas.DataFrame', 'DataFrame', ([], {}), '()\n', (31918, 31920), False, 'from pandas import DataFrame, NamedAgg, Series, Timestamp\n'), ((5994, 6034), 'pandas.NamedAgg', 'NamedAgg', ([], {'column': 'column', 'aggfunc': 'aggfunc'}), '(column=column, aggfunc=aggfunc)\n', (6002, 6034), False, 'from pandas import DataFrame, NamedAgg, Series, Timestamp\n'), ((20222, 20254), 'pandas.concat', 'pd.concat', (['[df, diff_df]'], {'axis': '(1)'}), '([df, diff_df], axis=1)\n', (20231, 20254), True, 'import pandas as pd\n'), ((22659, 22670), 'pandas.DataFrame', 'DataFrame', ([], {}), '()\n', (22668, 22670), False, 'from pandas import DataFrame, NamedAgg, Series, Timestamp\n'), ((24881, 24896), 'geopy.point.Point', 'Point', (['location'], {}), '(location)\n', (24886, 24896), False, 'from geopy.point import Point\n'), ((24973, 24984), 'pandas.DataFrame', 'DataFrame', ([], {}), '()\n', (24982, 24984), False, 'from pandas import DataFrame, NamedAgg, Series, Timestamp\n'), ((28349, 28382), 'logging.getLogger', 'logging.getLogger', (['"""prophet.plot"""'], {}), "('prophet.plot')\n", (28366, 28382), False, 'import logging\n'), ((34281, 34335), 'numpy.nanpercentile', 'np.nanpercentile', (['series', '(25)'], {'interpolation': '"""midpoint"""'}), "(series, 25, interpolation='midpoint')\n", (34297, 34335), True, 'import numpy as np\n'), ((34396, 34450), 'numpy.nanpercentile', 'np.nanpercentile', (['series', '(75)'], {'interpolation': '"""midpoint"""'}), "(series, 75, interpolation='midpoint')\n", (34412, 34450), True, 'import numpy as np\n'), ((5943, 5967), 'functools.partial', 'partial', (['func'], {}), '(func, **options)\n', (5950, 5967), False, 'from functools import partial\n'), ((9094, 9142), 'flask_babel.gettext', '_', (['"""Pivot operation requires at least one index"""'], {}), "('Pivot operation requires at least one index')\n", (9095, 9142), True, 'from flask_babel import gettext as _\n'), ((9230, 9286), 'flask_babel.gettext', '_', (['"""Pivot operation must include at least one aggregate"""'], {}), "('Pivot operation must include at least one aggregate')\n", (9231, 9286), True, 'from flask_babel import gettext as _\n'), ((14195, 14238), 'flask_babel.gettext', '_', (['"""Undefined window for rolling operation"""'], {}), "('Undefined window for rolling operation')\n", (14196, 14238), True, 'from flask_babel import gettext as _\n'), ((14301, 14324), 'flask_babel.gettext', '_', (['"""Window must be > 0"""'], {}), "('Window must be > 0')\n", (14302, 14324), True, 'from flask_babel import gettext as _\n'), ((14772, 14826), 'flask_babel.gettext', '_', (['"""Invalid rolling_type: %(type)s"""'], {'type': 'rolling_type'}), "('Invalid rolling_type: %(type)s', type=rolling_type)\n", (14773, 14826), True, 'from flask_babel import gettext as _\n'), ((19272, 19341), 'flask_babel.gettext', '_', (['"""`compare_columns` must have the same length as `source_columns`."""'], {}), "('`compare_columns` must have the same length as `source_columns`.')\n", (19273, 19341), True, 'from flask_babel import gettext as _\n'), ((19469, 19534), 'flask_babel.gettext', '_', (['"""`compare_type` must be `difference`, `percentage` or `ratio`"""'], {}), "('`compare_type` must be `difference`, `percentage` or `ratio`')\n", (19470, 19534), True, 'from flask_babel import gettext as _\n'), ((21551, 21616), 'flask_babel.gettext', '_', (['"""Invalid cumulative operator: %(operator)s"""'], {'operator': 'operator'}), "('Invalid cumulative operator: %(operator)s', operator=operator)\n", (21552, 21616), True, 'from flask_babel import gettext as _\n'), ((27128, 27189), 'flask_babel.gettext', '_', (['"""`rename_columns` must have the same length as `columns`."""'], {}), "('`rename_columns` must have the same length as `columns`.')\n", (27129, 27189), True, 'from flask_babel import gettext as _\n'), ((30939, 30962), 'flask_babel.gettext', '_', (['"""Time grain missing"""'], {}), "('Time grain missing')\n", (30940, 30962), True, 'from flask_babel import gettext as _\n'), ((31067, 31133), 'flask_babel.gettext', '_', (['"""Unsupported time grain: %(time_grain)s"""'], {'time_grain': 'time_grain'}), "('Unsupported time grain: %(time_grain)s', time_grain=time_grain)\n", (31068, 31133), True, 'from flask_babel import gettext as _\n'), ((31396, 31441), 'flask_babel.gettext', '_', (['"""Periods must be a positive integer value"""'], {}), "('Periods must be a positive integer value')\n", (31397, 31441), True, 'from flask_babel import gettext as _\n'), ((31585, 31645), 'flask_babel.gettext', '_', (['"""Confidence interval must be between 0 and 1 (exclusive)"""'], {}), "('Confidence interval must be between 0 and 1 (exclusive)')\n", (31586, 31645), True, 'from flask_babel import gettext as _\n'), ((31734, 31777), 'flask_babel.gettext', '_', (['"""DataFrame must include temporal column"""'], {}), "('DataFrame must include temporal column')\n", (31735, 31777), True, 'from flask_babel import gettext as _\n'), ((31848, 31890), 'flask_babel.gettext', '_', (['"""DataFrame include at least one series"""'], {}), "('DataFrame include at least one series')\n", (31849, 31890), True, 'from flask_babel import gettext as _\n'), ((5209, 5284), 'flask_babel.gettext', '_', (['"""Column referenced by aggregate is undefined: %(column)s"""'], {'column': 'column'}), "('Column referenced by aggregate is undefined: %(column)s', column=column)\n", (5210, 5284), True, 'from flask_babel import gettext as _\n'), ((5458, 5517), 'flask_babel.gettext', '_', (['"""Operator undefined for aggregator: %(name)s"""'], {'name': 'name'}), "('Operator undefined for aggregator: %(name)s', name=name)\n", (5459, 5517), True, 'from flask_babel import gettext as _\n'), ((15007, 15123), 'flask_babel.gettext', '_', (['"""Invalid options for %(rolling_type)s: %(options)s"""'], {'rolling_type': 'rolling_type', 'options': 'rolling_type_options'}), "('Invalid options for %(rolling_type)s: %(options)s', rolling_type=\n rolling_type, options=rolling_type_options)\n", (15008, 15123), True, 'from flask_babel import gettext as _\n'), ((20147, 20198), 'superset.utils.core.TIME_COMPARISION.join', 'TIME_COMPARISION.join', (['[compare_type, s_col, c_col]'], {}), '([compare_type, s_col, c_col])\n', (20168, 20198), False, 'from superset.utils.core import DTTM_ALIAS, PostProcessingBoxplotWhiskerType, PostProcessingContributionOrientation, TIME_COMPARISION\n'), ((22979, 23006), 'flask_babel.gettext', '_', (['"""Invalid geohash string"""'], {}), "('Invalid geohash string')\n", (22980, 23006), True, 'from flask_babel import gettext as _\n'), ((23700, 23753), 'geohash.encode', 'geohash_lib.encode', (["row['latitude']", "row['longitude']"], {}), "(row['latitude'], row['longitude'])\n", (23718, 23753), True, 'import geohash as geohash_lib\n'), ((23911, 23942), 'flask_babel.gettext', '_', (['"""Invalid longitude/latitude"""'], {}), "('Invalid longitude/latitude')\n", (23912, 23942), True, 'from flask_babel import gettext as _\n'), ((25417, 25445), 'flask_babel.gettext', '_', (['"""Invalid geodetic string"""'], {}), "('Invalid geodetic string')\n", (25418, 25445), True, 'from flask_babel import gettext as _\n'), ((28560, 28596), 'flask_babel.gettext', '_', (['"""`prophet` package not installed"""'], {}), "('`prophet` package not installed')\n", (28561, 28596), True, 'from flask_babel import gettext as _\n'), ((35718, 35748), 'numpy.nanpercentile', 'np.nanpercentile', (['series', 'high'], {}), '(series, high)\n', (35734, 35748), True, 'import numpy as np\n'), ((35819, 35848), 'numpy.nanpercentile', 'np.nanpercentile', (['series', 'low'], {}), '(series, low)\n', (35835, 35848), True, 'import numpy as np\n'), ((5792, 5852), 'flask_babel.gettext', '_', (['"""Invalid numpy function: %(operator)s"""'], {'operator': 'operator'}), "('Invalid numpy function: %(operator)s', operator=operator)\n", (5793, 5852), True, 'from flask_babel import gettext as _\n'), ((26730, 26827), 'flask_babel.gettext', '_', (['"""Column "%(column)s" is not numeric or does not exists in the query results."""'], {'column': 'col'}), '(\'Column "%(column)s" is not numeric or does not exists in the query results.\'\n , column=col)\n', (26731, 26827), True, 'from flask_babel import gettext as _\n'), ((35405, 35525), 'flask_babel.gettext', '_', (['"""percentiles must be a list or tuple with two numeric values, of which the first is lower than the second value"""'], {}), "('percentiles must be a list or tuple with two numeric values, of which the first is lower than the second value'\n )\n", (35406, 35525), True, 'from flask_babel import gettext as _\n'), ((4331, 4382), 'flask_babel.gettext', '_', (['"""Referenced columns not available in DataFrame."""'], {}), "('Referenced columns not available in DataFrame.')\n", (4332, 4382), True, 'from flask_babel import gettext as _\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Trains a neural network for bird classification.
For usage information, call with --help.
Author: <NAME>
"""
from __future__ import print_function
import sys
import os
import io
from argparse import ArgumentParser
try:
import cPickle as pickle
except ImportError:
import pickle
import numpy as np
import theano
import theano.tensor as T
floatX = theano.config.floatX
import lasagne
from progress import progress
import config
import data
import model
import augment
def opts_parser():
descr = "Trains a neural network for bird classification."
parser = ArgumentParser(description=descr)
parser.add_argument('modelfile', metavar='MODELFILE',
type=str,
help='File to save the learned weights to (.npz format)')
parser.add_argument('--dataset',
type=str, default='birdclef',
help='Name of the dataset to use (default: %(default)s)')
parser.add_argument('--validate',
action='store_true', default=False,
help='Monitor validation loss (disabled by default)')
parser.add_argument('--no-validate',
action='store_false', dest='validate',
help='Disable monitoring validation loss (disabled by default)')
parser.add_argument('--save-errors',
action='store_true', default=False,
help='If given, save error log in {MODELFILE%%.npz}.err.npz.')
parser.add_argument('--keep-state',
action='store_true', default=False,
help='If given, save the complete training state after each epoch '
'in {MODELFILE%%.npz}.state, and load it to continue from '
'there if the script is restarted.')
parser.add_argument('--vars', metavar='FILE',
action='append', type=str,
default=[os.path.join(os.path.dirname(__file__), 'defaults.vars')],
help='Reads configuration variables from a FILE of KEY=VALUE '
'lines. Can be given multiple times, settings from later '
'files overriding earlier ones. Will read defaults.vars, '
'then files given here.')
parser.add_argument('--var', metavar='KEY=VALUE',
action='append', type=str,
help='Set the configuration variable KEY to VALUE. Overrides '
'settings from --vars options. Can be given multiple times.')
return parser
def get_state(network, updates):
return ([p.get_value() for p in updates.keys()] +
lasagne.layers.get_all_param_values(network, trainable=False))
def restore_state(network, updates, state):
for p, s in zip(updates.keys(), state):
p.set_value(s)
lasagne.layers.set_all_param_values(
network, state[len(updates):], trainable=False)
def save_model(modelfile, network, cfg):
np.savez(modelfile, **{'param%d' % i: p for i, p in enumerate(
lasagne.layers.get_all_param_values(network))})
write = 'wb' if sys.version_info[0] == 2 else 'w'
with io.open(modelfile + '.vars', write) as f:
f.writelines('%s=%s\n' % kv for kv in cfg.items())
def main():
# parse command line
parser = opts_parser()
options = parser.parse_args()
modelfile = options.modelfile
# read configuration files and immediate settings
cfg = {}
for fn in options.vars:
cfg.update(config.parse_config_file(fn))
cfg.update(config.parse_variable_assignments(options.var))
# prepare dataset
datadir = os.path.join(os.path.dirname(__file__),
os.path.pardir, 'datasets', options.dataset)
print("Preparing training data feed...")
with io.open(os.path.join(datadir, 'filelists', 'train')) as f:
filelist = [l.rstrip() for l in f if l.rstrip()]
train_feed, train_formats = data.prepare_datafeed(filelist, datadir,
'train', cfg)
# If told so, we plot some mini-batches on screen.
if cfg.get('plot_datafeed'):
import matplotlib.pyplot as plt
for batch in data.run_datafeed(train_feed, cfg):
plt.matshow(np.log(batch['spect'][0]).T, aspect='auto',
origin='lower', cmap='hot', interpolation='nearest')
plt.colorbar()
plt.title(str(batch['label'][0]))
plt.show()
# We start the mini-batch generator and augmenter in one or more
# background threads or processes (unless disabled).
bg_threads = cfg['bg_threads']
bg_processes = cfg['bg_processes']
if not bg_threads and not bg_processes:
# no background processing: just create a single generator
batches = data.run_datafeed(train_feed, cfg)
elif bg_threads:
# multithreading: create a separate generator per thread
batches = augment.generate_in_background(
[data.run_datafeed(feed, cfg)
for feed in data.split_datafeed(train_feed, bg_threads, cfg)],
num_cached=bg_threads * 2)
elif bg_processes:
# multiprocessing: single generator is forked along with processes
batches = augment.generate_in_background(
[data.run_datafeed(train_feed, cfg)] * bg_processes,
num_cached=bg_processes * 25,
in_processes=True)
# If told so, we benchmark the creation of a given number of mini-batches.
if cfg.get('benchmark_datafeed'):
print("Benchmark: %d mini-batches of %d items " %
(cfg['benchmark_datafeed'], cfg['batchsize']), end='')
if bg_threads:
print("(in %d threads): " % bg_threads)
elif bg_processes:
print("(in %d processes): " % bg_processes)
else:
print("(in main thread): ")
import time
import itertools
t0 = time.time()
next(itertools.islice(batches, cfg['benchmark_datafeed'],
cfg['benchmark_datafeed']), None)
t1 = time.time()
print (t1 - t0)
return
# - prepare validation data generator
if options.validate:
print("Preparing validation data feed...")
with io.open(os.path.join(datadir, 'filelists', 'valid')) as f:
filelist_val = [l.rstrip() for l in f if l.rstrip()]
val_feed, val_formats = data.prepare_datafeed(filelist_val, datadir,
'valid', cfg)
if bg_threads or bg_processes:
multi = bg_threads or bg_processes
val_feed = data.split_datafeed(val_feed, multi, cfg)
def run_val_datafeed():
if bg_threads or bg_processes:
return augment.generate_in_background(
[data.run_datafeed(feed, cfg)
for feed in val_feed],
num_cached=multi, in_processes=bool(bg_processes))
else:
return data.run_datafeed(val_feed, cfg)
print("Preparing training function...")
# instantiate neural network
input_vars = {name: T.TensorType(str(np.dtype(dtype)),
(False,) * len(shape))(name)
for name, (dtype, shape) in train_formats.items()}
input_shapes = {name: shape
for name, (dtype, shape) in train_formats.items()}
network = model.architecture(input_vars, input_shapes, cfg)
print("- %d layers (%d with weights), %f mio params" %
(len(lasagne.layers.get_all_layers(network)),
sum(hasattr(l, 'W') for l in lasagne.layers.get_all_layers(network)),
lasagne.layers.count_params(network, trainable=True) / 1e6))
print("- weight shapes: %r" % [
l.W.get_value().shape
for l in lasagne.layers.get_all_layers(network)
if hasattr(l, 'W') and hasattr(l.W, 'get_value')])
cost_vars = dict(input_vars)
# prepare for born-again-network, if needed
if cfg.get('ban'):
network2 = model.architecture(input_vars, input_shapes, cfg)
with np.load(cfg['ban'], encoding='latin1') as f:
lasagne.layers.set_all_param_values(
network2, [f['param%d' % i] for i in range(len(f.files))])
cost_vars['pseudo_label'] = lasagne.layers.get_output(
network2, deterministic=True)
# load pre-trained weights, if needed
if cfg.get('init_from'):
param_values = []
for fn in cfg['init_from'].split(':'):
with np.load(fn, encoding='latin1') as f:
param_values.extend(f['param%d' % i]
for i in range(len(f.files)))
lasagne.layers.set_all_param_values(network, param_values)
del param_values
# create cost expression
outputs = lasagne.layers.get_output(network, deterministic=False)
cost = T.mean(model.cost(outputs, cost_vars, 'train', cfg))
if cfg.get('l2_decay', 0):
cost_l2 = lasagne.regularization.regularize_network_params(
network, lasagne.regularization.l2) * cfg['l2_decay']
else:
cost_l2 = 0
# prepare and compile training function
params = lasagne.layers.get_all_params(network, trainable=True)
initial_eta = cfg['initial_eta']
eta_decay = cfg['eta_decay']
eta_decay_every = cfg.get('eta_decay_every', 1)
eta_cycle = tuple(map(float, str(cfg['eta_cycle']).split(':')))
if eta_cycle == (0,):
eta_cycle = (1,) # so eta_cycle=0 equals disabling it
patience = cfg.get('patience', 0)
trials_of_patience = cfg.get('trials_of_patience', 1)
patience_criterion = cfg.get('patience_criterion',
'valid_loss' if options.validate
else 'train_loss')
momentum = cfg['momentum']
first_params = params[:cfg['first_params']]
first_params_eta_scale = cfg['first_params_eta_scale']
if cfg['learn_scheme'] == 'nesterov':
learn_scheme = lasagne.updates.nesterov_momentum
elif cfg['learn_scheme'] == 'momentum':
learn_scheme = lasagne.update.momentum
elif cfg['learn_scheme'] == 'adam':
learn_scheme = lasagne.updates.adam
else:
raise ValueError('Unknown learn_scheme=%s' % cfg['learn_scheme'])
eta = theano.shared(lasagne.utils.floatX(initial_eta))
if not first_params or first_params_eta_scale == 1:
updates = learn_scheme(cost + cost_l2, params, eta, momentum)
else:
grads = theano.grad(cost + cost_l2, params)
updates = learn_scheme(grads[len(first_params):],
params[len(first_params):], eta, momentum)
if first_params_eta_scale > 0:
updates.update(
learn_scheme(grads[:len(first_params)], first_params,
eta * first_params_eta_scale, momentum))
print("Compiling training function...")
train_fn = theano.function(list(input_vars.values()), cost, updates=updates,
on_unused_input='ignore')
# prepare and compile validation function, if requested
if options.validate:
print("Compiling validation function...")
outputs_test = lasagne.layers.get_output(network, deterministic=True)
cost_test = T.mean(model.cost(outputs_test, input_vars, 'valid', cfg))
if isinstance(outputs_test, (list, tuple)):
outputs_test = outputs_test[0]
val_fn = theano.function([input_vars[k] for k in val_formats],
[cost_test, outputs_test],
on_unused_input='ignore')
# restore previous training state, or create fresh training state
state = {}
if options.keep_state:
statefile = modelfile[:-len('.npz')] + '.state'
if os.path.exists(statefile):
print("Restoring training state...")
state = np.load(modelfile[:-len('.npz')] + '.state',
encoding='latin1')
restore_state(network, updates, state['network'])
epochs = cfg['epochs']
epochsize = cfg['epochsize']
batches = iter(batches)
if options.save_errors:
errors = state.get('errors', [])
if first_params and cfg['first_params_log']:
first_params_hist = []
if options.keep_state and os.path.exists(modelfile[:-4] + '.hist.npz'):
with np.load(modelfile[:-4] + '.hist.npz') as f:
first_params_hist = list(zip(*(f['param%d' % i]
for i in range(len(first_params)))))
if patience > 0:
best_error = state.get('best_error', np.inf)
best_state = state.get('best_state') or get_state(network, updates)
patience = state.get('patience', patience)
trials_of_patience = state.get('trials_of_patience', trials_of_patience)
epoch = state.get('epoch', 0)
del state
# run training loop
print("Training:")
for epoch in range(epoch, epochs):
# actual training
err = 0
for batch in progress(
range(epochsize), min_delay=.5,
desc='Epoch %d/%d: Batch ' % (epoch + 1, epochs)):
err += train_fn(**next(batches))
if not np.isfinite(err):
print("\nEncountered NaN loss in training. Aborting.")
sys.exit(1)
if first_params and cfg['first_params_log'] and (batch % cfg['first_params_log'] == 0):
first_params_hist.append(tuple(param.get_value()
for param in first_params))
np.savez(modelfile[:-4] + '.hist.npz',
**{'param%d' % i: param
for i, param in enumerate(zip(*first_params_hist))})
# report training loss
print("Train loss: %.3f" % (err / epochsize))
if options.save_errors:
errors.append(err / epochsize)
# compute and report validation loss, if requested
if options.validate:
import time
t0 = time.time()
# predict in mini-batches
val_err = 0
val_batches = 0
preds = []
truth = []
for batch in run_val_datafeed():
e, p = val_fn(**batch)
val_err += np.sum(e)
val_batches += 1
preds.append(p)
truth.append(batch['label'])
t1 = time.time()
# join mini-batches
preds = np.concatenate(preds) if len(preds) > 1 else preds[0]
truth = np.concatenate(truth) if len(truth) > 1 else truth[0]
# show results
print("Validation loss: %.3f" % (val_err / val_batches))
from eval import evaluate
results = evaluate(preds, truth)
print("Validation error: %.3f" % (1 - results['accuracy']))
print("Validation MAP: %.3f" % results['map'])
print("(took %.2f seconds)" % (t1 - t0))
if options.save_errors:
errors.append(val_err / val_batches)
errors.append(1 - results['accuracy'])
errors.append(results['map'])
# update learning rate and/or apply early stopping, if needed
if patience > 0:
if patience_criterion == 'train_loss':
cur_error = err / epochsize
elif patience_criterion == 'valid_loss':
cur_error = val_err / val_batches
elif patience_criterion == 'valid_error':
cur_error = 1 - results['accuracy']
elif patience_criterion == 'valid_map':
cur_error = 1 - results['map']
if cur_error <= best_error:
best_error = cur_error
best_state = get_state(network, updates)
patience = cfg['patience']
else:
patience -= 1
if patience == 0:
if eta_decay_every == 'trial_of_patience' and eta_decay != 1:
eta.set_value(eta.get_value() * lasagne.utils.floatX(eta_decay))
restore_state(network, updates, best_state)
patience = cfg['patience']
trials_of_patience -= 1
print("Lost patience (%d remaining trials)." % trials_of_patience)
if trials_of_patience == 0:
break
if eta_decay_every != 'trial_of_patience' and eta_decay != 1 and \
(epoch + 1) % eta_decay_every == 0:
eta.set_value(eta.get_value() * lasagne.utils.floatX(eta_decay))
if eta_cycle[epoch % len(eta_cycle)] != 1:
eta.set_value(eta.get_value() *
lasagne.utils.floatX(eta_cycle[epoch % len(eta_cycle)]))
# store current training state, if needed
if options.keep_state:
state = {}
state['epoch'] = epoch + 1
state['network'] = get_state(network, updates)
if options.save_errors:
state['errors'] = errors
if patience > 0:
state['best_error'] = best_error
state['best_state'] = best_state
state['patience'] = patience
state['trials_of_patience'] = trials_of_patience
with open(statefile, 'wb') as f:
pickle.dump(state, f, -1)
del state
# for debugging: print memory use and break into debugger
#import resource, psutil
#print("Memory usage: %.3f MiB / %.3f MiB" %
# (resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 1024.,
# psutil.Process().memory_info()[0] / float(1024**2)))
#import pdb; pdb.set_trace()
# save final network
print("Saving final model")
save_model(modelfile, network, cfg)
if options.save_errors:
np.savez(modelfile[:-len('.npz')] + '.err.npz',
np.asarray(errors).reshape(epoch + 1, -1))
if __name__ == "__main__":
main()
|
[
"numpy.load",
"config.parse_config_file",
"numpy.sum",
"argparse.ArgumentParser",
"model.cost",
"pickle.dump",
"lasagne.regularization.regularize_network_params",
"lasagne.layers.get_output",
"os.path.join",
"data.run_datafeed",
"model.architecture",
"os.path.dirname",
"os.path.exists",
"numpy.isfinite",
"matplotlib.pyplot.colorbar",
"data.split_datafeed",
"io.open",
"lasagne.layers.count_params",
"lasagne.layers.set_all_param_values",
"lasagne.layers.get_all_param_values",
"lasagne.layers.get_all_params",
"data.prepare_datafeed",
"matplotlib.pyplot.show",
"numpy.asarray",
"itertools.islice",
"eval.evaluate",
"theano.grad",
"sys.exit",
"numpy.concatenate",
"numpy.log",
"lasagne.layers.get_all_layers",
"theano.function",
"numpy.dtype",
"lasagne.utils.floatX",
"time.time",
"config.parse_variable_assignments"
] |
[((628, 661), 'argparse.ArgumentParser', 'ArgumentParser', ([], {'description': 'descr'}), '(description=descr)\n', (642, 661), False, 'from argparse import ArgumentParser\n'), ((3855, 3909), 'data.prepare_datafeed', 'data.prepare_datafeed', (['filelist', 'datadir', '"""train"""', 'cfg'], {}), "(filelist, datadir, 'train', cfg)\n", (3876, 3909), False, 'import data\n'), ((7403, 7452), 'model.architecture', 'model.architecture', (['input_vars', 'input_shapes', 'cfg'], {}), '(input_vars, input_shapes, cfg)\n', (7421, 7452), False, 'import model\n'), ((8837, 8892), 'lasagne.layers.get_output', 'lasagne.layers.get_output', (['network'], {'deterministic': '(False)'}), '(network, deterministic=False)\n', (8862, 8892), False, 'import lasagne\n'), ((9214, 9268), 'lasagne.layers.get_all_params', 'lasagne.layers.get_all_params', (['network'], {'trainable': '(True)'}), '(network, trainable=True)\n', (9243, 9268), False, 'import lasagne\n'), ((2550, 2611), 'lasagne.layers.get_all_param_values', 'lasagne.layers.get_all_param_values', (['network'], {'trainable': '(False)'}), '(network, trainable=False)\n', (2585, 2611), False, 'import lasagne\n'), ((3060, 3095), 'io.open', 'io.open', (["(modelfile + '.vars')", 'write'], {}), "(modelfile + '.vars', write)\n", (3067, 3095), False, 'import io\n'), ((3455, 3501), 'config.parse_variable_assignments', 'config.parse_variable_assignments', (['options.var'], {}), '(options.var)\n', (3488, 3501), False, 'import config\n'), ((3553, 3578), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3568, 3578), False, 'import os\n'), ((4114, 4148), 'data.run_datafeed', 'data.run_datafeed', (['train_feed', 'cfg'], {}), '(train_feed, cfg)\n', (4131, 4148), False, 'import data\n'), ((4721, 4755), 'data.run_datafeed', 'data.run_datafeed', (['train_feed', 'cfg'], {}), '(train_feed, cfg)\n', (4738, 4755), False, 'import data\n'), ((5874, 5885), 'time.time', 'time.time', ([], {}), '()\n', (5883, 5885), False, 'import time\n'), ((6029, 6040), 'time.time', 'time.time', ([], {}), '()\n', (6038, 6040), False, 'import time\n'), ((6368, 6426), 'data.prepare_datafeed', 'data.prepare_datafeed', (['filelist_val', 'datadir', '"""valid"""', 'cfg'], {}), "(filelist_val, datadir, 'valid', cfg)\n", (6389, 6426), False, 'import data\n'), ((8038, 8087), 'model.architecture', 'model.architecture', (['input_vars', 'input_shapes', 'cfg'], {}), '(input_vars, input_shapes, cfg)\n', (8056, 8087), False, 'import model\n'), ((8310, 8365), 'lasagne.layers.get_output', 'lasagne.layers.get_output', (['network2'], {'deterministic': '(True)'}), '(network2, deterministic=True)\n', (8335, 8365), False, 'import lasagne\n'), ((8709, 8767), 'lasagne.layers.set_all_param_values', 'lasagne.layers.set_all_param_values', (['network', 'param_values'], {}), '(network, param_values)\n', (8744, 8767), False, 'import lasagne\n'), ((8911, 8955), 'model.cost', 'model.cost', (['outputs', 'cost_vars', '"""train"""', 'cfg'], {}), "(outputs, cost_vars, 'train', cfg)\n", (8921, 8955), False, 'import model\n'), ((10337, 10370), 'lasagne.utils.floatX', 'lasagne.utils.floatX', (['initial_eta'], {}), '(initial_eta)\n', (10357, 10370), False, 'import lasagne\n'), ((10524, 10559), 'theano.grad', 'theano.grad', (['(cost + cost_l2)', 'params'], {}), '(cost + cost_l2, params)\n', (10535, 10559), False, 'import theano\n'), ((11248, 11302), 'lasagne.layers.get_output', 'lasagne.layers.get_output', (['network'], {'deterministic': '(True)'}), '(network, deterministic=True)\n', (11273, 11302), False, 'import lasagne\n'), ((11494, 11604), 'theano.function', 'theano.function', (['[input_vars[k] for k in val_formats]', '[cost_test, outputs_test]'], {'on_unused_input': '"""ignore"""'}), "([input_vars[k] for k in val_formats], [cost_test,\n outputs_test], on_unused_input='ignore')\n", (11509, 11604), False, 'import theano\n'), ((11847, 11872), 'os.path.exists', 'os.path.exists', (['statefile'], {}), '(statefile)\n', (11861, 11872), False, 'import os\n'), ((3410, 3438), 'config.parse_config_file', 'config.parse_config_file', (['fn'], {}), '(fn)\n', (3434, 3438), False, 'import config\n'), ((3715, 3758), 'os.path.join', 'os.path.join', (['datadir', '"""filelists"""', '"""train"""'], {}), "(datadir, 'filelists', 'train')\n", (3727, 3758), False, 'import os\n'), ((4307, 4321), 'matplotlib.pyplot.colorbar', 'plt.colorbar', ([], {}), '()\n', (4319, 4321), True, 'import matplotlib.pyplot as plt\n'), ((4380, 4390), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (4388, 4390), True, 'import matplotlib.pyplot as plt\n'), ((5899, 5978), 'itertools.islice', 'itertools.islice', (['batches', "cfg['benchmark_datafeed']", "cfg['benchmark_datafeed']"], {}), "(batches, cfg['benchmark_datafeed'], cfg['benchmark_datafeed'])\n", (5915, 5978), False, 'import itertools\n'), ((6590, 6631), 'data.split_datafeed', 'data.split_datafeed', (['val_feed', 'multi', 'cfg'], {}), '(val_feed, multi, cfg)\n', (6609, 6631), False, 'import data\n'), ((8101, 8139), 'numpy.load', 'np.load', (["cfg['ban']"], {'encoding': '"""latin1"""'}), "(cfg['ban'], encoding='latin1')\n", (8108, 8139), True, 'import numpy as np\n'), ((9006, 9095), 'lasagne.regularization.regularize_network_params', 'lasagne.regularization.regularize_network_params', (['network', 'lasagne.regularization.l2'], {}), '(network, lasagne.\n regularization.l2)\n', (9054, 9095), False, 'import lasagne\n'), ((11330, 11380), 'model.cost', 'model.cost', (['outputs_test', 'input_vars', '"""valid"""', 'cfg'], {}), "(outputs_test, input_vars, 'valid', cfg)\n", (11340, 11380), False, 'import model\n'), ((12368, 12412), 'os.path.exists', 'os.path.exists', (["(modelfile[:-4] + '.hist.npz')"], {}), "(modelfile[:-4] + '.hist.npz')\n", (12382, 12412), False, 'import os\n'), ((14123, 14134), 'time.time', 'time.time', ([], {}), '()\n', (14132, 14134), False, 'import time\n'), ((14519, 14530), 'time.time', 'time.time', ([], {}), '()\n', (14528, 14530), False, 'import time\n'), ((14867, 14889), 'eval.evaluate', 'evaluate', (['preds', 'truth'], {}), '(preds, truth)\n', (14875, 14889), False, 'from eval import evaluate\n'), ((6220, 6263), 'os.path.join', 'os.path.join', (['datadir', '"""filelists"""', '"""valid"""'], {}), "(datadir, 'filelists', 'valid')\n", (6232, 6263), False, 'import os\n'), ((6981, 7013), 'data.run_datafeed', 'data.run_datafeed', (['val_feed', 'cfg'], {}), '(val_feed, cfg)\n', (6998, 7013), False, 'import data\n'), ((8545, 8575), 'numpy.load', 'np.load', (['fn'], {'encoding': '"""latin1"""'}), "(fn, encoding='latin1')\n", (8552, 8575), True, 'import numpy as np\n'), ((12431, 12468), 'numpy.load', 'np.load', (["(modelfile[:-4] + '.hist.npz')"], {}), "(modelfile[:-4] + '.hist.npz')\n", (12438, 12468), True, 'import numpy as np\n'), ((13290, 13306), 'numpy.isfinite', 'np.isfinite', (['err'], {}), '(err)\n', (13301, 13306), True, 'import numpy as np\n'), ((13395, 13406), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13403, 13406), False, 'import sys\n'), ((14382, 14391), 'numpy.sum', 'np.sum', (['e'], {}), '(e)\n', (14388, 14391), True, 'import numpy as np\n'), ((14583, 14604), 'numpy.concatenate', 'np.concatenate', (['preds'], {}), '(preds)\n', (14597, 14604), True, 'import numpy as np\n'), ((14657, 14678), 'numpy.concatenate', 'np.concatenate', (['truth'], {}), '(truth)\n', (14671, 14678), True, 'import numpy as np\n'), ((17475, 17500), 'pickle.dump', 'pickle.dump', (['state', 'f', '(-1)'], {}), '(state, f, -1)\n', (17486, 17500), False, 'import pickle\n'), ((1868, 1893), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (1883, 1893), False, 'import os\n'), ((4174, 4199), 'numpy.log', 'np.log', (["batch['spect'][0]"], {}), "(batch['spect'][0])\n", (4180, 4199), True, 'import numpy as np\n'), ((4909, 4937), 'data.run_datafeed', 'data.run_datafeed', (['feed', 'cfg'], {}), '(feed, cfg)\n', (4926, 4937), False, 'import data\n'), ((7133, 7148), 'numpy.dtype', 'np.dtype', (['dtype'], {}), '(dtype)\n', (7141, 7148), True, 'import numpy as np\n'), ((7527, 7565), 'lasagne.layers.get_all_layers', 'lasagne.layers.get_all_layers', (['network'], {}), '(network)\n', (7556, 7565), False, 'import lasagne\n'), ((7660, 7712), 'lasagne.layers.count_params', 'lasagne.layers.count_params', (['network'], {'trainable': '(True)'}), '(network, trainable=True)\n', (7687, 7712), False, 'import lasagne\n'), ((7812, 7850), 'lasagne.layers.get_all_layers', 'lasagne.layers.get_all_layers', (['network'], {}), '(network)\n', (7841, 7850), False, 'import lasagne\n'), ((16686, 16717), 'lasagne.utils.floatX', 'lasagne.utils.floatX', (['eta_decay'], {}), '(eta_decay)\n', (16706, 16717), False, 'import lasagne\n'), ((18057, 18075), 'numpy.asarray', 'np.asarray', (['errors'], {}), '(errors)\n', (18067, 18075), True, 'import numpy as np\n'), ((2949, 2993), 'lasagne.layers.get_all_param_values', 'lasagne.layers.get_all_param_values', (['network'], {}), '(network)\n', (2984, 2993), False, 'import lasagne\n'), ((4967, 5015), 'data.split_datafeed', 'data.split_datafeed', (['train_feed', 'bg_threads', 'cfg'], {}), '(train_feed, bg_threads, cfg)\n', (4986, 5015), False, 'import data\n'), ((6788, 6816), 'data.run_datafeed', 'data.run_datafeed', (['feed', 'cfg'], {}), '(feed, cfg)\n', (6805, 6816), False, 'import data\n'), ((5226, 5260), 'data.run_datafeed', 'data.run_datafeed', (['train_feed', 'cfg'], {}), '(train_feed, cfg)\n', (5243, 5260), False, 'import data\n'), ((7608, 7646), 'lasagne.layers.get_all_layers', 'lasagne.layers.get_all_layers', (['network'], {}), '(network)\n', (7637, 7646), False, 'import lasagne\n'), ((16162, 16193), 'lasagne.utils.floatX', 'lasagne.utils.floatX', (['eta_decay'], {}), '(eta_decay)\n', (16182, 16193), False, 'import lasagne\n')]
|
import unittest
import numpy as np
from neurolib.utils.parameterSpace import ParameterSpace
class TestParameterSpace(unittest.TestCase):
def test_parameterspace_init(self):
# init from list
par = ParameterSpace(["a", "b"], [[3], [3]])
# init from dict
par = ParameterSpace({"a": [1, 2], "b": [1, 2]})
# init from dict with numpy arrays
par = ParameterSpace({"a": np.zeros((3)), "b": np.ones((33)),})
def test_parameterspace_kind(self):
# 'point'
par = ParameterSpace(["a", "b"], [[10], [3.0]])
self.assertEqual(par.kind, "point")
# 'bound'
par = ParameterSpace(["a", "b"], [[3.0, 5.0], [0.0, 3.0]])
self.assertEqual(par.kind, "bound")
# 'grid'
par = ParameterSpace(["a", "b"], [[3.0, 3.5, 5.0], [0.0, 3.0]])
self.assertEqual(par.kind, "grid")
def test_parameterspace_attributes(self):
par = ParameterSpace(["a", "b"], [[10], [3.0]])
par.a
par["a"]
par.b
par["c"] = [1, 2, 3]
def test_conversions(self):
par = ParameterSpace({"a": [1, 2], "b": [1, 2]})
par.named_tuple_constructor
par.named_tuple
par.dict()
print(par)
|
[
"numpy.zeros",
"neurolib.utils.parameterSpace.ParameterSpace",
"numpy.ones"
] |
[((218, 256), 'neurolib.utils.parameterSpace.ParameterSpace', 'ParameterSpace', (["['a', 'b']", '[[3], [3]]'], {}), "(['a', 'b'], [[3], [3]])\n", (232, 256), False, 'from neurolib.utils.parameterSpace import ParameterSpace\n'), ((297, 339), 'neurolib.utils.parameterSpace.ParameterSpace', 'ParameterSpace', (["{'a': [1, 2], 'b': [1, 2]}"], {}), "({'a': [1, 2], 'b': [1, 2]})\n", (311, 339), False, 'from neurolib.utils.parameterSpace import ParameterSpace\n'), ((529, 570), 'neurolib.utils.parameterSpace.ParameterSpace', 'ParameterSpace', (["['a', 'b']", '[[10], [3.0]]'], {}), "(['a', 'b'], [[10], [3.0]])\n", (543, 570), False, 'from neurolib.utils.parameterSpace import ParameterSpace\n'), ((648, 700), 'neurolib.utils.parameterSpace.ParameterSpace', 'ParameterSpace', (["['a', 'b']", '[[3.0, 5.0], [0.0, 3.0]]'], {}), "(['a', 'b'], [[3.0, 5.0], [0.0, 3.0]])\n", (662, 700), False, 'from neurolib.utils.parameterSpace import ParameterSpace\n'), ((777, 834), 'neurolib.utils.parameterSpace.ParameterSpace', 'ParameterSpace', (["['a', 'b']", '[[3.0, 3.5, 5.0], [0.0, 3.0]]'], {}), "(['a', 'b'], [[3.0, 3.5, 5.0], [0.0, 3.0]])\n", (791, 834), False, 'from neurolib.utils.parameterSpace import ParameterSpace\n'), ((939, 980), 'neurolib.utils.parameterSpace.ParameterSpace', 'ParameterSpace', (["['a', 'b']", '[[10], [3.0]]'], {}), "(['a', 'b'], [[10], [3.0]])\n", (953, 980), False, 'from neurolib.utils.parameterSpace import ParameterSpace\n'), ((1102, 1144), 'neurolib.utils.parameterSpace.ParameterSpace', 'ParameterSpace', (["{'a': [1, 2], 'b': [1, 2]}"], {}), "({'a': [1, 2], 'b': [1, 2]})\n", (1116, 1144), False, 'from neurolib.utils.parameterSpace import ParameterSpace\n'), ((419, 430), 'numpy.zeros', 'np.zeros', (['(3)'], {}), '(3)\n', (427, 430), True, 'import numpy as np\n'), ((439, 450), 'numpy.ones', 'np.ones', (['(33)'], {}), '(33)\n', (446, 450), True, 'import numpy as np\n')]
|
import json
import os
import random
from unittest.mock import patch
import cv2
import numpy as np
import pytest
import albumentations as A
import albumentations.augmentations.functional as F
from albumentations.core.serialization import SERIALIZABLE_REGISTRY, shorten_class_name
from albumentations.core.transforms_interface import ImageOnlyTransform
from .conftest import skipif_no_torch
from .utils import (
OpenMock,
check_all_augs_exists,
get_dual_transforms,
get_image_only_transforms,
get_transforms,
set_seed,
)
TEST_SEEDS = (0, 1, 42, 111, 9999)
@pytest.mark.parametrize(
["augmentation_cls", "params"],
get_transforms(
custom_arguments={
A.Crop: {"y_min": 0, "y_max": 10, "x_min": 0, "x_max": 10},
A.CenterCrop: {"height": 10, "width": 10},
A.CropNonEmptyMaskIfExists: {"height": 10, "width": 10},
A.RandomCrop: {"height": 10, "width": 10},
A.RandomResizedCrop: {"height": 10, "width": 10},
A.RandomSizedCrop: {"min_max_height": (4, 8), "height": 10, "width": 10},
A.CropAndPad: {"px": 10},
A.Resize: {"height": 10, "width": 10},
},
except_augmentations={
A.RandomCropNearBBox,
A.RandomSizedBBoxSafeCrop,
A.FDA,
A.HistogramMatching,
A.PixelDistributionAdaptation,
A.Lambda,
A.TemplateTransform,
},
),
)
@pytest.mark.parametrize("p", [0.5, 1])
@pytest.mark.parametrize("seed", TEST_SEEDS)
@pytest.mark.parametrize("always_apply", (False, True))
def test_augmentations_serialization(augmentation_cls, params, p, seed, image, mask, always_apply):
aug = augmentation_cls(p=p, always_apply=always_apply, **params)
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(image=image, mask=mask)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, mask=mask)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["mask"], deserialized_aug_data["mask"])
AUGMENTATION_CLS_PARAMS = [
[
A.ImageCompression,
{
"quality_lower": 10,
"quality_upper": 80,
"compression_type": A.ImageCompression.ImageCompressionType.WEBP,
},
],
[A.JpegCompression, {"quality_lower": 10, "quality_upper": 80}],
[A.HueSaturationValue, {"hue_shift_limit": 70, "sat_shift_limit": 95, "val_shift_limit": 55}],
[A.RGBShift, {"r_shift_limit": 70, "g_shift_limit": 80, "b_shift_limit": 40}],
[A.RandomBrightnessContrast, {"brightness_limit": 0.5, "contrast_limit": 0.8}],
[A.Blur, {"blur_limit": 3}],
[A.MotionBlur, {"blur_limit": 3}],
[A.MedianBlur, {"blur_limit": 3}],
[A.GaussianBlur, {"blur_limit": 3}],
[A.GaussNoise, {"var_limit": (20, 90), "mean": 10, "per_channel": False}],
[A.CLAHE, {"clip_limit": 2, "tile_grid_size": (12, 12)}],
[A.RandomGamma, {"gamma_limit": (10, 90)}],
[A.Cutout, {"num_holes": 4, "max_h_size": 4, "max_w_size": 4}],
[A.CoarseDropout, {"max_holes": 4, "max_height": 4, "max_width": 4}],
[A.RandomSnow, {"snow_point_lower": 0.2, "snow_point_upper": 0.4, "brightness_coeff": 4}],
[
A.RandomRain,
{
"slant_lower": -5,
"slant_upper": 5,
"drop_length": 15,
"drop_width": 2,
"drop_color": (100, 100, 100),
"blur_value": 3,
"brightness_coefficient": 0.5,
"rain_type": "heavy",
},
],
[A.RandomFog, {"fog_coef_lower": 0.2, "fog_coef_upper": 0.8, "alpha_coef": 0.11}],
[
A.RandomSunFlare,
{
"flare_roi": (0.1, 0.1, 0.9, 0.6),
"angle_lower": 0.1,
"angle_upper": 0.95,
"num_flare_circles_lower": 7,
"num_flare_circles_upper": 11,
"src_radius": 300,
"src_color": (200, 200, 200),
},
],
[
A.RandomShadow,
{
"shadow_roi": (0.1, 0.4, 0.9, 0.9),
"num_shadows_lower": 2,
"num_shadows_upper": 4,
"shadow_dimension": 8,
},
],
[
A.PadIfNeeded,
{"min_height": 512, "min_width": 512, "border_mode": cv2.BORDER_CONSTANT, "value": (10, 10, 10)},
],
[
A.Rotate,
{
"limit": 120,
"interpolation": cv2.INTER_CUBIC,
"border_mode": cv2.BORDER_CONSTANT,
"value": (10, 10, 10),
},
],
[
A.SafeRotate,
{
"limit": 120,
"interpolation": cv2.INTER_CUBIC,
"border_mode": cv2.BORDER_CONSTANT,
"value": (10, 10, 10),
},
],
[
A.ShiftScaleRotate,
{
"shift_limit": 0.2,
"scale_limit": 0.2,
"rotate_limit": 70,
"interpolation": cv2.INTER_CUBIC,
"border_mode": cv2.BORDER_CONSTANT,
"value": (10, 10, 10),
},
],
[
A.ShiftScaleRotate,
{
"shift_limit_x": 0.3,
"shift_limit_y": 0.4,
"scale_limit": 0.2,
"rotate_limit": 70,
"interpolation": cv2.INTER_CUBIC,
"border_mode": cv2.BORDER_CONSTANT,
"value": (10, 10, 10),
},
],
[
A.OpticalDistortion,
{
"distort_limit": 0.2,
"shift_limit": 0.2,
"interpolation": cv2.INTER_CUBIC,
"border_mode": cv2.BORDER_CONSTANT,
"value": (10, 10, 10),
},
],
[
A.GridDistortion,
{
"num_steps": 10,
"distort_limit": 0.5,
"interpolation": cv2.INTER_CUBIC,
"border_mode": cv2.BORDER_CONSTANT,
"value": (10, 10, 10),
},
],
[
A.ElasticTransform,
{
"alpha": 2,
"sigma": 25,
"alpha_affine": 40,
"interpolation": cv2.INTER_CUBIC,
"border_mode": cv2.BORDER_CONSTANT,
"value": (10, 10, 10),
},
],
[A.CenterCrop, {"height": 10, "width": 10}],
[A.RandomCrop, {"height": 10, "width": 10}],
[A.CropNonEmptyMaskIfExists, {"height": 10, "width": 10}],
[A.RandomSizedCrop, {"min_max_height": (4, 8), "height": 10, "width": 10}],
[A.Crop, {"x_max": 64, "y_max": 64}],
[A.ToFloat, {"max_value": 16536}],
[A.Normalize, {"mean": (0.385, 0.356, 0.306), "std": (0.129, 0.124, 0.125), "max_pixel_value": 100.0}],
[A.RandomBrightness, {"limit": 0.4}],
[A.RandomContrast, {"limit": 0.4}],
[A.RandomScale, {"scale_limit": 0.2, "interpolation": cv2.INTER_CUBIC}],
[A.Resize, {"height": 64, "width": 64}],
[A.SmallestMaxSize, {"max_size": 64, "interpolation": cv2.INTER_CUBIC}],
[A.LongestMaxSize, {"max_size": 128, "interpolation": cv2.INTER_CUBIC}],
[A.RandomGridShuffle, {"grid": (5, 5)}],
[A.Solarize, {"threshold": 32}],
[A.Posterize, {"num_bits": 1}],
[A.Equalize, {"mode": "pil", "by_channels": False}],
[A.MultiplicativeNoise, {"multiplier": (0.7, 2.3), "per_channel": True, "elementwise": True}],
[
A.ColorJitter,
{"brightness": [0.2, 0.3], "contrast": [0.7, 0.9], "saturation": [1.2, 1.7], "hue": [-0.2, 0.1]},
],
[
A.Perspective,
{
"scale": 0.5,
"keep_size": False,
"pad_mode": cv2.BORDER_REFLECT_101,
"pad_val": 10,
"mask_pad_val": 100,
"fit_output": True,
"interpolation": cv2.INTER_CUBIC,
},
],
[A.Sharpen, {"alpha": [0.2, 0.5], "lightness": [0.5, 1.0]}],
[A.Emboss, {"alpha": [0.2, 0.5], "strength": [0.5, 1.0]}],
[A.RandomToneCurve, {"scale": 0.2}],
[
A.CropAndPad,
{
"px": 10,
"keep_size": False,
"sample_independently": False,
"interpolation": cv2.INTER_CUBIC,
"pad_cval_mask": [10, 20, 30],
"pad_cval": [11, 12, 13],
"pad_mode": cv2.BORDER_REFLECT101,
},
],
[
A.Superpixels,
{"p_replace": (0.5, 0.7), "n_segments": (20, 30), "max_size": 25, "interpolation": cv2.INTER_CUBIC},
],
[
A.Affine,
{
"scale": 0.5,
"translate_percent": 0.7,
"translate_px": None,
"rotate": 33,
"shear": 21,
"interpolation": cv2.INTER_CUBIC,
"cval": 25,
"cval_mask": 1,
"mode": cv2.BORDER_REFLECT,
"fit_output": True,
},
],
[
A.Affine,
{
"scale": {"x": [0.3, 0.5], "y": [0.1, 0.2]},
"translate_percent": None,
"translate_px": {"x": [10, 200], "y": [5, 101]},
"rotate": [333, 360],
"shear": {"x": [31, 38], "y": [41, 48]},
"interpolation": 3,
"cval": [10, 20, 30],
"cval_mask": 1,
"mode": cv2.BORDER_REFLECT,
"fit_output": True,
},
],
[
A.PiecewiseAffine,
{
"scale": 0.33,
"nb_rows": (10, 20),
"nb_cols": 33,
"interpolation": 2,
"mask_interpolation": 1,
"cval": 10,
"cval_mask": 20,
"mode": "edge",
"absolute_scale": True,
"keypoints_threshold": 0.1,
},
],
[A.ChannelDropout, dict(channel_drop_range=(1, 2), fill_value=1)],
[A.ChannelShuffle, {}],
[A.Downscale, dict(scale_min=0.5, scale_max=0.75, interpolation=cv2.INTER_LINEAR)],
[A.Flip, {}],
[A.FromFloat, dict(dtype="uint8", max_value=1)],
[A.HorizontalFlip, {}],
[A.ISONoise, dict(color_shift=(0.2, 0.3), intensity=(0.7, 0.9))],
[A.InvertImg, {}],
[A.MaskDropout, dict(max_objects=2, image_fill_value=10, mask_fill_value=20)],
[A.NoOp, {}],
[A.RandomResizedCrop, dict(height=20, width=30, scale=(0.5, 0.6), ratio=(0.8, 0.9))],
[A.FancyPCA, dict(alpha=0.3)],
[A.RandomRotate90, {}],
[A.ToGray, {}],
[A.ToSepia, {}],
[A.Transpose, {}],
[A.VerticalFlip, {}],
[A.RingingOvershoot, dict(blur_limit=(7, 15), cutoff=(np.pi / 5, np.pi / 2))],
[A.UnsharpMask, {"blur_limit": 3, "sigma_limit": 0.5, "alpha": 0.2, "threshold": 15}],
[A.AdvancedBlur, dict(blur_limit=(3, 5), rotate_limit=(60, 90))],
[A.PixelDropout, {"dropout_prob": 0.1, "per_channel": True, "drop_value": None}],
[A.PixelDropout, {"dropout_prob": 0.1, "per_channel": False, "drop_value": None, "mask_drop_value": 15}],
]
AUGMENTATION_CLS_EXCEPT = {
A.FDA,
A.HistogramMatching,
A.PixelDistributionAdaptation,
A.Lambda,
A.RandomCropNearBBox,
A.RandomSizedBBoxSafeCrop,
A.GridDropout,
A.GlassBlur,
A.TemplateTransform,
}
@pytest.mark.parametrize(
["augmentation_cls", "params"], check_all_augs_exists(AUGMENTATION_CLS_PARAMS, AUGMENTATION_CLS_EXCEPT)
)
@pytest.mark.parametrize("p", [0.5, 1])
@pytest.mark.parametrize("seed", TEST_SEEDS)
@pytest.mark.parametrize("always_apply", (False, True))
def test_augmentations_serialization_with_custom_parameters(
augmentation_cls, params, p, seed, image, mask, always_apply
):
aug = augmentation_cls(p=p, always_apply=always_apply, **params)
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(image=image, mask=mask)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, mask=mask)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["mask"], deserialized_aug_data["mask"])
@pytest.mark.parametrize(
["augmentation_cls", "params"], check_all_augs_exists(AUGMENTATION_CLS_PARAMS, AUGMENTATION_CLS_EXCEPT)
)
@pytest.mark.parametrize("p", [0.5, 1])
@pytest.mark.parametrize("seed", TEST_SEEDS)
@pytest.mark.parametrize("always_apply", (False, True))
@pytest.mark.parametrize("data_format", ("yaml",))
def test_augmentations_serialization_to_file_with_custom_parameters(
augmentation_cls, params, p, seed, image, mask, always_apply, data_format
):
with patch("builtins.open", OpenMock()):
aug = augmentation_cls(p=p, always_apply=always_apply, **params)
filepath = "serialized.{}".format(data_format)
A.save(aug, filepath, data_format=data_format)
deserialized_aug = A.load(filepath, data_format=data_format)
set_seed(seed)
aug_data = aug(image=image, mask=mask)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, mask=mask)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["mask"], deserialized_aug_data["mask"])
@pytest.mark.parametrize(
["augmentation_cls", "params"],
get_transforms(
custom_arguments={
A.Crop: {"y_min": 0, "y_max": 10, "x_min": 0, "x_max": 10},
A.CenterCrop: {"height": 10, "width": 10},
A.CropNonEmptyMaskIfExists: {"height": 10, "width": 10},
A.RandomCrop: {"height": 10, "width": 10},
A.RandomResizedCrop: {"height": 10, "width": 10},
A.RandomSizedCrop: {"min_max_height": (4, 8), "height": 10, "width": 10},
A.CropAndPad: {"px": 10},
A.Resize: {"height": 10, "width": 10},
A.RandomSizedBBoxSafeCrop: {"height": 10, "width": 10},
},
except_augmentations={
A.RandomCropNearBBox,
A.FDA,
A.HistogramMatching,
A.PixelDistributionAdaptation,
A.Lambda,
A.CoarseDropout,
A.CropNonEmptyMaskIfExists,
A.ElasticTransform,
A.GridDistortion,
A.RandomGridShuffle,
A.GridDropout,
A.MaskDropout,
A.OpticalDistortion,
A.TemplateTransform,
},
),
)
@pytest.mark.parametrize("p", [0.5, 1])
@pytest.mark.parametrize("seed", TEST_SEEDS)
@pytest.mark.parametrize("always_apply", (False, True))
def test_augmentations_for_bboxes_serialization(
augmentation_cls, params, p, seed, image, albumentations_bboxes, always_apply
):
aug = augmentation_cls(p=p, always_apply=always_apply, **params)
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(image=image, bboxes=albumentations_bboxes)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, bboxes=albumentations_bboxes)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["bboxes"], deserialized_aug_data["bboxes"])
@pytest.mark.parametrize(
["augmentation_cls", "params"],
get_transforms(
custom_arguments={
A.Crop: {"y_min": 0, "y_max": 10, "x_min": 0, "x_max": 10},
A.CenterCrop: {"height": 10, "width": 10},
A.CropNonEmptyMaskIfExists: {"height": 10, "width": 10},
A.RandomCrop: {"height": 10, "width": 10},
A.RandomResizedCrop: {"height": 10, "width": 10},
A.RandomSizedCrop: {"min_max_height": (4, 8), "height": 10, "width": 10},
A.CropAndPad: {"px": 10},
A.Resize: {"height": 10, "width": 10},
},
except_augmentations={
A.RandomCropNearBBox,
A.FDA,
A.HistogramMatching,
A.PixelDistributionAdaptation,
A.Lambda,
A.CoarseDropout,
A.CropNonEmptyMaskIfExists,
A.ElasticTransform,
A.GridDistortion,
A.RandomGridShuffle,
A.GridDropout,
A.MaskDropout,
A.OpticalDistortion,
A.RandomSizedBBoxSafeCrop,
A.TemplateTransform,
},
),
)
@pytest.mark.parametrize("p", [0.5, 1])
@pytest.mark.parametrize("seed", TEST_SEEDS)
@pytest.mark.parametrize("always_apply", (False, True))
def test_augmentations_for_keypoints_serialization(augmentation_cls, params, p, seed, image, keypoints, always_apply):
aug = augmentation_cls(p=p, always_apply=always_apply, **params)
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(image=image, keypoints=keypoints)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, keypoints=keypoints)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["keypoints"], deserialized_aug_data["keypoints"])
@pytest.mark.parametrize(
["augmentation_cls", "params", "call_params"],
[[A.RandomCropNearBBox, {"max_part_shift": 0.15}, {"cropping_bbox": [-59, 77, 177, 231]}]],
)
@pytest.mark.parametrize("p", [0.5, 1])
@pytest.mark.parametrize("seed", TEST_SEEDS)
@pytest.mark.parametrize("always_apply", (False, True))
def test_augmentations_serialization_with_call_params(
augmentation_cls, params, call_params, p, seed, image, always_apply
):
aug = augmentation_cls(p=p, always_apply=always_apply, **params)
annotations = {"image": image, **call_params}
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(**annotations)
set_seed(seed)
deserialized_aug_data = deserialized_aug(**annotations)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
def test_from_float_serialization(float_image):
aug = A.FromFloat(p=1, dtype="uint8")
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
aug_data = aug(image=float_image)
deserialized_aug_data = deserialized_aug(image=float_image)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
@pytest.mark.parametrize("seed", TEST_SEEDS)
def test_transform_pipeline_serialization(seed, image, mask):
aug = A.Compose(
[
A.OneOrOther(
A.Compose(
[
A.Resize(1024, 1024),
A.RandomSizedCrop(min_max_height=(256, 1024), height=512, width=512, p=1),
A.OneOf(
[
A.RandomSizedCrop(min_max_height=(256, 512), height=384, width=384, p=0.5),
A.RandomSizedCrop(min_max_height=(256, 512), height=512, width=512, p=0.5),
]
),
]
),
A.Compose(
[
A.Resize(1024, 1024),
A.RandomSizedCrop(min_max_height=(256, 1025), height=256, width=256, p=1),
A.OneOf([A.HueSaturationValue(p=0.5), A.RGBShift(p=0.7)], p=1),
]
),
),
A.SomeOf(
[
A.HorizontalFlip(p=1),
A.Transpose(p=1),
A.HueSaturationValue(p=0.5),
A.RandomBrightnessContrast(p=0.5),
],
2,
replace=False,
),
]
)
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(image=image, mask=mask)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, mask=mask)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["mask"], deserialized_aug_data["mask"])
@pytest.mark.parametrize(
["bboxes", "bbox_format", "labels"],
[
([(20, 30, 40, 50)], "coco", [1]),
([(20, 30, 40, 50, 99), (10, 40, 30, 20, 9)], "coco", [1, 2]),
([(20, 30, 60, 80)], "pascal_voc", [2]),
([(20, 30, 60, 80, 99)], "pascal_voc", [1]),
([(0.2, 0.3, 0.4, 0.5)], "yolo", [2]),
([(0.2, 0.3, 0.4, 0.5, 99)], "yolo", [1]),
],
)
@pytest.mark.parametrize("seed", TEST_SEEDS)
def test_transform_pipeline_serialization_with_bboxes(seed, image, bboxes, bbox_format, labels):
aug = A.Compose(
[
A.OneOrOther(
A.Compose([A.RandomRotate90(), A.OneOf([A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5)])]),
A.Compose([A.Rotate(p=0.5), A.OneOf([A.HueSaturationValue(p=0.5), A.RGBShift(p=0.7)], p=1)]),
),
A.SomeOf(
[
A.HorizontalFlip(p=1),
A.Transpose(p=1),
A.HueSaturationValue(p=0.5),
A.RandomBrightnessContrast(p=0.5),
],
n=5,
),
],
bbox_params={"format": bbox_format, "label_fields": ["labels"]},
)
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(image=image, bboxes=bboxes, labels=labels)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, bboxes=bboxes, labels=labels)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["bboxes"], deserialized_aug_data["bboxes"])
@pytest.mark.parametrize(
["keypoints", "keypoint_format", "labels"],
[
([(20, 30, 40, 50)], "xyas", [1]),
([(20, 30, 40, 50, 99), (10, 40, 30, 20, 9)], "xy", [1, 2]),
([(20, 30, 60, 80)], "yx", [2]),
([(20, 30, 60, 80, 99)], "xys", [1]),
],
)
@pytest.mark.parametrize("seed", TEST_SEEDS)
def test_transform_pipeline_serialization_with_keypoints(seed, image, keypoints, keypoint_format, labels):
aug = A.Compose(
[
A.OneOrOther(
A.Compose([A.RandomRotate90(), A.OneOf([A.HorizontalFlip(p=0.5), A.VerticalFlip(p=0.5)])]),
A.Compose([A.Rotate(p=0.5), A.OneOf([A.HueSaturationValue(p=0.5), A.RGBShift(p=0.7)], p=1)]),
),
A.SomeOf(
n=2,
transforms=[
A.HorizontalFlip(p=1),
A.Transpose(p=1),
A.HueSaturationValue(p=0.5),
A.RandomBrightnessContrast(p=0.5),
],
replace=False,
),
],
keypoint_params={"format": keypoint_format, "label_fields": ["labels"]},
)
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(image=image, keypoints=keypoints, labels=labels)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, keypoints=keypoints, labels=labels)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["keypoints"], deserialized_aug_data["keypoints"])
@pytest.mark.parametrize(
["augmentation_cls", "params"],
get_image_only_transforms(
except_augmentations={A.HistogramMatching, A.FDA, A.PixelDistributionAdaptation, A.TemplateTransform},
),
)
@pytest.mark.parametrize("seed", TEST_SEEDS)
def test_additional_targets_for_image_only_serialization(augmentation_cls, params, image, seed):
aug = A.Compose([augmentation_cls(always_apply=True, **params)], additional_targets={"image2": "image"})
image2 = image.copy()
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug)
set_seed(seed)
aug_data = aug(image=image, image2=image2)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, image2=image2)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["image2"], deserialized_aug_data["image2"])
@pytest.mark.parametrize("seed", TEST_SEEDS)
@pytest.mark.parametrize("p", [1])
def test_lambda_serialization(image, mask, albumentations_bboxes, keypoints, seed, p):
def vflip_image(image, **kwargs):
return F.vflip(image)
def vflip_mask(mask, **kwargs):
return F.vflip(mask)
def vflip_bbox(bbox, **kwargs):
return F.bbox_vflip(bbox, **kwargs)
def vflip_keypoint(keypoint, **kwargs):
return F.keypoint_vflip(keypoint, **kwargs)
aug = A.Lambda(name="vflip", image=vflip_image, mask=vflip_mask, bbox=vflip_bbox, keypoint=vflip_keypoint, p=p)
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug, lambda_transforms={"vflip": aug})
set_seed(seed)
aug_data = aug(image=image, mask=mask, bboxes=albumentations_bboxes, keypoints=keypoints)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image, mask=mask, bboxes=albumentations_bboxes, keypoints=keypoints)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
assert np.array_equal(aug_data["mask"], deserialized_aug_data["mask"])
assert np.array_equal(aug_data["bboxes"], deserialized_aug_data["bboxes"])
assert np.array_equal(aug_data["keypoints"], deserialized_aug_data["keypoints"])
def test_serialization_v2_conversion_without_totensor():
current_directory = os.path.dirname(os.path.abspath(__file__))
files_directory = os.path.join(current_directory, "files")
transform_1_1_0 = A.load(os.path.join(files_directory, "transform_v1.1.0_without_totensor.json"))
with open(os.path.join(files_directory, "output_v1.1.0_without_totensor.json")) as f:
output_1_1_0 = json.load(f)
np.random.seed(42)
image = np.random.randint(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)
random.seed(42)
transformed_image = transform_1_1_0(image=image)["image"]
assert transformed_image.tolist() == output_1_1_0
@skipif_no_torch
def test_serialization_v2_conversion_with_totensor():
current_directory = os.path.dirname(os.path.abspath(__file__))
files_directory = os.path.join(current_directory, "files")
transform_1_1_0 = A.load(os.path.join(files_directory, "transform_v1.1.0_with_totensor.json"))
with open(os.path.join(files_directory, "output_v1.1.0_with_totensor.json")) as f:
output_1_1_0 = json.load(f)
np.random.seed(42)
image = np.random.randint(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)
random.seed(42)
transformed_image = transform_1_1_0(image=image)["image"]
assert transformed_image.numpy().tolist() == output_1_1_0
def test_serialization_v2_without_totensor():
current_directory = os.path.dirname(os.path.abspath(__file__))
files_directory = os.path.join(current_directory, "files")
transform = A.load(os.path.join(files_directory, "transform_serialization_v2_without_totensor.json"))
with open(os.path.join(files_directory, "output_v1.1.0_without_totensor.json")) as f:
output_1_1_0 = json.load(f)
np.random.seed(42)
image = np.random.randint(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)
random.seed(42)
transformed_image = transform(image=image)["image"]
assert transformed_image.tolist() == output_1_1_0
@skipif_no_torch
def test_serialization_v2_with_totensor():
current_directory = os.path.dirname(os.path.abspath(__file__))
files_directory = os.path.join(current_directory, "files")
transform = A.load(os.path.join(files_directory, "transform_serialization_v2_with_totensor.json"))
with open(os.path.join(files_directory, "output_v1.1.0_with_totensor.json")) as f:
output_1_1_0 = json.load(f)
np.random.seed(42)
image = np.random.randint(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)
random.seed(42)
transformed_image = transform(image=image)["image"]
assert transformed_image.numpy().tolist() == output_1_1_0
def test_custom_transform_with_overlapping_name():
class HorizontalFlip(ImageOnlyTransform):
pass
assert SERIALIZABLE_REGISTRY["HorizontalFlip"] == A.HorizontalFlip
assert SERIALIZABLE_REGISTRY["tests.test_serialization.HorizontalFlip"] == HorizontalFlip
def test_serialization_v2_to_dict():
transform = A.Compose([A.HorizontalFlip()])
transform_dict = A.to_dict(transform)["transform"]
assert transform_dict == {
"__class_fullname__": "Compose",
"p": 1.0,
"transforms": [{"__class_fullname__": "HorizontalFlip", "always_apply": False, "p": 0.5}],
"bbox_params": None,
"keypoint_params": None,
"additional_targets": {},
}
@pytest.mark.parametrize(
["class_fullname", "expected_short_class_name"],
[
["albumentations.augmentations.transforms.HorizontalFlip", "HorizontalFlip"],
["HorizontalFlip", "HorizontalFlip"],
["some_module.HorizontalFlip", "some_module.HorizontalFlip"],
],
)
def test_shorten_class_name(class_fullname, expected_short_class_name):
assert shorten_class_name(class_fullname) == expected_short_class_name
@pytest.mark.parametrize("seed", TEST_SEEDS)
@pytest.mark.parametrize("p", [1])
def test_template_transform_serialization(image, template, seed, p):
template_transform = A.TemplateTransform(name="template", templates=template, p=p)
aug = A.Compose([A.Flip(), template_transform, A.Blur()])
serialized_aug = A.to_dict(aug)
deserialized_aug = A.from_dict(serialized_aug, lambda_transforms={"template": template_transform})
set_seed(seed)
aug_data = aug(image=image)
set_seed(seed)
deserialized_aug_data = deserialized_aug(image=image)
assert np.array_equal(aug_data["image"], deserialized_aug_data["image"])
|
[
"albumentations.Lambda",
"numpy.random.seed",
"albumentations.Resize",
"albumentations.Flip",
"albumentations.Rotate",
"numpy.random.randint",
"albumentations.TemplateTransform",
"albumentations.load",
"pytest.mark.parametrize",
"albumentations.HorizontalFlip",
"os.path.join",
"albumentations.RGBShift",
"albumentations.from_dict",
"albumentations.Blur",
"os.path.abspath",
"albumentations.save",
"albumentations.core.serialization.shorten_class_name",
"random.seed",
"albumentations.augmentations.functional.bbox_vflip",
"albumentations.to_dict",
"albumentations.augmentations.functional.keypoint_vflip",
"albumentations.RandomSizedCrop",
"albumentations.VerticalFlip",
"json.load",
"albumentations.HueSaturationValue",
"albumentations.RandomBrightnessContrast",
"albumentations.Transpose",
"albumentations.augmentations.functional.vflip",
"albumentations.FromFloat",
"numpy.array_equal",
"albumentations.RandomRotate90"
] |
[((1467, 1505), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""p"""', '[0.5, 1]'], {}), "('p', [0.5, 1])\n", (1490, 1505), False, 'import pytest\n'), ((1507, 1550), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (1530, 1550), False, 'import pytest\n'), ((1552, 1606), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""always_apply"""', '(False, True)'], {}), "('always_apply', (False, True))\n", (1575, 1606), False, 'import pytest\n'), ((11113, 11151), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""p"""', '[0.5, 1]'], {}), "('p', [0.5, 1])\n", (11136, 11151), False, 'import pytest\n'), ((11153, 11196), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (11176, 11196), False, 'import pytest\n'), ((11198, 11252), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""always_apply"""', '(False, True)'], {}), "('always_apply', (False, True))\n", (11221, 11252), False, 'import pytest\n'), ((11979, 12017), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""p"""', '[0.5, 1]'], {}), "('p', [0.5, 1])\n", (12002, 12017), False, 'import pytest\n'), ((12019, 12062), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (12042, 12062), False, 'import pytest\n'), ((12064, 12118), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""always_apply"""', '(False, True)'], {}), "('always_apply', (False, True))\n", (12087, 12118), False, 'import pytest\n'), ((12120, 12169), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""data_format"""', "('yaml',)"], {}), "('data_format', ('yaml',))\n", (12143, 12169), False, 'import pytest\n'), ((14108, 14146), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""p"""', '[0.5, 1]'], {}), "('p', [0.5, 1])\n", (14131, 14146), False, 'import pytest\n'), ((14148, 14191), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (14171, 14191), False, 'import pytest\n'), ((14193, 14247), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""always_apply"""', '(False, True)'], {}), "('always_apply', (False, True))\n", (14216, 14247), False, 'import pytest\n'), ((16018, 16056), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""p"""', '[0.5, 1]'], {}), "('p', [0.5, 1])\n", (16041, 16056), False, 'import pytest\n'), ((16058, 16101), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (16081, 16101), False, 'import pytest\n'), ((16103, 16157), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""always_apply"""', '(False, True)'], {}), "('always_apply', (False, True))\n", (16126, 16157), False, 'import pytest\n'), ((16768, 16940), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['augmentation_cls', 'params', 'call_params']", "[[A.RandomCropNearBBox, {'max_part_shift': 0.15}, {'cropping_bbox': [-59, \n 77, 177, 231]}]]"], {}), "(['augmentation_cls', 'params', 'call_params'], [[A.\n RandomCropNearBBox, {'max_part_shift': 0.15}, {'cropping_bbox': [-59, \n 77, 177, 231]}]])\n", (16791, 16940), False, 'import pytest\n'), ((16943, 16981), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""p"""', '[0.5, 1]'], {}), "('p', [0.5, 1])\n", (16966, 16981), False, 'import pytest\n'), ((16983, 17026), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (17006, 17026), False, 'import pytest\n'), ((17028, 17082), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""always_apply"""', '(False, True)'], {}), "('always_apply', (False, True))\n", (17051, 17082), False, 'import pytest\n'), ((17989, 18032), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (18012, 18032), False, 'import pytest\n'), ((19778, 20123), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['bboxes', 'bbox_format', 'labels']", "[([(20, 30, 40, 50)], 'coco', [1]), ([(20, 30, 40, 50, 99), (10, 40, 30, 20,\n 9)], 'coco', [1, 2]), ([(20, 30, 60, 80)], 'pascal_voc', [2]), ([(20, \n 30, 60, 80, 99)], 'pascal_voc', [1]), ([(0.2, 0.3, 0.4, 0.5)], 'yolo',\n [2]), ([(0.2, 0.3, 0.4, 0.5, 99)], 'yolo', [1])]"], {}), "(['bboxes', 'bbox_format', 'labels'], [([(20, 30, 40,\n 50)], 'coco', [1]), ([(20, 30, 40, 50, 99), (10, 40, 30, 20, 9)],\n 'coco', [1, 2]), ([(20, 30, 60, 80)], 'pascal_voc', [2]), ([(20, 30, 60,\n 80, 99)], 'pascal_voc', [1]), ([(0.2, 0.3, 0.4, 0.5)], 'yolo', [2]), ([\n (0.2, 0.3, 0.4, 0.5, 99)], 'yolo', [1])])\n", (19801, 20123), False, 'import pytest\n'), ((20174, 20217), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (20197, 20217), False, 'import pytest\n'), ((21409, 21659), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['keypoints', 'keypoint_format', 'labels']", "[([(20, 30, 40, 50)], 'xyas', [1]), ([(20, 30, 40, 50, 99), (10, 40, 30, 20,\n 9)], 'xy', [1, 2]), ([(20, 30, 60, 80)], 'yx', [2]), ([(20, 30, 60, 80,\n 99)], 'xys', [1])]"], {}), "(['keypoints', 'keypoint_format', 'labels'], [([(20,\n 30, 40, 50)], 'xyas', [1]), ([(20, 30, 40, 50, 99), (10, 40, 30, 20, 9)\n ], 'xy', [1, 2]), ([(20, 30, 60, 80)], 'yx', [2]), ([(20, 30, 60, 80, \n 99)], 'xys', [1])])\n", (21432, 21659), False, 'import pytest\n'), ((21697, 21740), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (21720, 21740), False, 'import pytest\n'), ((23223, 23266), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (23246, 23266), False, 'import pytest\n'), ((23904, 23947), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (23927, 23947), False, 'import pytest\n'), ((23949, 23982), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""p"""', '[1]'], {}), "('p', [1])\n", (23972, 23982), False, 'import pytest\n'), ((28545, 28811), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (["['class_fullname', 'expected_short_class_name']", "[['albumentations.augmentations.transforms.HorizontalFlip',\n 'HorizontalFlip'], ['HorizontalFlip', 'HorizontalFlip'], [\n 'some_module.HorizontalFlip', 'some_module.HorizontalFlip']]"], {}), "(['class_fullname', 'expected_short_class_name'], [[\n 'albumentations.augmentations.transforms.HorizontalFlip',\n 'HorizontalFlip'], ['HorizontalFlip', 'HorizontalFlip'], [\n 'some_module.HorizontalFlip', 'some_module.HorizontalFlip']])\n", (28568, 28811), False, 'import pytest\n'), ((28990, 29033), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""seed"""', 'TEST_SEEDS'], {}), "('seed', TEST_SEEDS)\n", (29013, 29033), False, 'import pytest\n'), ((29035, 29068), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""p"""', '[1]'], {}), "('p', [1])\n", (29058, 29068), False, 'import pytest\n'), ((1797, 1811), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (1806, 1811), True, 'import albumentations as A\n'), ((1835, 1862), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (1846, 1862), True, 'import albumentations as A\n'), ((2024, 2089), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (2038, 2089), True, 'import numpy as np\n'), ((2101, 2164), 'numpy.array_equal', 'np.array_equal', (["aug_data['mask']", "deserialized_aug_data['mask']"], {}), "(aug_data['mask'], deserialized_aug_data['mask'])\n", (2115, 2164), True, 'import numpy as np\n'), ((11472, 11486), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (11481, 11486), True, 'import albumentations as A\n'), ((11510, 11537), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (11521, 11537), True, 'import albumentations as A\n'), ((11699, 11764), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (11713, 11764), True, 'import numpy as np\n'), ((11776, 11839), 'numpy.array_equal', 'np.array_equal', (["aug_data['mask']", "deserialized_aug_data['mask']"], {}), "(aug_data['mask'], deserialized_aug_data['mask'])\n", (11790, 11839), True, 'import numpy as np\n'), ((14472, 14486), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (14481, 14486), True, 'import albumentations as A\n'), ((14510, 14537), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (14521, 14537), True, 'import albumentations as A\n'), ((14737, 14802), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (14751, 14802), True, 'import numpy as np\n'), ((14814, 14881), 'numpy.array_equal', 'np.array_equal', (["aug_data['bboxes']", "deserialized_aug_data['bboxes']"], {}), "(aug_data['bboxes'], deserialized_aug_data['bboxes'])\n", (14828, 14881), True, 'import numpy as np\n'), ((16367, 16381), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (16376, 16381), True, 'import albumentations as A\n'), ((16405, 16432), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (16416, 16432), True, 'import albumentations as A\n'), ((16614, 16679), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (16628, 16679), True, 'import numpy as np\n'), ((16691, 16764), 'numpy.array_equal', 'np.array_equal', (["aug_data['keypoints']", "deserialized_aug_data['keypoints']"], {}), "(aug_data['keypoints'], deserialized_aug_data['keypoints'])\n", (16705, 16764), True, 'import numpy as np\n'), ((17353, 17367), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (17362, 17367), True, 'import albumentations as A\n'), ((17391, 17418), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (17402, 17418), True, 'import albumentations as A\n'), ((17562, 17627), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (17576, 17627), True, 'import numpy as np\n'), ((17688, 17719), 'albumentations.FromFloat', 'A.FromFloat', ([], {'p': '(1)', 'dtype': '"""uint8"""'}), "(p=1, dtype='uint8')\n", (17699, 17719), True, 'import albumentations as A\n'), ((17741, 17755), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (17750, 17755), True, 'import albumentations as A\n'), ((17779, 17806), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (17790, 17806), True, 'import albumentations as A\n'), ((17920, 17985), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (17934, 17985), True, 'import numpy as np\n'), ((19407, 19421), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (19416, 19421), True, 'import albumentations as A\n'), ((19445, 19472), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (19456, 19472), True, 'import albumentations as A\n'), ((19634, 19699), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (19648, 19699), True, 'import numpy as np\n'), ((19711, 19774), 'numpy.array_equal', 'np.array_equal', (["aug_data['mask']", "deserialized_aug_data['mask']"], {}), "(aug_data['mask'], deserialized_aug_data['mask'])\n", (19725, 19774), True, 'import numpy as np\n'), ((20996, 21010), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (21005, 21010), True, 'import albumentations as A\n'), ((21034, 21061), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (21045, 21061), True, 'import albumentations as A\n'), ((21261, 21326), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (21275, 21326), True, 'import numpy as np\n'), ((21338, 21405), 'numpy.array_equal', 'np.array_equal', (["aug_data['bboxes']", "deserialized_aug_data['bboxes']"], {}), "(aug_data['bboxes'], deserialized_aug_data['bboxes'])\n", (21352, 21405), True, 'import numpy as np\n'), ((22579, 22593), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (22588, 22593), True, 'import albumentations as A\n'), ((22617, 22644), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (22628, 22644), True, 'import albumentations as A\n'), ((22856, 22921), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (22870, 22921), True, 'import numpy as np\n'), ((22933, 23006), 'numpy.array_equal', 'np.array_equal', (["aug_data['keypoints']", "deserialized_aug_data['keypoints']"], {}), "(aug_data['keypoints'], deserialized_aug_data['keypoints'])\n", (22947, 23006), True, 'import numpy as np\n'), ((23521, 23535), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (23530, 23535), True, 'import albumentations as A\n'), ((23559, 23586), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {}), '(serialized_aug)\n', (23570, 23586), True, 'import albumentations as A\n'), ((23756, 23821), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (23770, 23821), True, 'import numpy as np\n'), ((23833, 23900), 'numpy.array_equal', 'np.array_equal', (["aug_data['image2']", "deserialized_aug_data['image2']"], {}), "(aug_data['image2'], deserialized_aug_data['image2'])\n", (23847, 23900), True, 'import numpy as np\n'), ((24393, 24502), 'albumentations.Lambda', 'A.Lambda', ([], {'name': '"""vflip"""', 'image': 'vflip_image', 'mask': 'vflip_mask', 'bbox': 'vflip_bbox', 'keypoint': 'vflip_keypoint', 'p': 'p'}), "(name='vflip', image=vflip_image, mask=vflip_mask, bbox=vflip_bbox,\n keypoint=vflip_keypoint, p=p)\n", (24401, 24502), True, 'import albumentations as A\n'), ((24521, 24535), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (24530, 24535), True, 'import albumentations as A\n'), ((24559, 24620), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {'lambda_transforms': "{'vflip': aug}"}), "(serialized_aug, lambda_transforms={'vflip': aug})\n", (24570, 24620), True, 'import albumentations as A\n'), ((24884, 24949), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (24898, 24949), True, 'import numpy as np\n'), ((24961, 25024), 'numpy.array_equal', 'np.array_equal', (["aug_data['mask']", "deserialized_aug_data['mask']"], {}), "(aug_data['mask'], deserialized_aug_data['mask'])\n", (24975, 25024), True, 'import numpy as np\n'), ((25036, 25103), 'numpy.array_equal', 'np.array_equal', (["aug_data['bboxes']", "deserialized_aug_data['bboxes']"], {}), "(aug_data['bboxes'], deserialized_aug_data['bboxes'])\n", (25050, 25103), True, 'import numpy as np\n'), ((25115, 25188), 'numpy.array_equal', 'np.array_equal', (["aug_data['keypoints']", "deserialized_aug_data['keypoints']"], {}), "(aug_data['keypoints'], deserialized_aug_data['keypoints'])\n", (25129, 25188), True, 'import numpy as np\n'), ((25337, 25377), 'os.path.join', 'os.path.join', (['current_directory', '"""files"""'], {}), "(current_directory, 'files')\n", (25349, 25377), False, 'import os\n'), ((25610, 25628), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (25624, 25628), True, 'import numpy as np\n'), ((25641, 25711), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(255)', 'size': '(256, 256, 3)', 'dtype': 'np.uint8'}), '(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)\n', (25658, 25711), True, 'import numpy as np\n'), ((25716, 25731), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (25727, 25731), False, 'import random\n'), ((26010, 26050), 'os.path.join', 'os.path.join', (['current_directory', '"""files"""'], {}), "(current_directory, 'files')\n", (26022, 26050), False, 'import os\n'), ((26277, 26295), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (26291, 26295), True, 'import numpy as np\n'), ((26308, 26378), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(255)', 'size': '(256, 256, 3)', 'dtype': 'np.uint8'}), '(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)\n', (26325, 26378), True, 'import numpy as np\n'), ((26383, 26398), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (26394, 26398), False, 'import random\n'), ((26660, 26700), 'os.path.join', 'os.path.join', (['current_directory', '"""files"""'], {}), "(current_directory, 'files')\n", (26672, 26700), False, 'import os\n'), ((26937, 26955), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (26951, 26955), True, 'import numpy as np\n'), ((26968, 27038), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(255)', 'size': '(256, 256, 3)', 'dtype': 'np.uint8'}), '(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)\n', (26985, 27038), True, 'import numpy as np\n'), ((27043, 27058), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (27054, 27058), False, 'import random\n'), ((27320, 27360), 'os.path.join', 'os.path.join', (['current_directory', '"""files"""'], {}), "(current_directory, 'files')\n", (27332, 27360), False, 'import os\n'), ((27591, 27609), 'numpy.random.seed', 'np.random.seed', (['(42)'], {}), '(42)\n', (27605, 27609), True, 'import numpy as np\n'), ((27622, 27692), 'numpy.random.randint', 'np.random.randint', ([], {'low': '(0)', 'high': '(255)', 'size': '(256, 256, 3)', 'dtype': 'np.uint8'}), '(low=0, high=255, size=(256, 256, 3), dtype=np.uint8)\n', (27639, 27692), True, 'import numpy as np\n'), ((27697, 27712), 'random.seed', 'random.seed', (['(42)'], {}), '(42)\n', (27708, 27712), False, 'import random\n'), ((29163, 29224), 'albumentations.TemplateTransform', 'A.TemplateTransform', ([], {'name': '"""template"""', 'templates': 'template', 'p': 'p'}), "(name='template', templates=template, p=p)\n", (29182, 29224), True, 'import albumentations as A\n'), ((29310, 29324), 'albumentations.to_dict', 'A.to_dict', (['aug'], {}), '(aug)\n', (29319, 29324), True, 'import albumentations as A\n'), ((29348, 29427), 'albumentations.from_dict', 'A.from_dict', (['serialized_aug'], {'lambda_transforms': "{'template': template_transform}"}), "(serialized_aug, lambda_transforms={'template': template_transform})\n", (29359, 29427), True, 'import albumentations as A\n'), ((29569, 29634), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (29583, 29634), True, 'import numpy as np\n'), ((12501, 12547), 'albumentations.save', 'A.save', (['aug', 'filepath'], {'data_format': 'data_format'}), '(aug, filepath, data_format=data_format)\n', (12507, 12547), True, 'import albumentations as A\n'), ((12575, 12616), 'albumentations.load', 'A.load', (['filepath'], {'data_format': 'data_format'}), '(filepath, data_format=data_format)\n', (12581, 12616), True, 'import albumentations as A\n'), ((12798, 12863), 'numpy.array_equal', 'np.array_equal', (["aug_data['image']", "deserialized_aug_data['image']"], {}), "(aug_data['image'], deserialized_aug_data['image'])\n", (12812, 12863), True, 'import numpy as np\n'), ((12879, 12942), 'numpy.array_equal', 'np.array_equal', (["aug_data['mask']", "deserialized_aug_data['mask']"], {}), "(aug_data['mask'], deserialized_aug_data['mask'])\n", (12893, 12942), True, 'import numpy as np\n'), ((24123, 24137), 'albumentations.augmentations.functional.vflip', 'F.vflip', (['image'], {}), '(image)\n', (24130, 24137), True, 'import albumentations.augmentations.functional as F\n'), ((24190, 24203), 'albumentations.augmentations.functional.vflip', 'F.vflip', (['mask'], {}), '(mask)\n', (24197, 24203), True, 'import albumentations.augmentations.functional as F\n'), ((24256, 24284), 'albumentations.augmentations.functional.bbox_vflip', 'F.bbox_vflip', (['bbox'], {}), '(bbox, **kwargs)\n', (24268, 24284), True, 'import albumentations.augmentations.functional as F\n'), ((24345, 24381), 'albumentations.augmentations.functional.keypoint_vflip', 'F.keypoint_vflip', (['keypoint'], {}), '(keypoint, **kwargs)\n', (24361, 24381), True, 'import albumentations.augmentations.functional as F\n'), ((25288, 25313), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (25303, 25313), False, 'import os\n'), ((25407, 25478), 'os.path.join', 'os.path.join', (['files_directory', '"""transform_v1.1.0_without_totensor.json"""'], {}), "(files_directory, 'transform_v1.1.0_without_totensor.json')\n", (25419, 25478), False, 'import os\n'), ((25593, 25605), 'json.load', 'json.load', (['f'], {}), '(f)\n', (25602, 25605), False, 'import json\n'), ((25961, 25986), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (25976, 25986), False, 'import os\n'), ((26080, 26148), 'os.path.join', 'os.path.join', (['files_directory', '"""transform_v1.1.0_with_totensor.json"""'], {}), "(files_directory, 'transform_v1.1.0_with_totensor.json')\n", (26092, 26148), False, 'import os\n'), ((26260, 26272), 'json.load', 'json.load', (['f'], {}), '(f)\n', (26269, 26272), False, 'import json\n'), ((26611, 26636), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (26626, 26636), False, 'import os\n'), ((26724, 26809), 'os.path.join', 'os.path.join', (['files_directory', '"""transform_serialization_v2_without_totensor.json"""'], {}), "(files_directory,\n 'transform_serialization_v2_without_totensor.json')\n", (26736, 26809), False, 'import os\n'), ((26920, 26932), 'json.load', 'json.load', (['f'], {}), '(f)\n', (26929, 26932), False, 'import json\n'), ((27271, 27296), 'os.path.abspath', 'os.path.abspath', (['__file__'], {}), '(__file__)\n', (27286, 27296), False, 'import os\n'), ((27384, 27462), 'os.path.join', 'os.path.join', (['files_directory', '"""transform_serialization_v2_with_totensor.json"""'], {}), "(files_directory, 'transform_serialization_v2_with_totensor.json')\n", (27396, 27462), False, 'import os\n'), ((27574, 27586), 'json.load', 'json.load', (['f'], {}), '(f)\n', (27583, 27586), False, 'import json\n'), ((28217, 28237), 'albumentations.to_dict', 'A.to_dict', (['transform'], {}), '(transform)\n', (28226, 28237), True, 'import albumentations as A\n'), ((28923, 28957), 'albumentations.core.serialization.shorten_class_name', 'shorten_class_name', (['class_fullname'], {}), '(class_fullname)\n', (28941, 28957), False, 'from albumentations.core.serialization import SERIALIZABLE_REGISTRY, shorten_class_name\n'), ((25494, 25562), 'os.path.join', 'os.path.join', (['files_directory', '"""output_v1.1.0_without_totensor.json"""'], {}), "(files_directory, 'output_v1.1.0_without_totensor.json')\n", (25506, 25562), False, 'import os\n'), ((26164, 26229), 'os.path.join', 'os.path.join', (['files_directory', '"""output_v1.1.0_with_totensor.json"""'], {}), "(files_directory, 'output_v1.1.0_with_totensor.json')\n", (26176, 26229), False, 'import os\n'), ((26821, 26889), 'os.path.join', 'os.path.join', (['files_directory', '"""output_v1.1.0_without_totensor.json"""'], {}), "(files_directory, 'output_v1.1.0_without_totensor.json')\n", (26833, 26889), False, 'import os\n'), ((27478, 27543), 'os.path.join', 'os.path.join', (['files_directory', '"""output_v1.1.0_with_totensor.json"""'], {}), "(files_directory, 'output_v1.1.0_with_totensor.json')\n", (27490, 27543), False, 'import os\n'), ((28175, 28193), 'albumentations.HorizontalFlip', 'A.HorizontalFlip', ([], {}), '()\n', (28191, 28193), True, 'import albumentations as A\n'), ((29247, 29255), 'albumentations.Flip', 'A.Flip', ([], {}), '()\n', (29253, 29255), True, 'import albumentations as A\n'), ((29277, 29285), 'albumentations.Blur', 'A.Blur', ([], {}), '()\n', (29283, 29285), True, 'import albumentations as A\n'), ((19121, 19142), 'albumentations.HorizontalFlip', 'A.HorizontalFlip', ([], {'p': '(1)'}), '(p=1)\n', (19137, 19142), True, 'import albumentations as A\n'), ((19164, 19180), 'albumentations.Transpose', 'A.Transpose', ([], {'p': '(1)'}), '(p=1)\n', (19175, 19180), True, 'import albumentations as A\n'), ((19202, 19229), 'albumentations.HueSaturationValue', 'A.HueSaturationValue', ([], {'p': '(0.5)'}), '(p=0.5)\n', (19222, 19229), True, 'import albumentations as A\n'), ((19251, 19284), 'albumentations.RandomBrightnessContrast', 'A.RandomBrightnessContrast', ([], {'p': '(0.5)'}), '(p=0.5)\n', (19277, 19284), True, 'import albumentations as A\n'), ((20665, 20686), 'albumentations.HorizontalFlip', 'A.HorizontalFlip', ([], {'p': '(1)'}), '(p=1)\n', (20681, 20686), True, 'import albumentations as A\n'), ((20708, 20724), 'albumentations.Transpose', 'A.Transpose', ([], {'p': '(1)'}), '(p=1)\n', (20719, 20724), True, 'import albumentations as A\n'), ((20746, 20773), 'albumentations.HueSaturationValue', 'A.HueSaturationValue', ([], {'p': '(0.5)'}), '(p=0.5)\n', (20766, 20773), True, 'import albumentations as A\n'), ((20795, 20828), 'albumentations.RandomBrightnessContrast', 'A.RandomBrightnessContrast', ([], {'p': '(0.5)'}), '(p=0.5)\n', (20821, 20828), True, 'import albumentations as A\n'), ((18225, 18245), 'albumentations.Resize', 'A.Resize', (['(1024)', '(1024)'], {}), '(1024, 1024)\n', (18233, 18245), True, 'import albumentations as A\n'), ((18271, 18344), 'albumentations.RandomSizedCrop', 'A.RandomSizedCrop', ([], {'min_max_height': '(256, 1024)', 'height': '(512)', 'width': '(512)', 'p': '(1)'}), '(min_max_height=(256, 1024), height=512, width=512, p=1)\n', (18288, 18344), True, 'import albumentations as A\n'), ((18796, 18816), 'albumentations.Resize', 'A.Resize', (['(1024)', '(1024)'], {}), '(1024, 1024)\n', (18804, 18816), True, 'import albumentations as A\n'), ((18842, 18915), 'albumentations.RandomSizedCrop', 'A.RandomSizedCrop', ([], {'min_max_height': '(256, 1025)', 'height': '(256)', 'width': '(256)', 'p': '(1)'}), '(min_max_height=(256, 1025), height=256, width=256, p=1)\n', (18859, 18915), True, 'import albumentations as A\n'), ((20399, 20417), 'albumentations.RandomRotate90', 'A.RandomRotate90', ([], {}), '()\n', (20415, 20417), True, 'import albumentations as A\n'), ((20507, 20522), 'albumentations.Rotate', 'A.Rotate', ([], {'p': '(0.5)'}), '(p=0.5)\n', (20515, 20522), True, 'import albumentations as A\n'), ((21932, 21950), 'albumentations.RandomRotate90', 'A.RandomRotate90', ([], {}), '()\n', (21948, 21950), True, 'import albumentations as A\n'), ((22040, 22055), 'albumentations.Rotate', 'A.Rotate', ([], {'p': '(0.5)'}), '(p=0.5)\n', (22048, 22055), True, 'import albumentations as A\n'), ((22230, 22251), 'albumentations.HorizontalFlip', 'A.HorizontalFlip', ([], {'p': '(1)'}), '(p=1)\n', (22246, 22251), True, 'import albumentations as A\n'), ((22273, 22289), 'albumentations.Transpose', 'A.Transpose', ([], {'p': '(1)'}), '(p=1)\n', (22284, 22289), True, 'import albumentations as A\n'), ((22311, 22338), 'albumentations.HueSaturationValue', 'A.HueSaturationValue', ([], {'p': '(0.5)'}), '(p=0.5)\n', (22331, 22338), True, 'import albumentations as A\n'), ((22360, 22393), 'albumentations.RandomBrightnessContrast', 'A.RandomBrightnessContrast', ([], {'p': '(0.5)'}), '(p=0.5)\n', (22386, 22393), True, 'import albumentations as A\n'), ((18441, 18515), 'albumentations.RandomSizedCrop', 'A.RandomSizedCrop', ([], {'min_max_height': '(256, 512)', 'height': '(384)', 'width': '(384)', 'p': '(0.5)'}), '(min_max_height=(256, 512), height=384, width=384, p=0.5)\n', (18458, 18515), True, 'import albumentations as A\n'), ((18549, 18623), 'albumentations.RandomSizedCrop', 'A.RandomSizedCrop', ([], {'min_max_height': '(256, 512)', 'height': '(512)', 'width': '(512)', 'p': '(0.5)'}), '(min_max_height=(256, 512), height=512, width=512, p=0.5)\n', (18566, 18623), True, 'import albumentations as A\n'), ((18950, 18977), 'albumentations.HueSaturationValue', 'A.HueSaturationValue', ([], {'p': '(0.5)'}), '(p=0.5)\n', (18970, 18977), True, 'import albumentations as A\n'), ((18979, 18996), 'albumentations.RGBShift', 'A.RGBShift', ([], {'p': '(0.7)'}), '(p=0.7)\n', (18989, 18996), True, 'import albumentations as A\n'), ((20428, 20451), 'albumentations.HorizontalFlip', 'A.HorizontalFlip', ([], {'p': '(0.5)'}), '(p=0.5)\n', (20444, 20451), True, 'import albumentations as A\n'), ((20453, 20474), 'albumentations.VerticalFlip', 'A.VerticalFlip', ([], {'p': '(0.5)'}), '(p=0.5)\n', (20467, 20474), True, 'import albumentations as A\n'), ((20533, 20560), 'albumentations.HueSaturationValue', 'A.HueSaturationValue', ([], {'p': '(0.5)'}), '(p=0.5)\n', (20553, 20560), True, 'import albumentations as A\n'), ((20562, 20579), 'albumentations.RGBShift', 'A.RGBShift', ([], {'p': '(0.7)'}), '(p=0.7)\n', (20572, 20579), True, 'import albumentations as A\n'), ((21961, 21984), 'albumentations.HorizontalFlip', 'A.HorizontalFlip', ([], {'p': '(0.5)'}), '(p=0.5)\n', (21977, 21984), True, 'import albumentations as A\n'), ((21986, 22007), 'albumentations.VerticalFlip', 'A.VerticalFlip', ([], {'p': '(0.5)'}), '(p=0.5)\n', (22000, 22007), True, 'import albumentations as A\n'), ((22066, 22093), 'albumentations.HueSaturationValue', 'A.HueSaturationValue', ([], {'p': '(0.5)'}), '(p=0.5)\n', (22086, 22093), True, 'import albumentations as A\n'), ((22095, 22112), 'albumentations.RGBShift', 'A.RGBShift', ([], {'p': '(0.7)'}), '(p=0.7)\n', (22105, 22112), True, 'import albumentations as A\n')]
|
from time import perf_counter as clock
import subprocess
import random
import numpy
# Constants
STEP = 1000 * 100 # the size of the buffer to fill the table, in rows
SCALE = 0.1 # standard deviation of the noise compared with actual
# values
NI_NTIMES = 1 # The number of queries for doing a mean (non-idx cols)
# COLDCACHE = 10 # The number of reads where the cache is considered 'cold'
# WARMCACHE = 50 # The number of reads until the cache is considered 'warmed'
# READ_TIMES = WARMCACHE+50 # The number of complete calls to DB.query_db()
# COLDCACHE = 50 # The number of reads where the cache is considered 'cold'
# WARMCACHE = 50 # The number of reads until the cache is considered 'warmed'
# READ_TIMES = WARMCACHE+50 # The number of complete calls to DB.query_db()
MROW = 1000 * 1000
# Test values
COLDCACHE = 5 # The number of reads where the cache is considered 'cold'
WARMCACHE = 5 # The number of reads until the cache is considered 'warmed'
READ_TIMES = 10 # The number of complete calls to DB.query_db()
# global variables
rdm_cod = ['lin', 'rnd']
prec = 6 # precision for printing floats purposes
def get_nrows(nrows_str):
powers = {'k': 3, 'm': 6, 'g': 9}
try:
return int(float(nrows_str[:-1]) * 10 ** powers[nrows_str[-1]])
except KeyError:
raise ValueError(
"value of nrows must end with either 'k', 'm' or 'g' suffixes.")
class DB:
def __init__(self, nrows, rng, userandom):
global step, scale
self.step = STEP
self.scale = SCALE
self.rng = rng
self.userandom = userandom
self.filename = '-'.join([rdm_cod[userandom], nrows])
self.nrows = get_nrows(nrows)
def get_db_size(self):
sout = subprocess.Popen("sync;du -s %s" % self.filename, shell=True,
stdout=subprocess.PIPE).stdout
line = [l for l in sout][0]
return int(line.split()[0])
def print_mtime(self, t1, explain):
mtime = clock() - t1
print(f"{explain}: {mtime:.6f}")
print(f"Krows/s: {self.nrows / 1000 / mtime:.6f}")
def print_qtime(self, colname, ltimes):
qtime1 = ltimes[0] # First measured time
qtime2 = ltimes[-1] # Last measured time
print(f"Query time for {colname}: {qtime1:.6f}")
print(f"Mrows/s: {self.nrows / MROW / qtime1:.6f}")
print(f"Query time for {colname} (cached): {qtime2:.6f}")
print(f"Mrows/s (cached): {self.nrows / MROW / qtime2:.6f}")
def norm_times(self, ltimes):
"Get the mean and stddev of ltimes, avoiding the extreme values."
lmean = ltimes.mean()
lstd = ltimes.std()
ntimes = ltimes[ltimes < lmean + lstd]
nmean = ntimes.mean()
nstd = ntimes.std()
return nmean, nstd
def print_qtime_idx(self, colname, ltimes, repeated, verbose):
if repeated:
r = "[REP] "
else:
r = "[NOREP] "
ltimes = numpy.array(ltimes)
ntimes = len(ltimes)
qtime1 = ltimes[0] # First measured time
ctimes = ltimes[1:COLDCACHE]
cmean, cstd = self.norm_times(ctimes)
wtimes = ltimes[WARMCACHE:]
wmean, wstd = self.norm_times(wtimes)
if verbose:
print("Times for cold cache:\n", ctimes)
# print "Times for warm cache:\n", wtimes
hist1, hist2 = numpy.histogram(wtimes)
print(f"Histogram for warm cache: {hist1}\n{hist2}")
print(f"{r}1st query time for {colname}: {qtime1:.{prec}f}")
print(f"{r}Query time for {colname} (cold cache): "
f"{cmean:.{prec}f} +- {cstd:.{prec}f}")
print(f"{r}Query time for {colname} (warm cache): "
f"{wmean:.{prec}f} +- {wstd:.{prec}f}")
def print_db_sizes(self, init, filled, indexed):
table_size = (filled - init) / 1024
indexes_size = (indexed - filled) / 1024
print(f"Table size (MB): {table_size:.3f}")
print(f"Indexes size (MB): {indexes_size:.3f}")
print(f"Full size (MB): {table_size + indexes_size:.3f}")
def fill_arrays(self, start, stop):
arr_f8 = numpy.arange(start, stop, dtype='float64')
arr_i4 = numpy.arange(start, stop, dtype='int32')
if self.userandom:
arr_f8 += numpy.random.normal(0, stop * self.scale,
size=stop - start)
arr_i4 = numpy.array(arr_f8, dtype='int32')
return arr_i4, arr_f8
def create_db(self, dtype, kind, optlevel, verbose):
self.con = self.open_db(remove=1)
self.create_table(self.con)
init_size = self.get_db_size()
t1 = clock()
self.fill_table(self.con)
table_size = self.get_db_size()
self.print_mtime(t1, 'Insert time')
self.index_db(dtype, kind, optlevel, verbose)
indexes_size = self.get_db_size()
self.print_db_sizes(init_size, table_size, indexes_size)
self.close_db(self.con)
def index_db(self, dtype, kind, optlevel, verbose):
if dtype == "int":
idx_cols = ['col2']
elif dtype == "float":
idx_cols = ['col4']
else:
idx_cols = ['col2', 'col4']
for colname in idx_cols:
t1 = clock()
self.index_col(self.con, colname, kind, optlevel, verbose)
self.print_mtime(t1, 'Index time (%s)' % colname)
def query_db(self, niter, dtype, onlyidxquery, onlynonidxquery,
avoidfscache, verbose, inkernel):
self.con = self.open_db()
if dtype == "int":
reg_cols = ['col1']
idx_cols = ['col2']
elif dtype == "float":
reg_cols = ['col3']
idx_cols = ['col4']
else:
reg_cols = ['col1', 'col3']
idx_cols = ['col2', 'col4']
if avoidfscache:
rseed = int(numpy.random.randint(self.nrows))
else:
rseed = 19
# Query for non-indexed columns
numpy.random.seed(rseed)
base = numpy.random.randint(self.nrows)
if not onlyidxquery:
for colname in reg_cols:
ltimes = []
random.seed(rseed)
for i in range(NI_NTIMES):
t1 = clock()
results = self.do_query(self.con, colname, base, inkernel)
ltimes.append(clock() - t1)
if verbose:
print("Results len:", results)
self.print_qtime(colname, ltimes)
# Always reopen the file after *every* query loop.
# Necessary to make the benchmark to run correctly.
self.close_db(self.con)
self.con = self.open_db()
# Query for indexed columns
if not onlynonidxquery:
for colname in idx_cols:
ltimes = []
numpy.random.seed(rseed)
rndbase = numpy.random.randint(self.nrows, size=niter)
# First, non-repeated queries
for i in range(niter):
base = rndbase[i]
t1 = clock()
results = self.do_query(self.con, colname, base, inkernel)
#results, tprof = self.do_query(
# self.con, colname, base, inkernel)
ltimes.append(clock() - t1)
if verbose:
print("Results len:", results)
self.print_qtime_idx(colname, ltimes, False, verbose)
# Always reopen the file after *every* query loop.
# Necessary to make the benchmark to run correctly.
self.close_db(self.con)
self.con = self.open_db()
ltimes = []
# Second, repeated queries
# for i in range(niter):
# t1=time()
# results = self.do_query(
# self.con, colname, base, inkernel)
# results, tprof = self.do_query(self.con, colname, base, inkernel)
# ltimes.append(time()-t1)
# if verbose:
# print "Results len:", results
# self.print_qtime_idx(colname, ltimes, True, verbose)
# Print internal PyTables index tprof statistics
#tprof = numpy.array(tprof)
#tmean, tstd = self.norm_times(tprof)
# print "tprof-->", round(tmean, prec), "+-", round(tstd, prec)
# print "tprof hist-->", \
# numpy.histogram(tprof)
# print "tprof raw-->", tprof
# Always reopen the file after *every* query loop.
# Necessary to make the benchmark to run correctly.
self.close_db(self.con)
self.con = self.open_db()
# Finally, close the file.
self.close_db(self.con)
def close_db(self, con):
con.close()
if __name__ == "__main__":
import sys
import getopt
try:
import psyco
psyco_imported = 1
except:
psyco_imported = 0
usage = """usage: %s [-T] [-P] [-v] [-f] [-k] [-p] [-m] [-c] [-q] [-i] [-I] [-S] [-x] [-z complevel] [-l complib] [-R range] [-N niter] [-n nrows] [-d datadir] [-O level] [-t kind] [-s] col -Q [suplim]
-T use Pytables
-P use Postgres
-v verbose
-f do a profile of the run (only query functionality & Python 2.5)
-k do a profile for kcachegrind use (out file is 'indexed_search.kcg')
-p use "psyco" if available
-m use random values to fill the table
-q do a query (both indexed and non-indexed versions)
-i do a query (just indexed one)
-I do a query (just in-kernel one)
-S do a query (just standard one)
-x choose a different seed for random numbers (i.e. avoid FS cache)
-c create the database
-z compress with zlib (no compression by default)
-l use complib for compression (zlib used by default)
-R select a range in a field in the form "start,stop" (def "0,10")
-N number of iterations for reading
-n sets the number of rows (in krows) in each table
-d directory to save data (default: data.nobackup)
-O set the optimization level for PyTables indexes
-t select the index type: "medium" (default) or "full", "light", "ultralight"
-s select a type column for operations ('int' or 'float'. def all)
-Q do a repeteated query up to 10**value
\n""" % sys.argv[0]
try:
opts, pargs = getopt.getopt(
sys.argv[1:], 'TPvfkpmcqiISxz:l:R:N:n:d:O:t:s:Q:')
except:
sys.stderr.write(usage)
sys.exit(1)
# default options
usepytables = 0
usepostgres = 0
verbose = 0
doprofile = 0
dokprofile = 0
usepsyco = 0
userandom = 0
docreate = 0
optlevel = 0
kind = "medium"
docompress = 0
complib = "zlib"
doquery = False
onlyidxquery = False
onlynonidxquery = False
inkernel = True
avoidfscache = 0
#rng = [-10, 10]
rng = [-1000, -1000]
repeatquery = 0
repeatvalue = 0
krows = '1k'
niter = READ_TIMES
dtype = "all"
datadir = "data.nobackup"
# Get the options
for option in opts:
if option[0] == '-T':
usepytables = 1
elif option[0] == '-P':
usepostgres = 1
elif option[0] == '-v':
verbose = 1
elif option[0] == '-f':
doprofile = 1
elif option[0] == '-k':
dokprofile = 1
elif option[0] == '-p':
usepsyco = 1
elif option[0] == '-m':
userandom = 1
elif option[0] == '-c':
docreate = 1
elif option[0] == '-q':
doquery = True
elif option[0] == '-i':
doquery = True
onlyidxquery = True
elif option[0] == '-I':
doquery = True
onlynonidxquery = True
elif option[0] == '-S':
doquery = True
onlynonidxquery = True
inkernel = False
elif option[0] == '-x':
avoidfscache = 1
elif option[0] == '-z':
docompress = int(option[1])
elif option[0] == '-l':
complib = option[1]
elif option[0] == '-R':
rng = [int(i) for i in option[1].split(",")]
elif option[0] == '-N':
niter = int(option[1])
elif option[0] == '-n':
krows = option[1]
elif option[0] == '-d':
datadir = option[1]
elif option[0] == '-O':
optlevel = int(option[1])
elif option[0] == '-t':
if option[1] in ('full', 'medium', 'light', 'ultralight'):
kind = option[1]
else:
print("kind should be either 'full', 'medium', 'light' or "
"'ultralight'")
sys.exit(1)
elif option[0] == '-s':
if option[1] in ('int', 'float'):
dtype = option[1]
else:
print("column should be either 'int' or 'float'")
sys.exit(1)
elif option[0] == '-Q':
repeatquery = 1
repeatvalue = int(option[1])
# If not database backend selected, abort
if not usepytables and not usepostgres:
print("Please select a backend:")
print("PyTables: -T")
print("Postgres: -P")
sys.exit(1)
# Create the class for the database
if usepytables:
from pytables_backend import PyTables_DB
db = PyTables_DB(krows, rng, userandom, datadir,
docompress, complib, kind, optlevel)
elif usepostgres:
from postgres_backend import Postgres_DB
db = Postgres_DB(krows, rng, userandom)
if not avoidfscache:
# in order to always generate the same random sequence
numpy.random.seed(20)
if verbose:
if userandom:
print("using random values")
if onlyidxquery:
print("doing indexed queries only")
if psyco_imported and usepsyco:
psyco.bind(db.create_db)
psyco.bind(db.query_db)
if docreate:
if verbose:
print("writing %s rows" % krows)
db.create_db(dtype, kind, optlevel, verbose)
if doquery:
print("Calling query_db() %s times" % niter)
if doprofile:
import pstats
import cProfile as prof
prof.run(
'db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, '
'avoidfscache, verbose, inkernel)',
'indexed_search.prof')
stats = pstats.Stats('indexed_search.prof')
stats.strip_dirs()
stats.sort_stats('time', 'calls')
if verbose:
stats.print_stats()
else:
stats.print_stats(20)
elif dokprofile:
from cProfile import Profile
import lsprofcalltree
prof = Profile()
prof.run(
'db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, '
'avoidfscache, verbose, inkernel)')
kcg = lsprofcalltree.KCacheGrind(prof)
ofile = open('indexed_search.kcg', 'w')
kcg.output(ofile)
ofile.close()
elif doprofile:
import hotshot
import hotshot.stats
prof = hotshot.Profile("indexed_search.prof")
benchtime, stones = prof.run(
'db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, '
'avoidfscache, verbose, inkernel)')
prof.close()
stats = hotshot.stats.load("indexed_search.prof")
stats.strip_dirs()
stats.sort_stats('time', 'calls')
stats.print_stats(20)
else:
db.query_db(niter, dtype, onlyidxquery, onlynonidxquery,
avoidfscache, verbose, inkernel)
if repeatquery:
# Start by a range which is almost None
db.rng = [1, 1]
if verbose:
print("range:", db.rng)
db.query_db(niter, dtype, onlyidxquery, onlynonidxquery,
avoidfscache, verbose, inkernel)
for i in range(repeatvalue):
for j in (1, 2, 5):
rng = j * 10 ** i
db.rng = [-rng / 2, rng / 2]
if verbose:
print("range:", db.rng)
# if usepostgres:
# os.system(
# "echo 1 > /proc/sys/vm/drop_caches;"
# " /etc/init.d/postgresql restart")
# else:
# os.system("echo 1 > /proc/sys/vm/drop_caches")
db.query_db(niter, dtype, onlyidxquery, onlynonidxquery,
avoidfscache, verbose, inkernel)
|
[
"numpy.random.seed",
"getopt.getopt",
"cProfile.Profile",
"numpy.histogram",
"numpy.random.randint",
"numpy.arange",
"hotshot.stats.load",
"numpy.random.normal",
"cProfile.close",
"pytables_backend.PyTables_DB",
"pstats.Stats",
"psyco.bind",
"random.seed",
"hotshot.Profile",
"subprocess.Popen",
"postgres_backend.Postgres_DB",
"time.perf_counter",
"sys.exit",
"lsprofcalltree.KCacheGrind",
"numpy.array",
"sys.stderr.write",
"cProfile.run"
] |
[((3019, 3038), 'numpy.array', 'numpy.array', (['ltimes'], {}), '(ltimes)\n', (3030, 3038), False, 'import numpy\n'), ((4202, 4244), 'numpy.arange', 'numpy.arange', (['start', 'stop'], {'dtype': '"""float64"""'}), "(start, stop, dtype='float64')\n", (4214, 4244), False, 'import numpy\n'), ((4262, 4302), 'numpy.arange', 'numpy.arange', (['start', 'stop'], {'dtype': '"""int32"""'}), "(start, stop, dtype='int32')\n", (4274, 4302), False, 'import numpy\n'), ((4729, 4736), 'time.perf_counter', 'clock', ([], {}), '()\n', (4734, 4736), True, 'from time import perf_counter as clock\n'), ((6074, 6098), 'numpy.random.seed', 'numpy.random.seed', (['rseed'], {}), '(rseed)\n', (6091, 6098), False, 'import numpy\n'), ((6114, 6146), 'numpy.random.randint', 'numpy.random.randint', (['self.nrows'], {}), '(self.nrows)\n', (6134, 6146), False, 'import numpy\n'), ((10778, 10842), 'getopt.getopt', 'getopt.getopt', (['sys.argv[1:]', '"""TPvfkpmcqiISxz:l:R:N:n:d:O:t:s:Q:"""'], {}), "(sys.argv[1:], 'TPvfkpmcqiISxz:l:R:N:n:d:O:t:s:Q:')\n", (10791, 10842), False, 'import getopt\n'), ((13701, 13712), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13709, 13712), False, 'import sys\n'), ((13836, 13921), 'pytables_backend.PyTables_DB', 'PyTables_DB', (['krows', 'rng', 'userandom', 'datadir', 'docompress', 'complib', 'kind', 'optlevel'], {}), '(krows, rng, userandom, datadir, docompress, complib, kind, optlevel\n )\n', (13847, 13921), False, 'from pytables_backend import PyTables_DB\n'), ((14158, 14179), 'numpy.random.seed', 'numpy.random.seed', (['(20)'], {}), '(20)\n', (14175, 14179), False, 'import numpy\n'), ((14378, 14402), 'psyco.bind', 'psyco.bind', (['db.create_db'], {}), '(db.create_db)\n', (14388, 14402), False, 'import psyco\n'), ((14411, 14434), 'psyco.bind', 'psyco.bind', (['db.query_db'], {}), '(db.query_db)\n', (14421, 14434), False, 'import psyco\n'), ((1784, 1874), 'subprocess.Popen', 'subprocess.Popen', (["('sync;du -s %s' % self.filename)"], {'shell': '(True)', 'stdout': 'subprocess.PIPE'}), "('sync;du -s %s' % self.filename, shell=True, stdout=\n subprocess.PIPE)\n", (1800, 1874), False, 'import subprocess\n'), ((2038, 2045), 'time.perf_counter', 'clock', ([], {}), '()\n', (2043, 2045), True, 'from time import perf_counter as clock\n'), ((3437, 3460), 'numpy.histogram', 'numpy.histogram', (['wtimes'], {}), '(wtimes)\n', (3452, 3460), False, 'import numpy\n'), ((4352, 4412), 'numpy.random.normal', 'numpy.random.normal', (['(0)', '(stop * self.scale)'], {'size': '(stop - start)'}), '(0, stop * self.scale, size=stop - start)\n', (4371, 4412), False, 'import numpy\n'), ((4476, 4510), 'numpy.array', 'numpy.array', (['arr_f8'], {'dtype': '"""int32"""'}), "(arr_f8, dtype='int32')\n", (4487, 4510), False, 'import numpy\n'), ((5331, 5338), 'time.perf_counter', 'clock', ([], {}), '()\n', (5336, 5338), True, 'from time import perf_counter as clock\n'), ((10876, 10899), 'sys.stderr.write', 'sys.stderr.write', (['usage'], {}), '(usage)\n', (10892, 10899), False, 'import sys\n'), ((10908, 10919), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (10916, 10919), False, 'import sys\n'), ((14026, 14060), 'postgres_backend.Postgres_DB', 'Postgres_DB', (['krows', 'rng', 'userandom'], {}), '(krows, rng, userandom)\n', (14037, 14060), False, 'from postgres_backend import Postgres_DB\n'), ((14737, 14871), 'cProfile.run', 'prof.run', (['"""db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, avoidfscache, verbose, inkernel)"""', '"""indexed_search.prof"""'], {}), "(\n 'db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, avoidfscache, verbose, inkernel)'\n , 'indexed_search.prof')\n", (14745, 14871), True, 'import cProfile as prof\n'), ((14934, 14969), 'pstats.Stats', 'pstats.Stats', (['"""indexed_search.prof"""'], {}), "('indexed_search.prof')\n", (14946, 14969), False, 'import pstats\n'), ((5955, 5987), 'numpy.random.randint', 'numpy.random.randint', (['self.nrows'], {}), '(self.nrows)\n', (5975, 5987), False, 'import numpy\n'), ((6257, 6275), 'random.seed', 'random.seed', (['rseed'], {}), '(rseed)\n', (6268, 6275), False, 'import random\n'), ((6958, 6982), 'numpy.random.seed', 'numpy.random.seed', (['rseed'], {}), '(rseed)\n', (6975, 6982), False, 'import numpy\n'), ((7009, 7053), 'numpy.random.randint', 'numpy.random.randint', (['self.nrows'], {'size': 'niter'}), '(self.nrows, size=niter)\n', (7029, 7053), False, 'import numpy\n'), ((15282, 15291), 'cProfile.Profile', 'Profile', ([], {}), '()\n', (15289, 15291), False, 'from cProfile import Profile\n'), ((15304, 15415), 'cProfile.run', 'prof.run', (['"""db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, avoidfscache, verbose, inkernel)"""'], {}), "(\n 'db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, avoidfscache, verbose, inkernel)'\n )\n", (15312, 15415), True, 'import cProfile as prof\n'), ((15460, 15492), 'lsprofcalltree.KCacheGrind', 'lsprofcalltree.KCacheGrind', (['prof'], {}), '(prof)\n', (15486, 15492), False, 'import lsprofcalltree\n'), ((6344, 6351), 'time.perf_counter', 'clock', ([], {}), '()\n', (6349, 6351), True, 'from time import perf_counter as clock\n'), ((7202, 7209), 'time.perf_counter', 'clock', ([], {}), '()\n', (7207, 7209), True, 'from time import perf_counter as clock\n'), ((15704, 15742), 'hotshot.Profile', 'hotshot.Profile', (['"""indexed_search.prof"""'], {}), "('indexed_search.prof')\n", (15719, 15742), False, 'import hotshot\n'), ((15775, 15886), 'cProfile.run', 'prof.run', (['"""db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, avoidfscache, verbose, inkernel)"""'], {}), "(\n 'db.query_db(niter, dtype, onlyidxquery, onlynonidxquery, avoidfscache, verbose, inkernel)'\n )\n", (15783, 15886), True, 'import cProfile as prof\n'), ((15925, 15937), 'cProfile.close', 'prof.close', ([], {}), '()\n', (15935, 15937), True, 'import cProfile as prof\n'), ((15958, 15999), 'hotshot.stats.load', 'hotshot.stats.load', (['"""indexed_search.prof"""'], {}), "('indexed_search.prof')\n", (15976, 15999), False, 'import hotshot\n'), ((6465, 6472), 'time.perf_counter', 'clock', ([], {}), '()\n', (6470, 6472), True, 'from time import perf_counter as clock\n'), ((7436, 7443), 'time.perf_counter', 'clock', ([], {}), '()\n', (7441, 7443), True, 'from time import perf_counter as clock\n'), ((13163, 13174), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13171, 13174), False, 'import sys\n'), ((13387, 13398), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (13395, 13398), False, 'import sys\n')]
|
import numpy as np
import pandas as pd
from tqdm import tqdm
def bootstrap(x, iter=int(1E6), return_samples=False):
"""
Performs a simple bootstrap resampling method on an array of data.
Parameters
----------
x : numpy array
A one-dimensional numpy array containing values you wish to bootstrap.
If this array is < 10 values long, a warning will be raised that the
sampling distribution is small and the resulting resampled distribution
may not capture the full data generating distribution
iter: integer
Number of iterations to perform. Default is 10^6
return_samples : bool
If true, a pandas DataFrame of the resampled distributions will be
returned.
Returns
-------
statistics : dict
Dictionary of statistics of the resampled distribution. This includes
details about the originally supplied data as well as the mean value,
standard deviation, and confidence intervals.
"""
means = np.empty(iter)
dfs = []
for i in tqdm(range(iter), desc='Performing bootstrap sampling'):
resamp = np.random.choice(x, size=len(x), replace=True)
means[i] = resamp.mean()
if return_samples:
_df = pd.DataFrame([])
_df['value'] = resamp
_df['iter'] = i + 1
dfs.append(_df)
# Compute confidence intervals of the means.
mean_val = means.mean()
bounds_ci = {'99%': (0.5, 99.5), '95%': (2.5, 97.5), '90%': (5, 95),
'75%': (12.5, 87.5), '50%': (25, 75), '25%': (37.5, 62.5),
'10%': (45, 55), '5%': (47.5, 52.5), '1%': (49.5, 50.5)}
cis = {}
for k, v in bounds_ci.items():
bounds = np.percentile(means, v)
cis[k] = bounds
statistics['original_data'] = x
statistics['resampled_means'] = means
statistics['mean_value'] = mean_val
statistics['confidence_intervals'] = cis
if return_samples:
_df = pd.concat(dfs, sort=False)
return [statistics, _df]
else:
return statistics
|
[
"numpy.percentile",
"numpy.empty",
"pandas.concat",
"pandas.DataFrame"
] |
[((1029, 1043), 'numpy.empty', 'np.empty', (['iter'], {}), '(iter)\n', (1037, 1043), True, 'import numpy as np\n'), ((1739, 1762), 'numpy.percentile', 'np.percentile', (['means', 'v'], {}), '(means, v)\n', (1752, 1762), True, 'import numpy as np\n'), ((1989, 2015), 'pandas.concat', 'pd.concat', (['dfs'], {'sort': '(False)'}), '(dfs, sort=False)\n', (1998, 2015), True, 'import pandas as pd\n'), ((1271, 1287), 'pandas.DataFrame', 'pd.DataFrame', (['[]'], {}), '([])\n', (1283, 1287), True, 'import pandas as pd\n')]
|
# -*- coding: utf-8 -*-
"""@package Methods.Machine.LamSlotWind.plot_winding
Plot the Lamination's Winding Methods
@date Created on Tue Dec 16 16:39:48 2014
@copyright (C) 2014-2015 EOMYS ENGINEERING.
@author pierre_b
@todo Matrix Zs*Qs for display (cf doc database/articles/electrical machines/
analytical modelling of electrical machines/modeling of AC windings)
"""
from matplotlib.lines import Line2D
from matplotlib.pyplot import axis, legend, plot, subplots, title
from numpy import array, linspace, meshgrid
from pyleecan.Functions.Winding.comp_wind_sym import comp_wind_sym
from pyleecan.Functions.Winding.gen_phase_list import gen_color, gen_name
def plot_winding(self, wind_mat=None, all_slot=False):
"""Plot the Winding in a matplotlib fig
Parameters
----------
self : LamSlotWind
A: LamSlotWind object
wind_mat : numpy.ndarray
Winding Matrix, if None will call comp_connection_mat (Default value = None)
all_slot : bool
True if we plot all slot and false when plotting only needed one(sym)
Returns
-------
None
"""
# We compute the wind_mat only if needed
if wind_mat is None:
wind_mat = self.winding.comp_connection_mat(self.slot.Zs)
# Number of point on rad and tan direction
Nrad, Ntan = self.winding.get_dim_wind()
Zs = self.slot.Zs # Number of slot
# Number of Slot to plot
if all_slot: # Every Slot
Nplot = Zs
else: # Only the needed one (sym)
Nperw = comp_wind_sym(wind_mat)[0] # Symmetry of the winding
Nplot = Zs // Nperw
qs = wind_mat.shape[3] # Number of phase
# Symbole for pole
qs_color = gen_color(self.winding.qs)
qs_name = gen_name(self.winding.qs)
# Schematic slot without ratio
Wt = 0.5
W0 = 0.5
H = 1
# Coordinate of the First Slot (center on 0)
Slot_tan = array(
[-Wt / 2 - W0 / 2, -W0 / 2, -W0 / 2, W0 / 2, W0 / 2, W0 / 2 + Wt / 2]
)
Slot_rad = [0, 0, H, H, 0, 0]
# Duplicate the Slot along tan direction (angular abscissa )
x = list()
y = list()
for i in range(0, Nplot):
x.extend((Slot_tan + (Wt + W0) * i).tolist())
y.extend(Slot_rad)
# Plot the Schematics Slots
fig, ax = subplots()
plot(x, y, "r-")
# First Winding Grid (Coordinate of the winding mark)
range_x = linspace(-W0 / 2, W0 / 2, Ntan + 1, endpoint=False)
range_y = linspace(0, H, Nrad + 1, endpoint=False)
# We don't want the first and last point of the linespace
Grid_x, Grid_y = meshgrid(range_x[1:], range_y[1:])
# Plot the Winding Grid point by point by reading wind_mat
for Zs in range(0, Nplot): # For "every" Slot
for q in range(0, qs): # For every phase
for r in range(0, Nrad): # For every rad layer
for theta in range(0, Ntan): # For every tan layer
if wind_mat[r, theta, Zs, q] != 0:
# Add the correct mark at the correct coordinates
if wind_mat[r, theta, Zs, q] > 0:
plot(
Grid_x[r][theta] + Zs * (Wt + W0),
Grid_y[r][theta],
color=qs_color[q],
linewidth=0,
marker="+",
markeredgewidth=3,
markersize=20,
)
else:
plot(
Grid_x[r][theta] + Zs * (Wt + W0),
Grid_y[r][theta],
color=qs_color[q],
linewidth=0,
marker="x",
markeredgewidth=3,
markersize=20,
)
if self.is_stator:
Lam_Name = "Stator"
else:
Lam_Name = "Rotor"
if all_slot or Nperw == 1:
title(Lam_Name + "'s Winding (every slot)")
else:
title(Lam_Name + "'s Winding (periodicity 1/" + str(Nperw) + ")")
axis("equal")
ax.get_yaxis().set_visible(False)
# Legend qs
sym_leg = list() # Symbol
label_leg = list() # Text
for q in range(0, qs): # Positive mark
sym_leg.append(
Line2D(
[],
[],
color=qs_color[q],
linewidth=0,
marker="+",
markeredgewidth=3,
markersize=20,
)
)
label_leg.append(qs_name[q] + "+")
for q in range(0, qs): # Negative mark
sym_leg.append(
Line2D(
[],
[],
color=qs_color[q],
linewidth=0,
marker="x",
markeredgewidth=3,
markersize=20,
)
)
label_leg.append(qs_name[q] + "-")
legend(sym_leg, label_leg, ncol=2)
fig.show()
|
[
"matplotlib.pyplot.title",
"numpy.meshgrid",
"matplotlib.pyplot.plot",
"pyleecan.Functions.Winding.gen_phase_list.gen_name",
"pyleecan.Functions.Winding.comp_wind_sym.comp_wind_sym",
"matplotlib.lines.Line2D",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.axis",
"pyleecan.Functions.Winding.gen_phase_list.gen_color",
"numpy.array",
"numpy.linspace",
"matplotlib.pyplot.subplots"
] |
[((1670, 1696), 'pyleecan.Functions.Winding.gen_phase_list.gen_color', 'gen_color', (['self.winding.qs'], {}), '(self.winding.qs)\n', (1679, 1696), False, 'from pyleecan.Functions.Winding.gen_phase_list import gen_color, gen_name\n'), ((1711, 1736), 'pyleecan.Functions.Winding.gen_phase_list.gen_name', 'gen_name', (['self.winding.qs'], {}), '(self.winding.qs)\n', (1719, 1736), False, 'from pyleecan.Functions.Winding.gen_phase_list import gen_color, gen_name\n'), ((1876, 1952), 'numpy.array', 'array', (['[-Wt / 2 - W0 / 2, -W0 / 2, -W0 / 2, W0 / 2, W0 / 2, W0 / 2 + Wt / 2]'], {}), '([-Wt / 2 - W0 / 2, -W0 / 2, -W0 / 2, W0 / 2, W0 / 2, W0 / 2 + Wt / 2])\n', (1881, 1952), False, 'from numpy import array, linspace, meshgrid\n'), ((2255, 2265), 'matplotlib.pyplot.subplots', 'subplots', ([], {}), '()\n', (2263, 2265), False, 'from matplotlib.pyplot import axis, legend, plot, subplots, title\n'), ((2270, 2286), 'matplotlib.pyplot.plot', 'plot', (['x', 'y', '"""r-"""'], {}), "(x, y, 'r-')\n", (2274, 2286), False, 'from matplotlib.pyplot import axis, legend, plot, subplots, title\n'), ((2360, 2411), 'numpy.linspace', 'linspace', (['(-W0 / 2)', '(W0 / 2)', '(Ntan + 1)'], {'endpoint': '(False)'}), '(-W0 / 2, W0 / 2, Ntan + 1, endpoint=False)\n', (2368, 2411), False, 'from numpy import array, linspace, meshgrid\n'), ((2426, 2466), 'numpy.linspace', 'linspace', (['(0)', 'H', '(Nrad + 1)'], {'endpoint': '(False)'}), '(0, H, Nrad + 1, endpoint=False)\n', (2434, 2466), False, 'from numpy import array, linspace, meshgrid\n'), ((2550, 2584), 'numpy.meshgrid', 'meshgrid', (['range_x[1:]', 'range_y[1:]'], {}), '(range_x[1:], range_y[1:])\n', (2558, 2584), False, 'from numpy import array, linspace, meshgrid\n'), ((4193, 4206), 'matplotlib.pyplot.axis', 'axis', (['"""equal"""'], {}), "('equal')\n", (4197, 4206), False, 'from matplotlib.pyplot import axis, legend, plot, subplots, title\n'), ((5035, 5069), 'matplotlib.pyplot.legend', 'legend', (['sym_leg', 'label_leg'], {'ncol': '(2)'}), '(sym_leg, label_leg, ncol=2)\n', (5041, 5069), False, 'from matplotlib.pyplot import axis, legend, plot, subplots, title\n'), ((4060, 4103), 'matplotlib.pyplot.title', 'title', (['(Lam_Name + "\'s Winding (every slot)")'], {}), '(Lam_Name + "\'s Winding (every slot)")\n', (4065, 4103), False, 'from matplotlib.pyplot import axis, legend, plot, subplots, title\n'), ((1502, 1525), 'pyleecan.Functions.Winding.comp_wind_sym.comp_wind_sym', 'comp_wind_sym', (['wind_mat'], {}), '(wind_mat)\n', (1515, 1525), False, 'from pyleecan.Functions.Winding.comp_wind_sym import comp_wind_sym\n'), ((4404, 4501), 'matplotlib.lines.Line2D', 'Line2D', (['[]', '[]'], {'color': 'qs_color[q]', 'linewidth': '(0)', 'marker': '"""+"""', 'markeredgewidth': '(3)', 'markersize': '(20)'}), "([], [], color=qs_color[q], linewidth=0, marker='+', markeredgewidth=\n 3, markersize=20)\n", (4410, 4501), False, 'from matplotlib.lines import Line2D\n'), ((4757, 4854), 'matplotlib.lines.Line2D', 'Line2D', (['[]', '[]'], {'color': 'qs_color[q]', 'linewidth': '(0)', 'marker': '"""x"""', 'markeredgewidth': '(3)', 'markersize': '(20)'}), "([], [], color=qs_color[q], linewidth=0, marker='x', markeredgewidth=\n 3, markersize=20)\n", (4763, 4854), False, 'from matplotlib.lines import Line2D\n'), ((3093, 3232), 'matplotlib.pyplot.plot', 'plot', (['(Grid_x[r][theta] + Zs * (Wt + W0))', 'Grid_y[r][theta]'], {'color': 'qs_color[q]', 'linewidth': '(0)', 'marker': '"""+"""', 'markeredgewidth': '(3)', 'markersize': '(20)'}), "(Grid_x[r][theta] + Zs * (Wt + W0), Grid_y[r][theta], color=qs_color[q],\n linewidth=0, marker='+', markeredgewidth=3, markersize=20)\n", (3097, 3232), False, 'from matplotlib.pyplot import axis, legend, plot, subplots, title\n'), ((3542, 3681), 'matplotlib.pyplot.plot', 'plot', (['(Grid_x[r][theta] + Zs * (Wt + W0))', 'Grid_y[r][theta]'], {'color': 'qs_color[q]', 'linewidth': '(0)', 'marker': '"""x"""', 'markeredgewidth': '(3)', 'markersize': '(20)'}), "(Grid_x[r][theta] + Zs * (Wt + W0), Grid_y[r][theta], color=qs_color[q],\n linewidth=0, marker='x', markeredgewidth=3, markersize=20)\n", (3546, 3681), False, 'from matplotlib.pyplot import axis, legend, plot, subplots, title\n')]
|
#!/usr/bin/env python3
import sys
sys.path.append('./lib')
import argparse
import os
import datetime
import numpy as np
import time
import pickle
import torch
from torch import optim
from param_stamp import get_param_stamp, get_param_stamp_from_args
import evaluate
from lib.encoder import Classifier
from lib.vae_models import AutoEncoder
import lib.callbacks as cb
from lib.train import train_cl
from lib.continual_learner import ContinualLearner
from lib.exemplars import ExemplarHandler
from lib.replayer import Replayer
RESULT_DIR = './results'
parser = argparse.ArgumentParser('./main.py', description='Run individual continual learning experiment.')
parser.add_argument('--get-stamp', action='store_true')
parser.add_argument('--no-gpus', action='store_false', dest='cuda')
parser.add_argument('--gpuID', type=int, nargs='+', default=[0, 1, 2, 3], help='GPU #')
parser.add_argument('--savepath', type=str, default='./results', dest='savepath')
parser.add_argument('--vis-cross-methods', action='store_true', dest='cross_methods', help='draw plots for cross methods')
parser.add_argument('--vis-cross-methods-type', nargs='+', default=['spider'], dest='cross_methods_type', help='alternatives=[\'spider\', \'bar\']')
parser.add_argument('--vis-cross-tasks', action='store_true', dest='cross_tasks', help='draw plots for cross tasks')
parser.add_argument('--matrices', type=str, nargs='+', default=['ACC', 'BWT', 'FWT', 'Overall ACC'])
parser.add_argument('--seed', type=int, default=7)
parser.add_argument('--factor', type=str, default='clutter', dest='factor')
parser.add_argument('--cumulative', type=int, default=0, dest='cul')
parser.add_argument('--bce', action='store_true')
parser.add_argument('--tasks', type=int, default=9)
parser.add_argument('--dataset', type=str, default='OpenLORIS-Object', dest='dataset')
parser.add_argument('--fc-layers', type=int, default=3, dest='fc_lay')
parser.add_argument('--fc-units', type=int, default=400, metavar="N")
parser.add_argument('--fc-drop', type=float, default=0.)
parser.add_argument('--fc-bn', type=str, default="no")
parser.add_argument('--fc-nl', type=str, default="relu", choices=["relu", "leakyrelu"])
parser.add_argument('--iters', type=int, default=3000)
parser.add_argument('--lr', type=float, default=0.0001)
parser.add_argument('--batch', type=int, default=32)
parser.add_argument('--optimizer', type=str, choices=['adam', 'adam_reset', 'sgd'], default='adam')
parser.add_argument('--feedback', action="store_true")
replay_choices = ['offline', 'exact', 'generative', 'none', 'current', 'exemplars']
parser.add_argument('--replay', type=str, default='none', choices=replay_choices)
parser.add_argument('--distill', action='store_true')
parser.add_argument('--temp', type=float, default=2., dest='temp')
parser.add_argument('--z_dim', type=int, default=100)
parser.add_argument('--g-z-dim', type=int, default=100)
parser.add_argument('--g-fc-lay', type=int)
parser.add_argument('--g-fc-uni', type=int)
parser.add_argument('--g-iters', type=int)
parser.add_argument('--lr-gen', type=float)
parser.add_argument('--ewc', action='store_true')
parser.add_argument('--lambda', type=float, default=5240., dest="ewc_lambda")
parser.add_argument('--fisher-n', type=int)
parser.add_argument('--online', action='store_true')
parser.add_argument('--gamma', type=float, default=1.)
parser.add_argument('--emp-fi', action='store_true')
parser.add_argument('--si', action='store_true')
parser.add_argument('--c', type=float, default=0.3, dest="si_c")
parser.add_argument('--epsilon', type=float, default=0.2, dest="epsilon")
parser.add_argument('--icarl', action='store_true')
parser.add_argument('--use-exemplars', action='store_true')
parser.add_argument('--add-exemplars', action='store_true')
parser.add_argument('--budget', type=int, default=2500, dest="budget")
parser.add_argument('--herding', action='store_true')
parser.add_argument('--norm-exemplars', action='store_true')
parser.add_argument('--log-per-task', action='store_true')
parser.add_argument('--loss-log', type=int, default=200, metavar="N")
parser.add_argument('--prec-log', type=int, default=200, metavar="N")
parser.add_argument('--prec-n', type=int, default=1024)
parser.add_argument('--sample-log', type=int, default=500, metavar="N")
parser.add_argument('--sample-n', type=int, default=64)
def run(args):
result_path = os.path.join('./benchmarks/results', args.savepath)
savepath = result_path + '/' + str(datetime.datetime.now().strftime('%Y-%m-%d %H-%M-%S')) + '.csv'
if not os.path.exists(result_path):
print('no exist the path and create one ...')
os.makedirs(result_path, exist_ok=True)
# Set default arguments
args.lr_gen = args.lr if args.lr_gen is None else args.lr_gen
args.g_iters = args.iters if args.g_iters is None else args.g_iters
args.g_fc_lay = args.fc_lay if args.g_fc_lay is None else args.g_fc_lay
args.g_fc_uni = args.fc_units if args.g_fc_uni is None else args.g_fc_uni
# -if [log_per_task], reset all logs
if args.log_per_task:
args.prec_log = args.iters
args.loss_log = args.iters
args.sample_log = args.iters
# -if [iCaRL] is selected, select all accompanying options
if hasattr(args, "icarl") and args.icarl:
args.use_exemplars = True
args.add_exemplars = True
# -if EWC or SI is selected together with 'feedback', give error
if args.feedback and (args.ewc or args.si or args.icarl):
raise NotImplementedError("EWC, SI and iCaRL are not supported with feedback connections.")
# -if binary classification loss is selected together with 'feedback', give error
if args.feedback and args.bce:
raise NotImplementedError("Binary classification loss not supported with feedback connections.")
if not os.path.isdir(RESULT_DIR):
os.mkdir(RESULT_DIR)
# If only want param-stamp, get it printed to screen and exit
if hasattr(args, "get_stamp") and args.get_stamp:
_ = get_param_stamp_from_args(args=args)
exit()
# Use cuda?
cuda = torch.cuda.is_available() and args.cuda
device = "cuda" if cuda else "cpu"
gpu_devices = None
if args.gpuID == None:
if torch.cuda.device_count() > 1:
gpu_devices = ','.join([str(id) for id in range(torch.cuda.device_count())])
print('==> training with CUDA (GPU id: ' + gpu_devices + ') ... <==')
else:
gpu_devices = ','.join([str(id) for id in args.gpuID])
os.environ['CUDA_VISIBLE_DEVICES'] = gpu_devices
print('==> training with CUDA (GPU id: ' + str(args.gpuID) + ') ... <==')
# Set random seeds
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if cuda:
torch.cuda.manual_seed(args.seed)
if args.factor == 'sequence':
args.tasks = 12
# -------------------------------------------------------------------------------------------------#
# ----------------#
# ----- DATA -----#
# ----------------#
# Prepare data for OpenLORIS-Object
if args.dataset == 'OpenLORIS-Object':
with open('./benchmarks/data/OpenLORIS-Object/' + args.factor + '.pk', 'rb') as f:
((train_datasets, test_datasets), config, classes_per_task) = pickle.load(f)
else:
with open('./benchmarks/data/' + args.dataset + '/' + args.dataset + '.pk', 'rb') as f:
((train_datasets, test_datasets), config, classes_per_task) = pickle.load(f)
if args.cul == 1:
for i in range(1, len(train_datasets)):
train_datasets[i].imgs.extend(train_datasets[i - 1].imgs)
train_datasets[i].labels.extend(train_datasets[i - 1].labels)
# -------------------------------------------------------------------------------------------------#
# ------------------------------#
# ----- MODEL (CLASSIFIER) -----#
# ------------------------------#
# Define main model (i.e., classifier, if requested with feedback connections)
if args.feedback:
model = AutoEncoder(
image_size=config['size'], image_channels=config['channels'], classes=config['classes'],
fc_layers=args.fc_lay, fc_units=args.g_fc_uni, z_dim=args.z_dim,
fc_drop=args.fc_drop, fc_bn=True if args.fc_bn == "yes" else False, fc_nl=args.fc_nl,
).to(device)
model.lamda_pl = 1. # --> to make that this VAE is also trained to classify
else:
model = Classifier(
image_size=config['size'], image_channels=config['channels'], classes=config['classes'],
fc_layers=args.fc_lay, fc_units=args.fc_units, fc_drop=args.fc_drop, fc_nl=args.fc_nl,
fc_bn=True if args.fc_bn == "yes" else False, excit_buffer=False,
binaryCE=args.bce
).to(device)
# Define optimizer (only include parameters that "requires_grad")
model.optim_list = [{'params': filter(lambda p: p.requires_grad, model.parameters()), 'lr': args.lr}]
model.optim_type = args.optimizer
if model.optim_type in ("adam", "adam_reset"):
model.optimizer = optim.Adam(model.optim_list, betas=(0.9, 0.999))
elif model.optim_type == "sgd":
model.optimizer = optim.SGD(model.optim_list)
else:
raise ValueError("Unrecognized optimizer, '{}' is not currently a valid option".format(args.optimizer))
# ----------------------------------#
# ----- CL-STRATEGY: EXEMPLARS -----#
# ----------------------------------#
# Store in model whether, how many and in what way to store exemplars
if isinstance(model, ExemplarHandler) and (args.use_exemplars or args.add_exemplars or args.replay == "exemplars"):
model.memory_budget = args.budget
model.norm_exemplars = args.norm_exemplars
model.herding = args.herding
# -----------------------------------#
# ----- CL-STRATEGY: ALLOCATION -----#
# -----------------------------------#
# Elastic Weight Consolidation (EWC)
if isinstance(model, ContinualLearner):
model.ewc_lambda = args.ewc_lambda if args.ewc else 0
if args.ewc:
model.fisher_n = args.fisher_n
model.gamma = args.gamma
model.online = args.online
model.emp_FI = args.emp_fi
# Synpatic Intelligence (SI)
if isinstance(model, ContinualLearner):
model.si_c = args.si_c if args.si else 0
if args.si:
model.epsilon = args.epsilon
# -------------------------------------------------------------------------------------------------#
# -------------------------------#
# ----- CL-STRATEGY: REPLAY -----#
# -------------------------------#
# Use distillation loss (i.e., soft targets) for replayed data? (and set temperature)
if isinstance(model, Replayer):
model.replay_targets = "soft" if args.distill else "hard"
model.KD_temp = args.temp
# If needed, specify separate model for the generator
train_gen = True if (args.replay == "generative" and not args.feedback) else False
if train_gen:
# -specify architecture
generator = AutoEncoder(
image_size=config['size'], image_channels=config['channels'],
fc_layers=args.g_fc_lay, fc_units=args.g_fc_uni, z_dim=args.z_dim, classes=config['classes'],
fc_drop=args.fc_drop, fc_bn=True if args.fc_bn == "yes" else False, fc_nl=args.fc_nl,
).to(device)
# -set optimizer(s)
generator.optim_list = [
{'params': filter(lambda p: p.requires_grad, generator.parameters()), 'lr': args.lr_gen}]
generator.optim_type = args.optimizer
if generator.optim_type in ("adam", "adam_reset"):
generator.optimizer = optim.Adam(generator.optim_list, betas=(0.9, 0.999))
elif generator.optim_type == "sgd":
generator.optimizer = optim.SGD(generator.optim_list)
else:
generator = None
# ---------------------#
# ----- REPORTING -----#
# ---------------------#
# Get parameter-stamp (and print on screen)
param_stamp = get_param_stamp(
args, model.name, verbose=True, replay=True if (not args.replay == "none") else False,
replay_model_name=generator.name if (args.replay == "generative" and not args.feedback) else None,
)
# -define [precision_dict] to keep track of performance during training for storing and for later plotting in pdf
precision_dict = evaluate.initiate_precision_dict(args.tasks)
precision_dict_exemplars = evaluate.initiate_precision_dict(args.tasks) if args.use_exemplars else None
# ---------------------#
# ----- CALLBACKS -----#
# ---------------------#
# Callbacks for reporting on and visualizing loss
generator_loss_cbs = [
cb._VAE_loss_cb(log=args.loss_log, model=model if args.feedback else generator, tasks=args.tasks,
iters_per_task=args.iters if args.feedback else args.g_iters,
replay=False if args.replay == "none" else True)
] if (train_gen or args.feedback) else [None]
solver_loss_cbs = [
cb._solver_loss_cb(log=args.loss_log, model=model, tasks=args.tasks,
iters_per_task=args.iters, replay=False if args.replay == "none" else True)
] if (not args.feedback) else [None]
# Callbacks for evaluating and plotting generated / reconstructed samples
sample_cbs = [
cb._sample_cb(log=args.sample_log, config=config, test_datasets=test_datasets,
sample_size=args.sample_n, iters_per_task=args.iters if args.feedback else args.g_iters)
] if (train_gen or args.feedback) else [None]
# Callbacks for reporting and visualizing accuracy
eval_cb = cb._eval_cb(
log=args.prec_log, test_datasets=test_datasets, precision_dict=None, iters_per_task=args.iters,
test_size=args.prec_n, classes_per_task=classes_per_task
)
# -pdf / reporting: summary plots (i.e, only after each task)
eval_cb_full = cb._eval_cb(
log=args.iters, test_datasets=test_datasets, precision_dict=precision_dict,
iters_per_task=args.iters, classes_per_task=classes_per_task
)
eval_cb_exemplars = cb._eval_cb(
log=args.iters, test_datasets=test_datasets, classes_per_task=classes_per_task,
precision_dict=precision_dict_exemplars, iters_per_task=args.iters,
with_exemplars=True,
) if args.use_exemplars else None
# -collect them in <lists>
eval_cbs = [eval_cb, eval_cb_full]
eval_cbs_exemplars = [eval_cb_exemplars]
# --------------------#
# ----- TRAINING -----#
# --------------------#
print("--> Training:")
# Keep track of training-time
start = time.time()
# Train model
train_cl(
model, train_datasets, test_datasets, replay_mode=args.replay,
classes_per_task=classes_per_task,
iters=args.iters, batch_size=args.batch, savepath=savepath,
generator=generator, gen_iters=args.g_iters, gen_loss_cbs=generator_loss_cbs,
sample_cbs=sample_cbs, eval_cbs=eval_cbs, loss_cbs=generator_loss_cbs if args.feedback else solver_loss_cbs,
eval_cbs_exemplars=eval_cbs_exemplars, use_exemplars=args.use_exemplars, add_exemplars=args.add_exemplars,
)
# -------------------------------------------------------------------------------------------------#
# --------------------#
# -- VISUALIZATION ---#
# --------------------#
matrices_names = args.matrices
method_names = []
if args.cul == 1:
method_names.append('Cumulative')
elif args.cul == 0:
method_names.append('Naive')
if args.replay == 'current':
method_names.append('LwF')
if args.online and args.ewc:
method_names.append('Online EWC')
if args.si:
method_names.append('SI')
if args.replay == "generative" and not args.feedback and not args.distill:
method_names.append('DGR')
if args.replay == "generative" and not args.feedback and args.distill:
method_names.append('DGR with distillation')
if args.replay == "generative" and args.feedback and args.distill:
method_names.append('DGR with feedback')
if args.ewc and not args.online:
method_names.append('EWC')
print('The selected methods are:', method_names)
print('The selected performance matrices are:', matrices_names)
if args.cross_methods:
print('==> Drawing results for cross selected-methods ... <==')
if 'spider' in args.cross_methods_type:
spider = True
if 'bar' in args.cross_methods_type:
bar = True
if args.cross_tasks:
print('==> Drawing results for cross tasks ... <==')
if __name__ == '__main__':
args = parser.parse_args()
run(args)
|
[
"os.mkdir",
"numpy.random.seed",
"argparse.ArgumentParser",
"torch.cuda.device_count",
"pickle.load",
"lib.train.train_cl",
"param_stamp.get_param_stamp_from_args",
"os.path.join",
"lib.encoder.Classifier",
"sys.path.append",
"lib.callbacks._VAE_loss_cb",
"os.path.exists",
"datetime.datetime.now",
"lib.vae_models.AutoEncoder",
"torch.manual_seed",
"param_stamp.get_param_stamp",
"torch.cuda.manual_seed",
"lib.callbacks._solver_loss_cb",
"evaluate.initiate_precision_dict",
"torch.optim.Adam",
"torch.cuda.is_available",
"lib.callbacks._sample_cb",
"lib.callbacks._eval_cb",
"os.makedirs",
"os.path.isdir",
"time.time",
"torch.optim.SGD"
] |
[((35, 59), 'sys.path.append', 'sys.path.append', (['"""./lib"""'], {}), "('./lib')\n", (50, 59), False, 'import sys\n'), ((564, 666), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['"""./main.py"""'], {'description': '"""Run individual continual learning experiment."""'}), "('./main.py', description=\n 'Run individual continual learning experiment.')\n", (587, 666), False, 'import argparse\n'), ((4370, 4421), 'os.path.join', 'os.path.join', (['"""./benchmarks/results"""', 'args.savepath'], {}), "('./benchmarks/results', args.savepath)\n", (4382, 4421), False, 'import os\n'), ((6663, 6688), 'numpy.random.seed', 'np.random.seed', (['args.seed'], {}), '(args.seed)\n', (6677, 6688), True, 'import numpy as np\n'), ((6693, 6721), 'torch.manual_seed', 'torch.manual_seed', (['args.seed'], {}), '(args.seed)\n', (6710, 6721), False, 'import torch\n'), ((12078, 12285), 'param_stamp.get_param_stamp', 'get_param_stamp', (['args', 'model.name'], {'verbose': '(True)', 'replay': "(True if not args.replay == 'none' else False)", 'replay_model_name': "(generator.name if args.replay == 'generative' and not args.feedback else None)"}), "(args, model.name, verbose=True, replay=True if not args.\n replay == 'none' else False, replay_model_name=generator.name if args.\n replay == 'generative' and not args.feedback else None)\n", (12093, 12285), False, 'from param_stamp import get_param_stamp, get_param_stamp_from_args\n'), ((12443, 12487), 'evaluate.initiate_precision_dict', 'evaluate.initiate_precision_dict', (['args.tasks'], {}), '(args.tasks)\n', (12475, 12487), False, 'import evaluate\n'), ((13742, 13916), 'lib.callbacks._eval_cb', 'cb._eval_cb', ([], {'log': 'args.prec_log', 'test_datasets': 'test_datasets', 'precision_dict': 'None', 'iters_per_task': 'args.iters', 'test_size': 'args.prec_n', 'classes_per_task': 'classes_per_task'}), '(log=args.prec_log, test_datasets=test_datasets, precision_dict=\n None, iters_per_task=args.iters, test_size=args.prec_n,\n classes_per_task=classes_per_task)\n', (13753, 13916), True, 'import lib.callbacks as cb\n'), ((14015, 14174), 'lib.callbacks._eval_cb', 'cb._eval_cb', ([], {'log': 'args.iters', 'test_datasets': 'test_datasets', 'precision_dict': 'precision_dict', 'iters_per_task': 'args.iters', 'classes_per_task': 'classes_per_task'}), '(log=args.iters, test_datasets=test_datasets, precision_dict=\n precision_dict, iters_per_task=args.iters, classes_per_task=\n classes_per_task)\n', (14026, 14174), True, 'import lib.callbacks as cb\n'), ((14729, 14740), 'time.time', 'time.time', ([], {}), '()\n', (14738, 14740), False, 'import time\n'), ((14763, 15250), 'lib.train.train_cl', 'train_cl', (['model', 'train_datasets', 'test_datasets'], {'replay_mode': 'args.replay', 'classes_per_task': 'classes_per_task', 'iters': 'args.iters', 'batch_size': 'args.batch', 'savepath': 'savepath', 'generator': 'generator', 'gen_iters': 'args.g_iters', 'gen_loss_cbs': 'generator_loss_cbs', 'sample_cbs': 'sample_cbs', 'eval_cbs': 'eval_cbs', 'loss_cbs': '(generator_loss_cbs if args.feedback else solver_loss_cbs)', 'eval_cbs_exemplars': 'eval_cbs_exemplars', 'use_exemplars': 'args.use_exemplars', 'add_exemplars': 'args.add_exemplars'}), '(model, train_datasets, test_datasets, replay_mode=args.replay,\n classes_per_task=classes_per_task, iters=args.iters, batch_size=args.\n batch, savepath=savepath, generator=generator, gen_iters=args.g_iters,\n gen_loss_cbs=generator_loss_cbs, sample_cbs=sample_cbs, eval_cbs=\n eval_cbs, loss_cbs=generator_loss_cbs if args.feedback else\n solver_loss_cbs, eval_cbs_exemplars=eval_cbs_exemplars, use_exemplars=\n args.use_exemplars, add_exemplars=args.add_exemplars)\n', (14771, 15250), False, 'from lib.train import train_cl\n'), ((4536, 4563), 'os.path.exists', 'os.path.exists', (['result_path'], {}), '(result_path)\n', (4550, 4563), False, 'import os\n'), ((4627, 4666), 'os.makedirs', 'os.makedirs', (['result_path'], {'exist_ok': '(True)'}), '(result_path, exist_ok=True)\n', (4638, 4666), False, 'import os\n'), ((5809, 5834), 'os.path.isdir', 'os.path.isdir', (['RESULT_DIR'], {}), '(RESULT_DIR)\n', (5822, 5834), False, 'import os\n'), ((5844, 5864), 'os.mkdir', 'os.mkdir', (['RESULT_DIR'], {}), '(RESULT_DIR)\n', (5852, 5864), False, 'import os\n'), ((5998, 6034), 'param_stamp.get_param_stamp_from_args', 'get_param_stamp_from_args', ([], {'args': 'args'}), '(args=args)\n', (6023, 6034), False, 'from param_stamp import get_param_stamp, get_param_stamp_from_args\n'), ((6078, 6103), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (6101, 6103), False, 'import torch\n'), ((6743, 6776), 'torch.cuda.manual_seed', 'torch.cuda.manual_seed', (['args.seed'], {}), '(args.seed)\n', (6765, 6776), False, 'import torch\n'), ((9086, 9134), 'torch.optim.Adam', 'optim.Adam', (['model.optim_list'], {'betas': '(0.9, 0.999)'}), '(model.optim_list, betas=(0.9, 0.999))\n', (9096, 9134), False, 'from torch import optim\n'), ((12519, 12563), 'evaluate.initiate_precision_dict', 'evaluate.initiate_precision_dict', (['args.tasks'], {}), '(args.tasks)\n', (12551, 12563), False, 'import evaluate\n'), ((14211, 14400), 'lib.callbacks._eval_cb', 'cb._eval_cb', ([], {'log': 'args.iters', 'test_datasets': 'test_datasets', 'classes_per_task': 'classes_per_task', 'precision_dict': 'precision_dict_exemplars', 'iters_per_task': 'args.iters', 'with_exemplars': '(True)'}), '(log=args.iters, test_datasets=test_datasets, classes_per_task=\n classes_per_task, precision_dict=precision_dict_exemplars,\n iters_per_task=args.iters, with_exemplars=True)\n', (14222, 14400), True, 'import lib.callbacks as cb\n'), ((6219, 6244), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (6242, 6244), False, 'import torch\n'), ((7265, 7279), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7276, 7279), False, 'import pickle\n'), ((7460, 7474), 'pickle.load', 'pickle.load', (['f'], {}), '(f)\n', (7471, 7474), False, 'import pickle\n'), ((9197, 9224), 'torch.optim.SGD', 'optim.SGD', (['model.optim_list'], {}), '(model.optim_list)\n', (9206, 9224), False, 'from torch import optim\n'), ((11725, 11777), 'torch.optim.Adam', 'optim.Adam', (['generator.optim_list'], {'betas': '(0.9, 0.999)'}), '(generator.optim_list, betas=(0.9, 0.999))\n', (11735, 11777), False, 'from torch import optim\n'), ((12774, 12991), 'lib.callbacks._VAE_loss_cb', 'cb._VAE_loss_cb', ([], {'log': 'args.loss_log', 'model': '(model if args.feedback else generator)', 'tasks': 'args.tasks', 'iters_per_task': '(args.iters if args.feedback else args.g_iters)', 'replay': "(False if args.replay == 'none' else True)"}), "(log=args.loss_log, model=model if args.feedback else\n generator, tasks=args.tasks, iters_per_task=args.iters if args.feedback\n else args.g_iters, replay=False if args.replay == 'none' else True)\n", (12789, 12991), True, 'import lib.callbacks as cb\n'), ((13113, 13261), 'lib.callbacks._solver_loss_cb', 'cb._solver_loss_cb', ([], {'log': 'args.loss_log', 'model': 'model', 'tasks': 'args.tasks', 'iters_per_task': 'args.iters', 'replay': "(False if args.replay == 'none' else True)"}), "(log=args.loss_log, model=model, tasks=args.tasks,\n iters_per_task=args.iters, replay=False if args.replay == 'none' else True)\n", (13131, 13261), True, 'import lib.callbacks as cb\n'), ((13432, 13608), 'lib.callbacks._sample_cb', 'cb._sample_cb', ([], {'log': 'args.sample_log', 'config': 'config', 'test_datasets': 'test_datasets', 'sample_size': 'args.sample_n', 'iters_per_task': '(args.iters if args.feedback else args.g_iters)'}), '(log=args.sample_log, config=config, test_datasets=\n test_datasets, sample_size=args.sample_n, iters_per_task=args.iters if\n args.feedback else args.g_iters)\n', (13445, 13608), True, 'import lib.callbacks as cb\n'), ((8032, 8297), 'lib.vae_models.AutoEncoder', 'AutoEncoder', ([], {'image_size': "config['size']", 'image_channels': "config['channels']", 'classes': "config['classes']", 'fc_layers': 'args.fc_lay', 'fc_units': 'args.g_fc_uni', 'z_dim': 'args.z_dim', 'fc_drop': 'args.fc_drop', 'fc_bn': "(True if args.fc_bn == 'yes' else False)", 'fc_nl': 'args.fc_nl'}), "(image_size=config['size'], image_channels=config['channels'],\n classes=config['classes'], fc_layers=args.fc_lay, fc_units=args.\n g_fc_uni, z_dim=args.z_dim, fc_drop=args.fc_drop, fc_bn=True if args.\n fc_bn == 'yes' else False, fc_nl=args.fc_nl)\n", (8043, 8297), False, 'from lib.vae_models import AutoEncoder\n'), ((8453, 8738), 'lib.encoder.Classifier', 'Classifier', ([], {'image_size': "config['size']", 'image_channels': "config['channels']", 'classes': "config['classes']", 'fc_layers': 'args.fc_lay', 'fc_units': 'args.fc_units', 'fc_drop': 'args.fc_drop', 'fc_nl': 'args.fc_nl', 'fc_bn': "(True if args.fc_bn == 'yes' else False)", 'excit_buffer': '(False)', 'binaryCE': 'args.bce'}), "(image_size=config['size'], image_channels=config['channels'],\n classes=config['classes'], fc_layers=args.fc_lay, fc_units=args.\n fc_units, fc_drop=args.fc_drop, fc_nl=args.fc_nl, fc_bn=True if args.\n fc_bn == 'yes' else False, excit_buffer=False, binaryCE=args.bce)\n", (8463, 8738), False, 'from lib.encoder import Classifier\n'), ((11111, 11377), 'lib.vae_models.AutoEncoder', 'AutoEncoder', ([], {'image_size': "config['size']", 'image_channels': "config['channels']", 'fc_layers': 'args.g_fc_lay', 'fc_units': 'args.g_fc_uni', 'z_dim': 'args.z_dim', 'classes': "config['classes']", 'fc_drop': 'args.fc_drop', 'fc_bn': "(True if args.fc_bn == 'yes' else False)", 'fc_nl': 'args.fc_nl'}), "(image_size=config['size'], image_channels=config['channels'],\n fc_layers=args.g_fc_lay, fc_units=args.g_fc_uni, z_dim=args.z_dim,\n classes=config['classes'], fc_drop=args.fc_drop, fc_bn=True if args.\n fc_bn == 'yes' else False, fc_nl=args.fc_nl)\n", (11122, 11377), False, 'from lib.vae_models import AutoEncoder\n'), ((11856, 11887), 'torch.optim.SGD', 'optim.SGD', (['generator.optim_list'], {}), '(generator.optim_list)\n', (11865, 11887), False, 'from torch import optim\n'), ((4461, 4484), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4482, 4484), False, 'import datetime\n'), ((6310, 6335), 'torch.cuda.device_count', 'torch.cuda.device_count', ([], {}), '()\n', (6333, 6335), False, 'import torch\n')]
|
# pylint: disable-msg=W0401,W0511,W0611,W0612,W0614,R0201,E1102
"""Tests suite for MaskedArray & subclassing.
:author: <NAME>
:contact: pierregm_at_uga_dot_edu
"""
from __future__ import division, absolute_import, print_function
__author__ = "<NAME>"
import warnings
import pickle
import operator
import itertools
from functools import reduce
import numpy as np
import numpy.ma.core
import numpy.core.fromnumeric as fromnumeric
import numpy.core.umath as umath
from numpy.testing import TestCase, run_module_suite, assert_raises
from numpy import ndarray
from numpy.compat import asbytes, asbytes_nested
from numpy.ma.testutils import (
assert_, assert_array_equal, assert_equal, assert_almost_equal,
assert_equal_records, fail_if_equal, assert_not_equal,
assert_mask_equal,
)
from numpy.ma.core import (
MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all,
allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2,
arcsin, arctan, argsort, array, asarray, choose, concatenate,
conjugate, cos, cosh, count, default_fill_value, diag, divide, empty,
empty_like, equal, exp, flatten_mask, filled, fix_invalid,
flatten_structured_array, fromflex, getmask, getmaskarray, greater,
greater_equal, identity, inner, isMaskedArray, less, less_equal, log,
log10, make_mask, make_mask_descr, mask_or, masked, masked_array,
masked_equal, masked_greater, masked_greater_equal, masked_inside,
masked_less, masked_less_equal, masked_not_equal, masked_outside,
masked_print_option, masked_values, masked_where, max, maximum,
maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply,
mvoid, nomask, not_equal, ones, outer, power, product, put, putmask,
ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt,
subtract, sum, take, tan, tanh, transpose, where, zeros,
)
pi = np.pi
class TestMaskedArray(TestCase):
# Base test class for MaskedArrays.
def setUp(self):
# Base data definition.
x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
a10 = 10.
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
xm = masked_array(x, mask=m1)
ym = masked_array(y, mask=m2)
z = np.array([-.5, 0., .5, .8])
zm = masked_array(z, mask=[0, 1, 0, 0])
xf = np.where(m1, 1e+20, x)
xm.set_fill_value(1e+20)
self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
def test_basicattributes(self):
# Tests some basic array attributes.
a = array([1, 3, 2])
b = array([1, 3, 2], mask=[1, 0, 1])
assert_equal(a.ndim, 1)
assert_equal(b.ndim, 1)
assert_equal(a.size, 3)
assert_equal(b.size, 3)
assert_equal(a.shape, (3,))
assert_equal(b.shape, (3,))
def test_basic0d(self):
# Checks masking a scalar
x = masked_array(0)
assert_equal(str(x), '0')
x = masked_array(0, mask=True)
assert_equal(str(x), str(masked_print_option))
x = masked_array(0, mask=False)
assert_equal(str(x), '0')
x = array(0, mask=1)
self.assertTrue(x.filled().dtype is x._data.dtype)
def test_basic1d(self):
# Test of basic array creation and properties in 1 dimension.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
self.assertTrue(not isMaskedArray(x))
self.assertTrue(isMaskedArray(xm))
self.assertTrue((xm - ym).filled(0).any())
fail_if_equal(xm.mask.astype(int), ym.mask.astype(int))
s = x.shape
assert_equal(np.shape(xm), s)
assert_equal(xm.shape, s)
assert_equal(xm.dtype, x.dtype)
assert_equal(zm.dtype, z.dtype)
assert_equal(xm.size, reduce(lambda x, y:x * y, s))
assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
assert_array_equal(xm, xf)
assert_array_equal(filled(xm, 1.e20), xf)
assert_array_equal(x, xm)
def test_basic2d(self):
# Test of basic array creation and properties in 2 dimensions.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
for s in [(4, 3), (6, 2)]:
x.shape = s
y.shape = s
xm.shape = s
ym.shape = s
xf.shape = s
self.assertTrue(not isMaskedArray(x))
self.assertTrue(isMaskedArray(xm))
assert_equal(shape(xm), s)
assert_equal(xm.shape, s)
assert_equal(xm.size, reduce(lambda x, y:x * y, s))
assert_equal(count(xm), len(m1) - reduce(lambda x, y:x + y, m1))
assert_equal(xm, xf)
assert_equal(filled(xm, 1.e20), xf)
assert_equal(x, xm)
def test_concatenate_basic(self):
# Tests concatenations.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
# basic concatenation
assert_equal(np.concatenate((x, y)), concatenate((xm, ym)))
assert_equal(np.concatenate((x, y)), concatenate((x, y)))
assert_equal(np.concatenate((x, y)), concatenate((xm, y)))
assert_equal(np.concatenate((x, y, x)), concatenate((x, ym, x)))
def test_concatenate_alongaxis(self):
# Tests concatenations.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
# Concatenation along an axis
s = (3, 4)
x.shape = y.shape = xm.shape = ym.shape = s
assert_equal(xm.mask, np.reshape(m1, s))
assert_equal(ym.mask, np.reshape(m2, s))
xmym = concatenate((xm, ym), 1)
assert_equal(np.concatenate((x, y), 1), xmym)
assert_equal(np.concatenate((xm.mask, ym.mask), 1), xmym._mask)
x = zeros(2)
y = array(ones(2), mask=[False, True])
z = concatenate((x, y))
assert_array_equal(z, [0, 0, 1, 1])
assert_array_equal(z.mask, [False, False, False, True])
z = concatenate((y, x))
assert_array_equal(z, [1, 1, 0, 0])
assert_array_equal(z.mask, [False, True, False, False])
def test_concatenate_flexible(self):
# Tests the concatenation on flexible arrays.
data = masked_array(list(zip(np.random.rand(10),
np.arange(10))),
dtype=[('a', float), ('b', int)])
test = concatenate([data[:5], data[5:]])
assert_equal_records(test, data)
def test_creation_ndmin(self):
# Check the use of ndmin
x = array([1, 2, 3], mask=[1, 0, 0], ndmin=2)
assert_equal(x.shape, (1, 3))
assert_equal(x._data, [[1, 2, 3]])
assert_equal(x._mask, [[1, 0, 0]])
def test_creation_ndmin_from_maskedarray(self):
# Make sure we're not losing the original mask w/ ndmin
x = array([1, 2, 3])
x[-1] = masked
xx = array(x, ndmin=2, dtype=float)
assert_equal(x.shape, x._mask.shape)
assert_equal(xx.shape, xx._mask.shape)
def test_creation_maskcreation(self):
# Tests how masks are initialized at the creation of Maskedarrays.
data = arange(24, dtype=float)
data[[3, 6, 15]] = masked
dma_1 = MaskedArray(data)
assert_equal(dma_1.mask, data.mask)
dma_2 = MaskedArray(dma_1)
assert_equal(dma_2.mask, dma_1.mask)
dma_3 = MaskedArray(dma_1, mask=[1, 0, 0, 0] * 6)
fail_if_equal(dma_3.mask, dma_1.mask)
x = array([1, 2, 3], mask=True)
assert_equal(x._mask, [True, True, True])
x = array([1, 2, 3], mask=False)
assert_equal(x._mask, [False, False, False])
y = array([1, 2, 3], mask=x._mask, copy=False)
assert_(np.may_share_memory(x.mask, y.mask))
y = array([1, 2, 3], mask=x._mask, copy=True)
assert_(not np.may_share_memory(x.mask, y.mask))
def test_creation_with_list_of_maskedarrays(self):
# Tests creating a masked array from a list of masked arrays.
x = array(np.arange(5), mask=[1, 0, 0, 0, 0])
data = array((x, x[::-1]))
assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
assert_equal(data._mask, [[1, 0, 0, 0, 0], [0, 0, 0, 0, 1]])
x.mask = nomask
data = array((x, x[::-1]))
assert_equal(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])
self.assertTrue(data.mask is nomask)
def test_asarray(self):
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
xm.fill_value = -9999
xm._hardmask = True
xmm = asarray(xm)
assert_equal(xmm._data, xm._data)
assert_equal(xmm._mask, xm._mask)
assert_equal(xmm.fill_value, xm.fill_value)
assert_equal(xmm._hardmask, xm._hardmask)
def test_asarray_default_order(self):
# See Issue #6646
m = np.eye(3).T
self.assertFalse(m.flags.c_contiguous)
new_m = asarray(m)
self.assertTrue(new_m.flags.c_contiguous)
def test_asarray_enforce_order(self):
# See Issue #6646
m = np.eye(3).T
self.assertFalse(m.flags.c_contiguous)
new_m = asarray(m, order='C')
self.assertTrue(new_m.flags.c_contiguous)
def test_fix_invalid(self):
# Checks fix_invalid.
with np.errstate(invalid='ignore'):
data = masked_array([np.nan, 0., 1.], mask=[0, 0, 1])
data_fixed = fix_invalid(data)
assert_equal(data_fixed._data, [data.fill_value, 0., 1.])
assert_equal(data_fixed._mask, [1., 0., 1.])
def test_maskedelement(self):
# Test of masked element
x = arange(6)
x[1] = masked
self.assertTrue(str(masked) == '--')
self.assertTrue(x[1] is masked)
assert_equal(filled(x[1], 0), 0)
def test_set_element_as_object(self):
# Tests setting elements with object
a = empty(1, dtype=object)
x = (1, 2, 3, 4, 5)
a[0] = x
assert_equal(a[0], x)
self.assertTrue(a[0] is x)
import datetime
dt = datetime.datetime.now()
a[0] = dt
self.assertTrue(a[0] is dt)
def test_indexing(self):
# Tests conversions and indexing
x1 = np.array([1, 2, 4, 3])
x2 = array(x1, mask=[1, 0, 0, 0])
x3 = array(x1, mask=[0, 1, 0, 1])
x4 = array(x1)
# test conversion to strings
str(x2) # raises?
repr(x2) # raises?
assert_equal(np.sort(x1), sort(x2, endwith=False))
# tests of indexing
assert_(type(x2[1]) is type(x1[1]))
assert_(x1[1] == x2[1])
assert_(x2[0] is masked)
assert_equal(x1[2], x2[2])
assert_equal(x1[2:5], x2[2:5])
assert_equal(x1[:], x2[:])
assert_equal(x1[1:], x3[1:])
x1[2] = 9
x2[2] = 9
assert_equal(x1, x2)
x1[1:3] = 99
x2[1:3] = 99
assert_equal(x1, x2)
x2[1] = masked
assert_equal(x1, x2)
x2[1:3] = masked
assert_equal(x1, x2)
x2[:] = x1
x2[1] = masked
assert_(allequal(getmask(x2), array([0, 1, 0, 0])))
x3[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
assert_(allequal(getmask(x3), array([0, 1, 1, 0])))
x4[:] = masked_array([1, 2, 3, 4], [0, 1, 1, 0])
assert_(allequal(getmask(x4), array([0, 1, 1, 0])))
assert_(allequal(x4, array([1, 2, 3, 4])))
x1 = np.arange(5) * 1.0
x2 = masked_values(x1, 3.0)
assert_equal(x1, x2)
assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
assert_equal(3.0, x2.fill_value)
x1 = array([1, 'hello', 2, 3], object)
x2 = np.array([1, 'hello', 2, 3], object)
s1 = x1[1]
s2 = x2[1]
assert_equal(type(s2), str)
assert_equal(type(s1), str)
assert_equal(s1, s2)
assert_(x1[1:1].shape == (0,))
def test_matrix_indexing(self):
# Tests conversions and indexing
x1 = np.matrix([[1, 2, 3], [4, 3, 2]])
x2 = array(x1, mask=[[1, 0, 0], [0, 1, 0]])
x3 = array(x1, mask=[[0, 1, 0], [1, 0, 0]])
x4 = array(x1)
# test conversion to strings
str(x2) # raises?
repr(x2) # raises?
# tests of indexing
assert_(type(x2[1, 0]) is type(x1[1, 0]))
assert_(x1[1, 0] == x2[1, 0])
assert_(x2[1, 1] is masked)
assert_equal(x1[0, 2], x2[0, 2])
assert_equal(x1[0, 1:], x2[0, 1:])
assert_equal(x1[:, 2], x2[:, 2])
assert_equal(x1[:], x2[:])
assert_equal(x1[1:], x3[1:])
x1[0, 2] = 9
x2[0, 2] = 9
assert_equal(x1, x2)
x1[0, 1:] = 99
x2[0, 1:] = 99
assert_equal(x1, x2)
x2[0, 1] = masked
assert_equal(x1, x2)
x2[0, 1:] = masked
assert_equal(x1, x2)
x2[0, :] = x1[0, :]
x2[0, 1] = masked
assert_(allequal(getmask(x2), np.array([[0, 1, 0], [0, 1, 0]])))
x3[1, :] = masked_array([1, 2, 3], [1, 1, 0])
assert_(allequal(getmask(x3)[1], array([1, 1, 0])))
assert_(allequal(getmask(x3[1]), array([1, 1, 0])))
x4[1, :] = masked_array([1, 2, 3], [1, 1, 0])
assert_(allequal(getmask(x4[1]), array([1, 1, 0])))
assert_(allequal(x4[1], array([1, 2, 3])))
x1 = np.matrix(np.arange(5) * 1.0)
x2 = masked_values(x1, 3.0)
assert_equal(x1, x2)
assert_(allequal(array([0, 0, 0, 1, 0], MaskType), x2.mask))
assert_equal(3.0, x2.fill_value)
def test_copy(self):
# Tests of some subtle points of copying and sizing.
n = [0, 0, 1, 0, 0]
m = make_mask(n)
m2 = make_mask(m)
self.assertTrue(m is m2)
m3 = make_mask(m, copy=1)
self.assertTrue(m is not m3)
x1 = np.arange(5)
y1 = array(x1, mask=m)
assert_equal(y1._data.__array_interface__, x1.__array_interface__)
self.assertTrue(allequal(x1, y1.data))
assert_equal(y1._mask.__array_interface__, m.__array_interface__)
y1a = array(y1)
self.assertTrue(y1a._data.__array_interface__ ==
y1._data.__array_interface__)
self.assertTrue(y1a.mask is y1.mask)
y2 = array(x1, mask=m)
self.assertTrue(y2._data.__array_interface__ == x1.__array_interface__)
self.assertTrue(y2._mask.__array_interface__ == m.__array_interface__)
self.assertTrue(y2[2] is masked)
y2[2] = 9
self.assertTrue(y2[2] is not masked)
self.assertTrue(y2._mask.__array_interface__ != m.__array_interface__)
self.assertTrue(allequal(y2.mask, 0))
y3 = array(x1 * 1.0, mask=m)
self.assertTrue(filled(y3).dtype is (x1 * 1.0).dtype)
x4 = arange(4)
x4[2] = masked
y4 = resize(x4, (8,))
assert_equal(concatenate([x4, x4]), y4)
assert_equal(getmask(y4), [0, 0, 1, 0, 0, 0, 1, 0])
y5 = repeat(x4, (2, 2, 2, 2), axis=0)
assert_equal(y5, [0, 0, 1, 1, 2, 2, 3, 3])
y6 = repeat(x4, 2, axis=0)
assert_equal(y5, y6)
y7 = x4.repeat((2, 2, 2, 2), axis=0)
assert_equal(y5, y7)
y8 = x4.repeat(2, 0)
assert_equal(y5, y8)
y9 = x4.copy()
assert_equal(y9._data, x4._data)
assert_equal(y9._mask, x4._mask)
x = masked_array([1, 2, 3], mask=[0, 1, 0])
# Copy is False by default
y = masked_array(x)
assert_equal(y._data.ctypes.data, x._data.ctypes.data)
assert_equal(y._mask.ctypes.data, x._mask.ctypes.data)
y = masked_array(x, copy=True)
assert_not_equal(y._data.ctypes.data, x._data.ctypes.data)
assert_not_equal(y._mask.ctypes.data, x._mask.ctypes.data)
def test_copy_immutable(self):
# Tests that the copy method is immutable, GitHub issue #5247
a = np.ma.array([1, 2, 3])
b = np.ma.array([4, 5, 6])
a_copy_method = a.copy
b.copy
assert_equal(a_copy_method(), [1, 2, 3])
def test_deepcopy(self):
from copy import deepcopy
a = array([0, 1, 2], mask=[False, True, False])
copied = deepcopy(a)
assert_equal(copied.mask, a.mask)
assert_not_equal(id(a._mask), id(copied._mask))
copied[1] = 1
assert_equal(copied.mask, [0, 0, 0])
assert_equal(a.mask, [0, 1, 0])
copied = deepcopy(a)
assert_equal(copied.mask, a.mask)
copied.mask[1] = False
assert_equal(copied.mask, [0, 0, 0])
assert_equal(a.mask, [0, 1, 0])
def test_str_repr(self):
a = array([0, 1, 2], mask=[False, True, False])
assert_equal(str(a), '[0 -- 2]')
assert_equal(repr(a), 'masked_array(data = [0 -- 2],\n'
' mask = [False True False],\n'
' fill_value = 999999)\n')
a = np.ma.arange(2000)
a[1:50] = np.ma.masked
assert_equal(
repr(a),
'masked_array(data = [0 -- -- ..., 1997 1998 1999],\n'
' mask = [False True True ..., False False False],\n'
' fill_value = 999999)\n'
)
def test_pickling(self):
# Tests pickling
a = arange(10)
a[::3] = masked
a.fill_value = 999
a_pickled = pickle.loads(a.dumps())
assert_equal(a_pickled._mask, a._mask)
assert_equal(a_pickled._data, a._data)
assert_equal(a_pickled.fill_value, 999)
def test_pickling_subbaseclass(self):
# Test pickling w/ a subclass of ndarray
a = array(np.matrix(list(range(10))), mask=[1, 0, 1, 0, 0] * 2)
a_pickled = pickle.loads(a.dumps())
assert_equal(a_pickled._mask, a._mask)
assert_equal(a_pickled, a)
self.assertTrue(isinstance(a_pickled._data, np.matrix))
def test_pickling_maskedconstant(self):
# Test pickling MaskedConstant
mc = np.ma.masked
mc_pickled = pickle.loads(mc.dumps())
assert_equal(mc_pickled._baseclass, mc._baseclass)
assert_equal(mc_pickled._mask, mc._mask)
assert_equal(mc_pickled._data, mc._data)
def test_pickling_wstructured(self):
# Tests pickling w/ structured array
a = array([(1, 1.), (2, 2.)], mask=[(0, 0), (0, 1)],
dtype=[('a', int), ('b', float)])
a_pickled = pickle.loads(a.dumps())
assert_equal(a_pickled._mask, a._mask)
assert_equal(a_pickled, a)
def test_pickling_keepalignment(self):
# Tests pickling w/ F_CONTIGUOUS arrays
a = arange(10)
a.shape = (-1, 2)
b = a.T
test = pickle.loads(pickle.dumps(b))
assert_equal(test, b)
def test_single_element_subscript(self):
# Tests single element subscripts of Maskedarrays.
a = array([1, 3, 2])
b = array([1, 3, 2], mask=[1, 0, 1])
assert_equal(a[0].shape, ())
assert_equal(b[0].shape, ())
assert_equal(b[1].shape, ())
def test_topython(self):
# Tests some communication issues with Python.
assert_equal(1, int(array(1)))
assert_equal(1.0, float(array(1)))
assert_equal(1, int(array([[[1]]])))
assert_equal(1.0, float(array([[1]])))
self.assertRaises(TypeError, float, array([1, 1]))
with warnings.catch_warnings():
warnings.simplefilter('ignore', UserWarning)
assert_(np.isnan(float(array([1], mask=[1]))))
a = array([1, 2, 3], mask=[1, 0, 0])
self.assertRaises(TypeError, lambda:float(a))
assert_equal(float(a[-1]), 3.)
self.assertTrue(np.isnan(float(a[0])))
self.assertRaises(TypeError, int, a)
assert_equal(int(a[-1]), 3)
self.assertRaises(MAError, lambda:int(a[0]))
def test_oddfeatures_1(self):
# Test of other odd features
x = arange(20)
x = x.reshape(4, 5)
x.flat[5] = 12
assert_(x[1, 0] == 12)
z = x + 10j * x
assert_equal(z.real, x)
assert_equal(z.imag, 10 * x)
assert_equal((z * conjugate(z)).real, 101 * x * x)
z.imag[...] = 0.0
x = arange(10)
x[3] = masked
assert_(str(x[3]) == str(masked))
c = x >= 8
assert_(count(where(c, masked, masked)) == 0)
assert_(shape(where(c, masked, masked)) == c.shape)
z = masked_where(c, x)
assert_(z.dtype is x.dtype)
assert_(z[3] is masked)
assert_(z[4] is not masked)
assert_(z[7] is not masked)
assert_(z[8] is masked)
assert_(z[9] is masked)
assert_equal(x, z)
def test_oddfeatures_2(self):
# Tests some more features.
x = array([1., 2., 3., 4., 5.])
c = array([1, 1, 1, 0, 0])
x[2] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
c[0] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
assert_(z[0] is masked)
assert_(z[1] is not masked)
assert_(z[2] is masked)
def test_oddfeatures_3(self):
# Tests some generic features
atest = array([10], mask=True)
btest = array([20])
idx = atest.mask
atest[idx] = btest[idx]
assert_equal(atest, [20])
def test_filled_w_object_dtype(self):
a = np.ma.masked_all(1, dtype='O')
assert_equal(a.filled('x')[0], 'x')
def test_filled_w_flexible_dtype(self):
# Test filled w/ flexible dtype
flexi = array([(1, 1, 1)],
dtype=[('i', int), ('s', '|S8'), ('f', float)])
flexi[0] = masked
assert_equal(flexi.filled(),
np.array([(default_fill_value(0),
default_fill_value('0'),
default_fill_value(0.),)], dtype=flexi.dtype))
flexi[0] = masked
assert_equal(flexi.filled(1),
np.array([(1, '1', 1.)], dtype=flexi.dtype))
def test_filled_w_mvoid(self):
# Test filled w/ mvoid
ndtype = [('a', int), ('b', float)]
a = mvoid((1, 2.), mask=[(0, 1)], dtype=ndtype)
# Filled using default
test = a.filled()
assert_equal(tuple(test), (1, default_fill_value(1.)))
# Explicit fill_value
test = a.filled((-1, -1))
assert_equal(tuple(test), (1, -1))
# Using predefined filling values
a.fill_value = (-999, -999)
assert_equal(tuple(a.filled()), (1, -999))
def test_filled_w_nested_dtype(self):
# Test filled w/ nested dtype
ndtype = [('A', int), ('B', [('BA', int), ('BB', int)])]
a = array([(1, (1, 1)), (2, (2, 2))],
mask=[(0, (1, 0)), (0, (0, 1))], dtype=ndtype)
test = a.filled(0)
control = np.array([(1, (0, 1)), (2, (2, 0))], dtype=ndtype)
assert_equal(test, control)
test = a['B'].filled(0)
control = np.array([(0, 1), (2, 0)], dtype=a['B'].dtype)
assert_equal(test, control)
# test if mask gets set correctly (see #6760)
Z = numpy.ma.zeros(2, numpy.dtype([("A", "(2,2)i1,(2,2)i1", (2,2))]))
assert_equal(Z.data.dtype, numpy.dtype([('A', [('f0', 'i1', (2, 2)),
('f1', 'i1', (2, 2))], (2, 2))]))
assert_equal(Z.mask.dtype, numpy.dtype([('A', [('f0', '?', (2, 2)),
('f1', '?', (2, 2))], (2, 2))]))
def test_filled_w_f_order(self):
# Test filled w/ F-contiguous array
a = array(np.array([(0, 1, 2), (4, 5, 6)], order='F'),
mask=np.array([(0, 0, 1), (1, 0, 0)], order='F'),
order='F') # this is currently ignored
self.assertTrue(a.flags['F_CONTIGUOUS'])
self.assertTrue(a.filled(0).flags['F_CONTIGUOUS'])
def test_optinfo_propagation(self):
# Checks that _optinfo dictionary isn't back-propagated
x = array([1, 2, 3, ], dtype=float)
x._optinfo['info'] = '???'
y = x.copy()
assert_equal(y._optinfo['info'], '???')
y._optinfo['info'] = '!!!'
assert_equal(x._optinfo['info'], '???')
def test_fancy_printoptions(self):
# Test printing a masked array w/ fancy dtype.
fancydtype = np.dtype([('x', int), ('y', [('t', int), ('s', float)])])
test = array([(1, (2, 3.0)), (4, (5, 6.0))],
mask=[(1, (0, 1)), (0, (1, 0))],
dtype=fancydtype)
control = "[(--, (2, --)) (4, (--, 6.0))]"
assert_equal(str(test), control)
# Test 0-d array with multi-dimensional dtype
t_2d0 = masked_array(data = (0, [[0.0, 0.0, 0.0],
[0.0, 0.0, 0.0]],
0.0),
mask = (False, [[True, False, True],
[False, False, True]],
False),
dtype = "int, (2,3)float, float")
control = "(0, [[--, 0.0, --], [0.0, 0.0, --]], 0.0)"
assert_equal(str(t_2d0), control)
def test_flatten_structured_array(self):
# Test flatten_structured_array on arrays
# On ndarray
ndtype = [('a', int), ('b', float)]
a = np.array([(1, 1), (2, 2)], dtype=ndtype)
test = flatten_structured_array(a)
control = np.array([[1., 1.], [2., 2.]], dtype=np.float)
assert_equal(test, control)
assert_equal(test.dtype, control.dtype)
# On masked_array
a = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
test = flatten_structured_array(a)
control = array([[1., 1.], [2., 2.]],
mask=[[0, 1], [1, 0]], dtype=np.float)
assert_equal(test, control)
assert_equal(test.dtype, control.dtype)
assert_equal(test.mask, control.mask)
# On masked array with nested structure
ndtype = [('a', int), ('b', [('ba', int), ('bb', float)])]
a = array([(1, (1, 1.1)), (2, (2, 2.2))],
mask=[(0, (1, 0)), (1, (0, 1))], dtype=ndtype)
test = flatten_structured_array(a)
control = array([[1., 1., 1.1], [2., 2., 2.2]],
mask=[[0, 1, 0], [1, 0, 1]], dtype=np.float)
assert_equal(test, control)
assert_equal(test.dtype, control.dtype)
assert_equal(test.mask, control.mask)
# Keeping the initial shape
ndtype = [('a', int), ('b', float)]
a = np.array([[(1, 1), ], [(2, 2), ]], dtype=ndtype)
test = flatten_structured_array(a)
control = np.array([[[1., 1.], ], [[2., 2.], ]], dtype=np.float)
assert_equal(test, control)
assert_equal(test.dtype, control.dtype)
def test_void0d(self):
# Test creating a mvoid object
ndtype = [('a', int), ('b', int)]
a = np.array([(1, 2,)], dtype=ndtype)[0]
f = mvoid(a)
assert_(isinstance(f, mvoid))
a = masked_array([(1, 2)], mask=[(1, 0)], dtype=ndtype)[0]
assert_(isinstance(a, mvoid))
a = masked_array([(1, 2), (1, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
f = mvoid(a._data[0], a._mask[0])
assert_(isinstance(f, mvoid))
def test_mvoid_getitem(self):
# Test mvoid.__getitem__
ndtype = [('a', int), ('b', int)]
a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)],
dtype=ndtype)
# w/o mask
f = a[0]
self.assertTrue(isinstance(f, mvoid))
assert_equal((f[0], f['a']), (1, 1))
assert_equal(f['b'], 2)
# w/ mask
f = a[1]
self.assertTrue(isinstance(f, mvoid))
self.assertTrue(f[0] is masked)
self.assertTrue(f['a'] is masked)
assert_equal(f[1], 4)
# exotic dtype
A = masked_array(data=[([0,1],)],
mask=[([True, False],)],
dtype=[("A", ">i2", (2,))])
assert_equal(A[0]["A"], A["A"][0])
assert_equal(A[0]["A"], masked_array(data=[0, 1],
mask=[True, False], dtype=">i2"))
def test_mvoid_iter(self):
# Test iteration on __getitem__
ndtype = [('a', int), ('b', int)]
a = masked_array([(1, 2,), (3, 4)], mask=[(0, 0), (1, 0)],
dtype=ndtype)
# w/o mask
assert_equal(list(a[0]), [1, 2])
# w/ mask
assert_equal(list(a[1]), [masked, 4])
def test_mvoid_print(self):
# Test printing a mvoid
mx = array([(1, 1), (2, 2)], dtype=[('a', int), ('b', int)])
assert_equal(str(mx[0]), "(1, 1)")
mx['b'][0] = masked
ini_display = masked_print_option._display
masked_print_option.set_display("-X-")
try:
assert_equal(str(mx[0]), "(1, -X-)")
assert_equal(repr(mx[0]), "(1, -X-)")
finally:
masked_print_option.set_display(ini_display)
# also check if there are object datatypes (see gh-7493)
mx = array([(1,), (2,)], dtype=[('a', 'O')])
assert_equal(str(mx[0]), "(1,)")
def test_mvoid_multidim_print(self):
# regression test for gh-6019
t_ma = masked_array(data = [([1, 2, 3],)],
mask = [([False, True, False],)],
fill_value = ([999999, 999999, 999999],),
dtype = [('a', '<i4', (3,))])
assert_(str(t_ma[0]) == "([1, --, 3],)")
assert_(repr(t_ma[0]) == "([1, --, 3],)")
# additional tests with structured arrays
t_2d = masked_array(data = [([[1, 2], [3,4]],)],
mask = [([[False, True], [True, False]],)],
dtype = [('a', '<i4', (2,2))])
assert_(str(t_2d[0]) == "([[1, --], [--, 4]],)")
assert_(repr(t_2d[0]) == "([[1, --], [--, 4]],)")
t_0d = masked_array(data = [(1,2)],
mask = [(True,False)],
dtype = [('a', '<i4'), ('b', '<i4')])
assert_(str(t_0d[0]) == "(--, 2)")
assert_(repr(t_0d[0]) == "(--, 2)")
t_2d = masked_array(data = [([[1, 2], [3,4]], 1)],
mask = [([[False, True], [True, False]], False)],
dtype = [('a', '<i4', (2,2)), ('b', float)])
assert_(str(t_2d[0]) == "([[1, --], [--, 4]], 1.0)")
assert_(repr(t_2d[0]) == "([[1, --], [--, 4]], 1.0)")
t_ne = masked_array(data=[(1, (1, 1))],
mask=[(True, (True, False))],
dtype = [('a', '<i4'), ('b', 'i4,i4')])
assert_(str(t_ne[0]) == "(--, (--, 1))")
assert_(repr(t_ne[0]) == "(--, (--, 1))")
def test_object_with_array(self):
mx1 = masked_array([1.], mask=[True])
mx2 = masked_array([1., 2.])
mx = masked_array([mx1, mx2], mask=[False, True])
assert_(mx[0] is mx1)
assert_(mx[1] is not mx2)
assert_(np.all(mx[1].data == mx2.data))
assert_(np.all(mx[1].mask))
# check that we return a view.
mx[1].data[0] = 0.
assert_(mx2[0] == 0.)
class TestMaskedArrayArithmetic(TestCase):
# Base test class for MaskedArrays.
def setUp(self):
# Base data definition.
x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
a10 = 10.
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
xm = masked_array(x, mask=m1)
ym = masked_array(y, mask=m2)
z = np.array([-.5, 0., .5, .8])
zm = masked_array(z, mask=[0, 1, 0, 0])
xf = np.where(m1, 1e+20, x)
xm.set_fill_value(1e+20)
self.d = (x, y, a10, m1, m2, xm, ym, z, zm, xf)
self.err_status = np.geterr()
np.seterr(divide='ignore', invalid='ignore')
def tearDown(self):
np.seterr(**self.err_status)
def test_basic_arithmetic(self):
# Test of basic arithmetic.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
a2d = array([[1, 2], [0, 4]])
a2dm = masked_array(a2d, [[0, 0], [1, 0]])
assert_equal(a2d * a2d, a2d * a2dm)
assert_equal(a2d + a2d, a2d + a2dm)
assert_equal(a2d - a2d, a2d - a2dm)
for s in [(12,), (4, 3), (2, 6)]:
x = x.reshape(s)
y = y.reshape(s)
xm = xm.reshape(s)
ym = ym.reshape(s)
xf = xf.reshape(s)
assert_equal(-x, -xm)
assert_equal(x + y, xm + ym)
assert_equal(x - y, xm - ym)
assert_equal(x * y, xm * ym)
assert_equal(x / y, xm / ym)
assert_equal(a10 + y, a10 + ym)
assert_equal(a10 - y, a10 - ym)
assert_equal(a10 * y, a10 * ym)
assert_equal(a10 / y, a10 / ym)
assert_equal(x + a10, xm + a10)
assert_equal(x - a10, xm - a10)
assert_equal(x * a10, xm * a10)
assert_equal(x / a10, xm / a10)
assert_equal(x ** 2, xm ** 2)
assert_equal(abs(x) ** 2.5, abs(xm) ** 2.5)
assert_equal(x ** y, xm ** ym)
assert_equal(np.add(x, y), add(xm, ym))
assert_equal(np.subtract(x, y), subtract(xm, ym))
assert_equal(np.multiply(x, y), multiply(xm, ym))
assert_equal(np.divide(x, y), divide(xm, ym))
def test_divide_on_different_shapes(self):
x = arange(6, dtype=float)
x.shape = (2, 3)
y = arange(3, dtype=float)
z = x / y
assert_equal(z, [[-1., 1., 1.], [-1., 4., 2.5]])
assert_equal(z.mask, [[1, 0, 0], [1, 0, 0]])
z = x / y[None,:]
assert_equal(z, [[-1., 1., 1.], [-1., 4., 2.5]])
assert_equal(z.mask, [[1, 0, 0], [1, 0, 0]])
y = arange(2, dtype=float)
z = x / y[:, None]
assert_equal(z, [[-1., -1., -1.], [3., 4., 5.]])
assert_equal(z.mask, [[1, 1, 1], [0, 0, 0]])
def test_mixed_arithmetic(self):
# Tests mixed arithmetics.
na = np.array([1])
ma = array([1])
self.assertTrue(isinstance(na + ma, MaskedArray))
self.assertTrue(isinstance(ma + na, MaskedArray))
def test_limits_arithmetic(self):
tiny = np.finfo(float).tiny
a = array([tiny, 1. / tiny, 0.])
assert_equal(getmaskarray(a / 2), [0, 0, 0])
assert_equal(getmaskarray(2 / a), [1, 0, 1])
def test_masked_singleton_arithmetic(self):
# Tests some scalar arithmetics on MaskedArrays.
# Masked singleton should remain masked no matter what
xm = array(0, mask=1)
self.assertTrue((1 / array(0)).mask)
self.assertTrue((1 + xm).mask)
self.assertTrue((-xm).mask)
self.assertTrue(maximum(xm, xm).mask)
self.assertTrue(minimum(xm, xm).mask)
def test_masked_singleton_equality(self):
# Tests (in)equality on masked singleton
a = array([1, 2, 3], mask=[1, 1, 0])
assert_((a[0] == 0) is masked)
assert_((a[0] != 0) is masked)
assert_equal((a[-1] == 0), False)
assert_equal((a[-1] != 0), True)
def test_arithmetic_with_masked_singleton(self):
# Checks that there's no collapsing to masked
x = masked_array([1, 2])
y = x * masked
assert_equal(y.shape, x.shape)
assert_equal(y._mask, [True, True])
y = x[0] * masked
assert_(y is masked)
y = x + masked
assert_equal(y.shape, x.shape)
assert_equal(y._mask, [True, True])
def test_arithmetic_with_masked_singleton_on_1d_singleton(self):
# Check that we're not losing the shape of a singleton
x = masked_array([1, ])
y = x + masked
assert_equal(y.shape, x.shape)
assert_equal(y.mask, [True, ])
def test_scalar_arithmetic(self):
x = array(0, mask=0)
assert_equal(x.filled().ctypes.data, x.ctypes.data)
# Make sure we don't lose the shape in some circumstances
xm = array((0, 0)) / 0.
assert_equal(xm.shape, (2,))
assert_equal(xm.mask, [1, 1])
def test_basic_ufuncs(self):
# Test various functions such as sin, cos.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
assert_equal(np.cos(x), cos(xm))
assert_equal(np.cosh(x), cosh(xm))
assert_equal(np.sin(x), sin(xm))
assert_equal(np.sinh(x), sinh(xm))
assert_equal(np.tan(x), tan(xm))
assert_equal(np.tanh(x), tanh(xm))
assert_equal(np.sqrt(abs(x)), sqrt(xm))
assert_equal(np.log(abs(x)), log(xm))
assert_equal(np.log10(abs(x)), log10(xm))
assert_equal(np.exp(x), exp(xm))
assert_equal(np.arcsin(z), arcsin(zm))
assert_equal(np.arccos(z), arccos(zm))
assert_equal(np.arctan(z), arctan(zm))
assert_equal(np.arctan2(x, y), arctan2(xm, ym))
assert_equal(np.absolute(x), absolute(xm))
assert_equal(np.angle(x + 1j*y), angle(xm + 1j*ym))
assert_equal(np.angle(x + 1j*y, deg=True), angle(xm + 1j*ym, deg=True))
assert_equal(np.equal(x, y), equal(xm, ym))
assert_equal(np.not_equal(x, y), not_equal(xm, ym))
assert_equal(np.less(x, y), less(xm, ym))
assert_equal(np.greater(x, y), greater(xm, ym))
assert_equal(np.less_equal(x, y), less_equal(xm, ym))
assert_equal(np.greater_equal(x, y), greater_equal(xm, ym))
assert_equal(np.conjugate(x), conjugate(xm))
def test_count_func(self):
# Tests count
assert_equal(1, count(1))
assert_equal(0, array(1, mask=[1]))
ott = array([0., 1., 2., 3.], mask=[1, 0, 0, 0])
res = count(ott)
self.assertTrue(res.dtype.type is np.intp)
assert_equal(3, res)
ott = ott.reshape((2, 2))
res = count(ott)
assert_(res.dtype.type is np.intp)
assert_equal(3, res)
res = count(ott, 0)
assert_(isinstance(res, ndarray))
assert_equal([1, 2], res)
assert_(getmask(res) is nomask)
ott = array([0., 1., 2., 3.])
res = count(ott, 0)
assert_(isinstance(res, ndarray))
assert_(res.dtype.type is np.intp)
assert_raises(ValueError, ott.count, axis=1)
def test_minmax_func(self):
# Tests minimum and maximum.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
# max doesn't work if shaped
xr = np.ravel(x)
xmr = ravel(xm)
# following are true because of careful selection of data
assert_equal(max(xr), maximum(xmr))
assert_equal(min(xr), minimum(xmr))
assert_equal(minimum([1, 2, 3], [4, 0, 9]), [1, 0, 3])
assert_equal(maximum([1, 2, 3], [4, 0, 9]), [4, 2, 9])
x = arange(5)
y = arange(5) - 2
x[3] = masked
y[0] = masked
assert_equal(minimum(x, y), where(less(x, y), x, y))
assert_equal(maximum(x, y), where(greater(x, y), x, y))
assert_(minimum(x) == 0)
assert_(maximum(x) == 4)
x = arange(4).reshape(2, 2)
x[-1, -1] = masked
assert_equal(maximum(x), 2)
def test_minimummaximum_func(self):
a = np.ones((2, 2))
aminimum = minimum(a, a)
self.assertTrue(isinstance(aminimum, MaskedArray))
assert_equal(aminimum, np.minimum(a, a))
aminimum = minimum.outer(a, a)
self.assertTrue(isinstance(aminimum, MaskedArray))
assert_equal(aminimum, np.minimum.outer(a, a))
amaximum = maximum(a, a)
self.assertTrue(isinstance(amaximum, MaskedArray))
assert_equal(amaximum, np.maximum(a, a))
amaximum = maximum.outer(a, a)
self.assertTrue(isinstance(amaximum, MaskedArray))
assert_equal(amaximum, np.maximum.outer(a, a))
def test_minmax_reduce(self):
# Test np.min/maximum.reduce on array w/ full False mask
a = array([1, 2, 3], mask=[False, False, False])
b = np.maximum.reduce(a)
assert_equal(b, 3)
def test_minmax_funcs_with_output(self):
# Tests the min/max functions with explicit outputs
mask = np.random.rand(12).round()
xm = array(np.random.uniform(0, 10, 12), mask=mask)
xm.shape = (3, 4)
for funcname in ('min', 'max'):
# Initialize
npfunc = getattr(np, funcname)
mafunc = getattr(numpy.ma.core, funcname)
# Use the np version
nout = np.empty((4,), dtype=int)
try:
result = npfunc(xm, axis=0, out=nout)
except MaskError:
pass
nout = np.empty((4,), dtype=float)
result = npfunc(xm, axis=0, out=nout)
self.assertTrue(result is nout)
# Use the ma version
nout.fill(-999)
result = mafunc(xm, axis=0, out=nout)
self.assertTrue(result is nout)
def test_minmax_methods(self):
# Additional tests on max/min
(_, _, _, _, _, xm, _, _, _, _) = self.d
xm.shape = (xm.size,)
assert_equal(xm.max(), 10)
self.assertTrue(xm[0].max() is masked)
self.assertTrue(xm[0].max(0) is masked)
self.assertTrue(xm[0].max(-1) is masked)
assert_equal(xm.min(), -10.)
self.assertTrue(xm[0].min() is masked)
self.assertTrue(xm[0].min(0) is masked)
self.assertTrue(xm[0].min(-1) is masked)
assert_equal(xm.ptp(), 20.)
self.assertTrue(xm[0].ptp() is masked)
self.assertTrue(xm[0].ptp(0) is masked)
self.assertTrue(xm[0].ptp(-1) is masked)
x = array([1, 2, 3], mask=True)
self.assertTrue(x.min() is masked)
self.assertTrue(x.max() is masked)
self.assertTrue(x.ptp() is masked)
def test_addsumprod(self):
# Tests add, sum, product.
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
assert_equal(np.add.reduce(x), add.reduce(x))
assert_equal(np.add.accumulate(x), add.accumulate(x))
assert_equal(4, sum(array(4), axis=0))
assert_equal(4, sum(array(4), axis=0))
assert_equal(np.sum(x, axis=0), sum(x, axis=0))
assert_equal(np.sum(filled(xm, 0), axis=0), sum(xm, axis=0))
assert_equal(np.sum(x, 0), sum(x, 0))
assert_equal(np.product(x, axis=0), product(x, axis=0))
assert_equal(np.product(x, 0), product(x, 0))
assert_equal(np.product(filled(xm, 1), axis=0), product(xm, axis=0))
s = (3, 4)
x.shape = y.shape = xm.shape = ym.shape = s
if len(s) > 1:
assert_equal(np.concatenate((x, y), 1), concatenate((xm, ym), 1))
assert_equal(np.add.reduce(x, 1), add.reduce(x, 1))
assert_equal(np.sum(x, 1), sum(x, 1))
assert_equal(np.product(x, 1), product(x, 1))
def test_binops_d2D(self):
# Test binary operations on 2D data
a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]])
b = array([[2., 3.], [4., 5.], [6., 7.]])
test = a * b
control = array([[2., 3.], [2., 2.], [3., 3.]],
mask=[[0, 0], [1, 1], [1, 1]])
assert_equal(test, control)
assert_equal(test.data, control.data)
assert_equal(test.mask, control.mask)
test = b * a
control = array([[2., 3.], [4., 5.], [6., 7.]],
mask=[[0, 0], [1, 1], [1, 1]])
assert_equal(test, control)
assert_equal(test.data, control.data)
assert_equal(test.mask, control.mask)
a = array([[1.], [2.], [3.]])
b = array([[2., 3.], [4., 5.], [6., 7.]],
mask=[[0, 0], [0, 0], [0, 1]])
test = a * b
control = array([[2, 3], [8, 10], [18, 3]],
mask=[[0, 0], [0, 0], [0, 1]])
assert_equal(test, control)
assert_equal(test.data, control.data)
assert_equal(test.mask, control.mask)
test = b * a
control = array([[2, 3], [8, 10], [18, 7]],
mask=[[0, 0], [0, 0], [0, 1]])
assert_equal(test, control)
assert_equal(test.data, control.data)
assert_equal(test.mask, control.mask)
def test_domained_binops_d2D(self):
# Test domained binary operations on 2D data
a = array([[1.], [2.], [3.]], mask=[[False], [True], [True]])
b = array([[2., 3.], [4., 5.], [6., 7.]])
test = a / b
control = array([[1. / 2., 1. / 3.], [2., 2.], [3., 3.]],
mask=[[0, 0], [1, 1], [1, 1]])
assert_equal(test, control)
assert_equal(test.data, control.data)
assert_equal(test.mask, control.mask)
test = b / a
control = array([[2. / 1., 3. / 1.], [4., 5.], [6., 7.]],
mask=[[0, 0], [1, 1], [1, 1]])
assert_equal(test, control)
assert_equal(test.data, control.data)
assert_equal(test.mask, control.mask)
a = array([[1.], [2.], [3.]])
b = array([[2., 3.], [4., 5.], [6., 7.]],
mask=[[0, 0], [0, 0], [0, 1]])
test = a / b
control = array([[1. / 2, 1. / 3], [2. / 4, 2. / 5], [3. / 6, 3]],
mask=[[0, 0], [0, 0], [0, 1]])
assert_equal(test, control)
assert_equal(test.data, control.data)
assert_equal(test.mask, control.mask)
test = b / a
control = array([[2 / 1., 3 / 1.], [4 / 2., 5 / 2.], [6 / 3., 7]],
mask=[[0, 0], [0, 0], [0, 1]])
assert_equal(test, control)
assert_equal(test.data, control.data)
assert_equal(test.mask, control.mask)
def test_noshrinking(self):
# Check that we don't shrink a mask when not wanted
# Binary operations
a = masked_array([1., 2., 3.], mask=[False, False, False],
shrink=False)
b = a + 1
assert_equal(b.mask, [0, 0, 0])
# In place binary operation
a += 1
assert_equal(a.mask, [0, 0, 0])
# Domained binary operation
b = a / 1.
assert_equal(b.mask, [0, 0, 0])
# In place binary operation
a /= 1.
assert_equal(a.mask, [0, 0, 0])
def test_noshink_on_creation(self):
# Check that the mask is not shrunk on array creation when not wanted
a = np.ma.masked_values([1., 2.5, 3.1], 1.5, shrink=False)
assert_equal(a.mask, [0, 0, 0])
def test_mod(self):
# Tests mod
(x, y, a10, m1, m2, xm, ym, z, zm, xf) = self.d
assert_equal(mod(x, y), mod(xm, ym))
test = mod(ym, xm)
assert_equal(test, np.mod(ym, xm))
assert_equal(test.mask, mask_or(xm.mask, ym.mask))
test = mod(xm, ym)
assert_equal(test, np.mod(xm, ym))
assert_equal(test.mask, mask_or(mask_or(xm.mask, ym.mask), (ym == 0)))
def test_TakeTransposeInnerOuter(self):
# Test of take, transpose, inner, outer products
x = arange(24)
y = np.arange(24)
x[5:6] = masked
x = x.reshape(2, 3, 4)
y = y.reshape(2, 3, 4)
assert_equal(np.transpose(y, (2, 0, 1)), transpose(x, (2, 0, 1)))
assert_equal(np.take(y, (2, 0, 1), 1), take(x, (2, 0, 1), 1))
assert_equal(np.inner(filled(x, 0), filled(y, 0)),
inner(x, y))
assert_equal(np.outer(filled(x, 0), filled(y, 0)),
outer(x, y))
y = array(['abc', 1, 'def', 2, 3], object)
y[2] = masked
t = take(y, [0, 3, 4])
assert_(t[0] == 'abc')
assert_(t[1] == 2)
assert_(t[2] == 3)
def test_imag_real(self):
# Check complex
xx = array([1 + 10j, 20 + 2j], mask=[1, 0])
assert_equal(xx.imag, [10, 2])
assert_equal(xx.imag.filled(), [1e+20, 2])
assert_equal(xx.imag.dtype, xx._data.imag.dtype)
assert_equal(xx.real, [1, 20])
assert_equal(xx.real.filled(), [1e+20, 20])
assert_equal(xx.real.dtype, xx._data.real.dtype)
def test_methods_with_output(self):
xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
xm[:, 0] = xm[0] = xm[-1, -1] = masked
funclist = ('sum', 'prod', 'var', 'std', 'max', 'min', 'ptp', 'mean',)
for funcname in funclist:
npfunc = getattr(np, funcname)
xmmeth = getattr(xm, funcname)
# A ndarray as explicit input
output = np.empty(4, dtype=float)
output.fill(-9999)
result = npfunc(xm, axis=0, out=output)
# ... the result should be the given output
assert_(result is output)
assert_equal(result, xmmeth(axis=0, out=output))
output = empty(4, dtype=int)
result = xmmeth(axis=0, out=output)
assert_(result is output)
assert_(output[0] is masked)
def test_count_mean_with_matrix(self):
m = np.ma.array(np.matrix([[1,2],[3,4]]), mask=np.zeros((2,2)))
assert_equal(m.count(axis=0).shape, (1,2))
assert_equal(m.count(axis=1).shape, (2,1))
#make sure broadcasting inside mean and var work
assert_equal(m.mean(axis=0), [[2., 3.]])
assert_equal(m.mean(axis=1), [[1.5], [3.5]])
def test_eq_on_structured(self):
# Test the equality of structured arrays
ndtype = [('A', int), ('B', int)]
a = array([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype)
test = (a == a)
assert_equal(test, [True, True])
assert_equal(test.mask, [False, False])
b = array([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
test = (a == b)
assert_equal(test, [False, True])
assert_equal(test.mask, [True, False])
b = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
test = (a == b)
assert_equal(test, [True, False])
assert_equal(test.mask, [False, False])
def test_ne_on_structured(self):
# Test the equality of structured arrays
ndtype = [('A', int), ('B', int)]
a = array([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype)
test = (a != a)
assert_equal(test, [False, False])
assert_equal(test.mask, [False, False])
b = array([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)
test = (a != b)
assert_equal(test, [True, False])
assert_equal(test.mask, [True, False])
b = array([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)
test = (a != b)
assert_equal(test, [False, True])
assert_equal(test.mask, [False, False])
def test_eq_w_None(self):
# Really, comparisons with None should not be done, but check them
# anyway. Note that pep8 will flag these tests.
# With partial mask
a = array([1, 2], mask=[0, 1])
assert_equal(a == None, False)
assert_equal(a.data == None, False)
assert_equal(a.mask == None, False)
assert_equal(a != None, True)
# With nomask
a = array([1, 2], mask=False)
assert_equal(a == None, False)
assert_equal(a != None, True)
# With complete mask
a = array([1, 2], mask=True)
assert_equal(a == None, False)
assert_equal(a != None, True)
# Fully masked, even comparison to None should return "masked"
a = masked
assert_equal(a == None, masked)
def test_eq_w_scalar(self):
a = array(1)
assert_equal(a == 1, True)
assert_equal(a == 0, False)
assert_equal(a != 1, False)
assert_equal(a != 0, True)
def test_numpyarithmetics(self):
# Check that the mask is not back-propagated when using numpy functions
a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1])
control = masked_array([np.nan, np.nan, 0, np.log(2), -1],
mask=[1, 1, 0, 0, 1])
test = log(a)
assert_equal(test, control)
assert_equal(test.mask, control.mask)
assert_equal(a.mask, [0, 0, 0, 0, 1])
test = np.log(a)
assert_equal(test, control)
assert_equal(test.mask, control.mask)
assert_equal(a.mask, [0, 0, 0, 0, 1])
class TestMaskedArrayAttributes(TestCase):
def test_keepmask(self):
# Tests the keep mask flag
x = masked_array([1, 2, 3], mask=[1, 0, 0])
mx = masked_array(x)
assert_equal(mx.mask, x.mask)
mx = masked_array(x, mask=[0, 1, 0], keep_mask=False)
assert_equal(mx.mask, [0, 1, 0])
mx = masked_array(x, mask=[0, 1, 0], keep_mask=True)
assert_equal(mx.mask, [1, 1, 0])
# We default to true
mx = masked_array(x, mask=[0, 1, 0])
assert_equal(mx.mask, [1, 1, 0])
def test_hardmask(self):
# Test hard_mask
d = arange(5)
n = [0, 0, 0, 1, 1]
m = make_mask(n)
xh = array(d, mask=m, hard_mask=True)
# We need to copy, to avoid updating d in xh !
xs = array(d, mask=m, hard_mask=False, copy=True)
xh[[1, 4]] = [10, 40]
xs[[1, 4]] = [10, 40]
assert_equal(xh._data, [0, 10, 2, 3, 4])
assert_equal(xs._data, [0, 10, 2, 3, 40])
assert_equal(xs.mask, [0, 0, 0, 1, 0])
self.assertTrue(xh._hardmask)
self.assertTrue(not xs._hardmask)
xh[1:4] = [10, 20, 30]
xs[1:4] = [10, 20, 30]
assert_equal(xh._data, [0, 10, 20, 3, 4])
assert_equal(xs._data, [0, 10, 20, 30, 40])
assert_equal(xs.mask, nomask)
xh[0] = masked
xs[0] = masked
assert_equal(xh.mask, [1, 0, 0, 1, 1])
assert_equal(xs.mask, [1, 0, 0, 0, 0])
xh[:] = 1
xs[:] = 1
assert_equal(xh._data, [0, 1, 1, 3, 4])
assert_equal(xs._data, [1, 1, 1, 1, 1])
assert_equal(xh.mask, [1, 0, 0, 1, 1])
assert_equal(xs.mask, nomask)
# Switch to soft mask
xh.soften_mask()
xh[:] = arange(5)
assert_equal(xh._data, [0, 1, 2, 3, 4])
assert_equal(xh.mask, nomask)
# Switch back to hard mask
xh.harden_mask()
xh[xh < 3] = masked
assert_equal(xh._data, [0, 1, 2, 3, 4])
assert_equal(xh._mask, [1, 1, 1, 0, 0])
xh[filled(xh > 1, False)] = 5
assert_equal(xh._data, [0, 1, 2, 5, 5])
assert_equal(xh._mask, [1, 1, 1, 0, 0])
xh = array([[1, 2], [3, 4]], mask=[[1, 0], [0, 0]], hard_mask=True)
xh[0] = 0
assert_equal(xh._data, [[1, 0], [3, 4]])
assert_equal(xh._mask, [[1, 0], [0, 0]])
xh[-1, -1] = 5
assert_equal(xh._data, [[1, 0], [3, 5]])
assert_equal(xh._mask, [[1, 0], [0, 0]])
xh[filled(xh < 5, False)] = 2
assert_equal(xh._data, [[1, 2], [2, 5]])
assert_equal(xh._mask, [[1, 0], [0, 0]])
def test_hardmask_again(self):
# Another test of hardmask
d = arange(5)
n = [0, 0, 0, 1, 1]
m = make_mask(n)
xh = array(d, mask=m, hard_mask=True)
xh[4:5] = 999
xh[0:1] = 999
assert_equal(xh._data, [999, 1, 2, 3, 4])
def test_hardmask_oncemore_yay(self):
# OK, yet another test of hardmask
# Make sure that harden_mask/soften_mask//unshare_mask returns self
a = array([1, 2, 3], mask=[1, 0, 0])
b = a.harden_mask()
assert_equal(a, b)
b[0] = 0
assert_equal(a, b)
assert_equal(b, array([1, 2, 3], mask=[1, 0, 0]))
a = b.soften_mask()
a[0] = 0
assert_equal(a, b)
assert_equal(b, array([0, 2, 3], mask=[0, 0, 0]))
def test_smallmask(self):
# Checks the behaviour of _smallmask
a = arange(10)
a[1] = masked
a[1] = 1
assert_equal(a._mask, nomask)
a = arange(10)
a._smallmask = False
a[1] = masked
a[1] = 1
assert_equal(a._mask, zeros(10))
def test_shrink_mask(self):
# Tests .shrink_mask()
a = array([1, 2, 3], mask=[0, 0, 0])
b = a.shrink_mask()
assert_equal(a, b)
assert_equal(a.mask, nomask)
def test_flat(self):
# Test that flat can return all types of items [#4585, #4615]
# test simple access
test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
assert_equal(test.flat[1], 2)
assert_equal(test.flat[2], masked)
self.assertTrue(np.all(test.flat[0:2] == test[0, 0:2]))
# Test flat on masked_matrices
test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
test.flat = masked_array([3, 2, 1], mask=[1, 0, 0])
control = masked_array(np.matrix([[3, 2, 1]]), mask=[1, 0, 0])
assert_equal(test, control)
# Test setting
test = masked_array(np.matrix([[1, 2, 3]]), mask=[0, 0, 1])
testflat = test.flat
testflat[:] = testflat[[2, 1, 0]]
assert_equal(test, control)
testflat[0] = 9
assert_equal(test[0, 0], 9)
# test 2-D record array
# ... on structured array w/ masked records
x = array([[(1, 1.1, 'one'), (2, 2.2, 'two'), (3, 3.3, 'thr')],
[(4, 4.4, 'fou'), (5, 5.5, 'fiv'), (6, 6.6, 'six')]],
dtype=[('a', int), ('b', float), ('c', '|S8')])
x['a'][0, 1] = masked
x['b'][1, 0] = masked
x['c'][0, 2] = masked
x[-1, -1] = masked
xflat = x.flat
assert_equal(xflat[0], x[0, 0])
assert_equal(xflat[1], x[0, 1])
assert_equal(xflat[2], x[0, 2])
assert_equal(xflat[:3], x[0])
assert_equal(xflat[3], x[1, 0])
assert_equal(xflat[4], x[1, 1])
assert_equal(xflat[5], x[1, 2])
assert_equal(xflat[3:], x[1])
assert_equal(xflat[-1], x[-1, -1])
i = 0
j = 0
for xf in xflat:
assert_equal(xf, x[j, i])
i += 1
if i >= x.shape[-1]:
i = 0
j += 1
# test that matrices keep the correct shape (#4615)
a = masked_array(np.matrix(np.eye(2)), mask=0)
b = a.flat
b01 = b[:2]
assert_equal(b01.data, array([[1., 0.]]))
assert_equal(b01.mask, array([[False, False]]))
def test_assign_dtype(self):
# check that the mask's dtype is updated when dtype is changed
a = np.zeros(4, dtype='f4,i4')
m = np.ma.array(a)
m.dtype = np.dtype('f4')
repr(m) # raises?
assert_equal(m.dtype, np.dtype('f4'))
# check that dtype changes that change shape of mask too much
# are not allowed
def assign():
m = np.ma.array(a)
m.dtype = np.dtype('f8')
assert_raises(ValueError, assign)
b = a.view(dtype='f4', type=np.ma.MaskedArray) # raises?
assert_equal(b.dtype, np.dtype('f4'))
# check that nomask is preserved
a = np.zeros(4, dtype='f4')
m = np.ma.array(a)
m.dtype = np.dtype('f4,i4')
assert_equal(m.dtype, np.dtype('f4,i4'))
assert_equal(m._mask, np.ma.nomask)
class TestFillingValues(TestCase):
def test_check_on_scalar(self):
# Test _check_fill_value set to valid and invalid values
_check_fill_value = np.ma.core._check_fill_value
fval = _check_fill_value(0, int)
assert_equal(fval, 0)
fval = _check_fill_value(None, int)
assert_equal(fval, default_fill_value(0))
fval = _check_fill_value(0, "|S3")
assert_equal(fval, asbytes("0"))
fval = _check_fill_value(None, "|S3")
assert_equal(fval, default_fill_value(b"camelot!"))
self.assertRaises(TypeError, _check_fill_value, 1e+20, int)
self.assertRaises(TypeError, _check_fill_value, 'stuff', int)
def test_check_on_fields(self):
# Tests _check_fill_value with records
_check_fill_value = np.ma.core._check_fill_value
ndtype = [('a', int), ('b', float), ('c', "|S3")]
# A check on a list should return a single record
fval = _check_fill_value([-999, -12345678.9, "???"], ndtype)
self.assertTrue(isinstance(fval, ndarray))
assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")])
# A check on None should output the defaults
fval = _check_fill_value(None, ndtype)
self.assertTrue(isinstance(fval, ndarray))
assert_equal(fval.item(), [default_fill_value(0),
default_fill_value(0.),
asbytes(default_fill_value("0"))])
#.....Using a structured type as fill_value should work
fill_val = np.array((-999, -12345678.9, "???"), dtype=ndtype)
fval = _check_fill_value(fill_val, ndtype)
self.assertTrue(isinstance(fval, ndarray))
assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")])
#.....Using a flexible type w/ a different type shouldn't matter
# BEHAVIOR in 1.5 and earlier: match structured types by position
#fill_val = np.array((-999, -12345678.9, "???"),
# dtype=[("A", int), ("B", float), ("C", "|S3")])
# BEHAVIOR in 1.6 and later: match structured types by name
fill_val = np.array(("???", -999, -12345678.9),
dtype=[("c", "|S3"), ("a", int), ("b", float), ])
fval = _check_fill_value(fill_val, ndtype)
self.assertTrue(isinstance(fval, ndarray))
assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")])
#.....Using an object-array shouldn't matter either
fill_val = np.ndarray(shape=(1,), dtype=object)
fill_val[0] = (-999, -12345678.9, asbytes("???"))
fval = _check_fill_value(fill_val, object)
self.assertTrue(isinstance(fval, ndarray))
assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")])
# NOTE: This test was never run properly as "fill_value" rather than
# "fill_val" was assigned. Written properly, it fails.
#fill_val = np.array((-999, -12345678.9, "???"))
#fval = _check_fill_value(fill_val, ndtype)
#self.assertTrue(isinstance(fval, ndarray))
#assert_equal(fval.item(), [-999, -12345678.9, asbytes("???")])
#.....One-field-only flexible type should work as well
ndtype = [("a", int)]
fval = _check_fill_value(-999999999, ndtype)
self.assertTrue(isinstance(fval, ndarray))
assert_equal(fval.item(), (-999999999,))
def test_fillvalue_conversion(self):
# Tests the behavior of fill_value during conversion
# We had a tailored comment to make sure special attributes are
# properly dealt with
a = array(asbytes_nested(['3', '4', '5']))
a._optinfo.update({'comment':"updated!"})
b = array(a, dtype=int)
assert_equal(b._data, [3, 4, 5])
assert_equal(b.fill_value, default_fill_value(0))
b = array(a, dtype=float)
assert_equal(b._data, [3, 4, 5])
assert_equal(b.fill_value, default_fill_value(0.))
b = a.astype(int)
assert_equal(b._data, [3, 4, 5])
assert_equal(b.fill_value, default_fill_value(0))
assert_equal(b._optinfo['comment'], "updated!")
b = a.astype([('a', '|S3')])
assert_equal(b['a']._data, a._data)
assert_equal(b['a'].fill_value, a.fill_value)
def test_fillvalue(self):
# Yet more fun with the fill_value
data = masked_array([1, 2, 3], fill_value=-999)
series = data[[0, 2, 1]]
assert_equal(series._fill_value, data._fill_value)
mtype = [('f', float), ('s', '|S3')]
x = array([(1, 'a'), (2, 'b'), (pi, 'pi')], dtype=mtype)
x.fill_value = 999
assert_equal(x.fill_value.item(), [999., asbytes('999')])
assert_equal(x['f'].fill_value, 999)
assert_equal(x['s'].fill_value, asbytes('999'))
x.fill_value = (9, '???')
assert_equal(x.fill_value.item(), (9, asbytes('???')))
assert_equal(x['f'].fill_value, 9)
assert_equal(x['s'].fill_value, asbytes('???'))
x = array([1, 2, 3.1])
x.fill_value = 999
assert_equal(np.asarray(x.fill_value).dtype, float)
assert_equal(x.fill_value, 999.)
assert_equal(x._fill_value, np.array(999.))
def test_fillvalue_exotic_dtype(self):
# Tests yet more exotic flexible dtypes
_check_fill_value = np.ma.core._check_fill_value
ndtype = [('i', int), ('s', '|S8'), ('f', float)]
control = np.array((default_fill_value(0),
default_fill_value('0'),
default_fill_value(0.),),
dtype=ndtype)
assert_equal(_check_fill_value(None, ndtype), control)
# The shape shouldn't matter
ndtype = [('f0', float, (2, 2))]
control = np.array((default_fill_value(0.),),
dtype=[('f0', float)]).astype(ndtype)
assert_equal(_check_fill_value(None, ndtype), control)
control = np.array((0,), dtype=[('f0', float)]).astype(ndtype)
assert_equal(_check_fill_value(0, ndtype), control)
ndtype = np.dtype("int, (2,3)float, float")
control = np.array((default_fill_value(0),
default_fill_value(0.),
default_fill_value(0.),),
dtype="int, float, float").astype(ndtype)
test = _check_fill_value(None, ndtype)
assert_equal(test, control)
control = np.array((0, 0, 0), dtype="int, float, float").astype(ndtype)
assert_equal(_check_fill_value(0, ndtype), control)
# but when indexing, fill value should become scalar not tuple
# See issue #6723
M = masked_array(control)
assert_equal(M["f1"].fill_value.ndim, 0)
def test_fillvalue_datetime_timedelta(self):
# Test default fillvalue for datetime64 and timedelta64 types.
# See issue #4476, this would return '?' which would cause errors
# elsewhere
for timecode in ("as", "fs", "ps", "ns", "us", "ms", "s", "m",
"h", "D", "W", "M", "Y"):
control = numpy.datetime64("NaT", timecode)
test = default_fill_value(numpy.dtype("<M8[" + timecode + "]"))
assert_equal(test, control)
control = numpy.timedelta64("NaT", timecode)
test = default_fill_value(numpy.dtype("<m8[" + timecode + "]"))
assert_equal(test, control)
def test_extremum_fill_value(self):
# Tests extremum fill values for flexible type.
a = array([(1, (2, 3)), (4, (5, 6))],
dtype=[('A', int), ('B', [('BA', int), ('BB', int)])])
test = a.fill_value
assert_equal(test['A'], default_fill_value(a['A']))
assert_equal(test['B']['BA'], default_fill_value(a['B']['BA']))
assert_equal(test['B']['BB'], default_fill_value(a['B']['BB']))
test = minimum_fill_value(a)
assert_equal(test[0], minimum_fill_value(a['A']))
assert_equal(test[1][0], minimum_fill_value(a['B']['BA']))
assert_equal(test[1][1], minimum_fill_value(a['B']['BB']))
assert_equal(test[1], minimum_fill_value(a['B']))
test = maximum_fill_value(a)
assert_equal(test[0], maximum_fill_value(a['A']))
assert_equal(test[1][0], maximum_fill_value(a['B']['BA']))
assert_equal(test[1][1], maximum_fill_value(a['B']['BB']))
assert_equal(test[1], maximum_fill_value(a['B']))
def test_fillvalue_individual_fields(self):
# Test setting fill_value on individual fields
ndtype = [('a', int), ('b', int)]
# Explicit fill_value
a = array(list(zip([1, 2, 3], [4, 5, 6])),
fill_value=(-999, -999), dtype=ndtype)
aa = a['a']
aa.set_fill_value(10)
assert_equal(aa._fill_value, np.array(10))
assert_equal(tuple(a.fill_value), (10, -999))
a.fill_value['b'] = -10
assert_equal(tuple(a.fill_value), (10, -10))
# Implicit fill_value
t = array(list(zip([1, 2, 3], [4, 5, 6])), dtype=ndtype)
tt = t['a']
tt.set_fill_value(10)
assert_equal(tt._fill_value, np.array(10))
assert_equal(tuple(t.fill_value), (10, default_fill_value(0)))
def test_fillvalue_implicit_structured_array(self):
# Check that fill_value is always defined for structured arrays
ndtype = ('b', float)
adtype = ('a', float)
a = array([(1.,), (2.,)], mask=[(False,), (False,)],
fill_value=(np.nan,), dtype=np.dtype([adtype]))
b = empty(a.shape, dtype=[adtype, ndtype])
b['a'] = a['a']
b['a'].set_fill_value(a['a'].fill_value)
f = b._fill_value[()]
assert_(np.isnan(f[0]))
assert_equal(f[-1], default_fill_value(1.))
def test_fillvalue_as_arguments(self):
# Test adding a fill_value parameter to empty/ones/zeros
a = empty(3, fill_value=999.)
assert_equal(a.fill_value, 999.)
a = ones(3, fill_value=999., dtype=float)
assert_equal(a.fill_value, 999.)
a = zeros(3, fill_value=0., dtype=complex)
assert_equal(a.fill_value, 0.)
a = identity(3, fill_value=0., dtype=complex)
assert_equal(a.fill_value, 0.)
def test_shape_argument(self):
# Test that shape can be provides as an argument
# GH issue 6106
a = empty(shape=(3, ))
assert_equal(a.shape, (3, ))
a = ones(shape=(3, ), dtype=float)
assert_equal(a.shape, (3, ))
a = zeros(shape=(3, ), dtype=complex)
assert_equal(a.shape, (3, ))
def test_fillvalue_in_view(self):
# Test the behavior of fill_value in view
# Create initial masked array
x = array([1, 2, 3], fill_value=1, dtype=np.int64)
# Check that fill_value is preserved by default
y = x.view()
assert_(y.fill_value == 1)
# Check that fill_value is preserved if dtype is specified and the
# dtype is an ndarray sub-class and has a _fill_value attribute
y = x.view(MaskedArray)
assert_(y.fill_value == 1)
# Check that fill_value is preserved if type is specified and the
# dtype is an ndarray sub-class and has a _fill_value attribute (by
# default, the first argument is dtype, not type)
y = x.view(type=MaskedArray)
assert_(y.fill_value == 1)
# Check that code does not crash if passed an ndarray sub-class that
# does not have a _fill_value attribute
y = x.view(np.ndarray)
y = x.view(type=np.ndarray)
# Check that fill_value can be overridden with view
y = x.view(MaskedArray, fill_value=2)
assert_(y.fill_value == 2)
# Check that fill_value can be overridden with view (using type=)
y = x.view(type=MaskedArray, fill_value=2)
assert_(y.fill_value == 2)
# Check that fill_value gets reset if passed a dtype but not a
# fill_value. This is because even though in some cases one can safely
# cast the fill_value, e.g. if taking an int64 view of an int32 array,
# in other cases, this cannot be done (e.g. int32 view of an int64
# array with a large fill_value).
y = x.view(dtype=np.int32)
assert_(y.fill_value == 999999)
def test_fillvalue_bytes_or_str(self):
# Test whether fill values work as expected for structured dtypes
# containing bytes or str. See issue #7259.
a = empty(shape=(3, ), dtype="(2)3S,(2)3U")
assert_equal(a["f0"].fill_value, default_fill_value(b"spam"))
assert_equal(a["f1"].fill_value, default_fill_value("eggs"))
class TestUfuncs(TestCase):
# Test class for the application of ufuncs on MaskedArrays.
def setUp(self):
# Base data definition.
self.d = (array([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6),
array([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6),)
self.err_status = np.geterr()
np.seterr(divide='ignore', invalid='ignore')
def tearDown(self):
np.seterr(**self.err_status)
def test_testUfuncRegression(self):
# Tests new ufuncs on MaskedArrays.
for f in ['sqrt', 'log', 'log10', 'exp', 'conjugate',
'sin', 'cos', 'tan',
'arcsin', 'arccos', 'arctan',
'sinh', 'cosh', 'tanh',
'arcsinh',
'arccosh',
'arctanh',
'absolute', 'fabs', 'negative',
'floor', 'ceil',
'logical_not',
'add', 'subtract', 'multiply',
'divide', 'true_divide', 'floor_divide',
'remainder', 'fmod', 'hypot', 'arctan2',
'equal', 'not_equal', 'less_equal', 'greater_equal',
'less', 'greater',
'logical_and', 'logical_or', 'logical_xor',
]:
try:
uf = getattr(umath, f)
except AttributeError:
uf = getattr(fromnumeric, f)
mf = getattr(numpy.ma.core, f)
args = self.d[:uf.nin]
ur = uf(*args)
mr = mf(*args)
assert_equal(ur.filled(0), mr.filled(0), f)
assert_mask_equal(ur.mask, mr.mask, err_msg=f)
def test_reduce(self):
# Tests reduce on MaskedArrays.
a = self.d[0]
self.assertTrue(not alltrue(a, axis=0))
self.assertTrue(sometrue(a, axis=0))
assert_equal(sum(a[:3], axis=0), 0)
assert_equal(product(a, axis=0), 0)
assert_equal(add.reduce(a), pi)
def test_minmax(self):
# Tests extrema on MaskedArrays.
a = arange(1, 13).reshape(3, 4)
amask = masked_where(a < 5, a)
assert_equal(amask.max(), a.max())
assert_equal(amask.min(), 5)
assert_equal(amask.max(0), a.max(0))
assert_equal(amask.min(0), [5, 6, 7, 8])
self.assertTrue(amask.max(1)[0].mask)
self.assertTrue(amask.min(1)[0].mask)
def test_ndarray_mask(self):
# Check that the mask of the result is a ndarray (not a MaskedArray...)
a = masked_array([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1])
test = np.sqrt(a)
control = masked_array([-1, 0, 1, np.sqrt(2), -1],
mask=[1, 0, 0, 0, 1])
assert_equal(test, control)
assert_equal(test.mask, control.mask)
self.assertTrue(not isinstance(test.mask, MaskedArray))
def test_treatment_of_NotImplemented(self):
# Check that NotImplemented is returned at appropriate places
a = masked_array([1., 2.], mask=[1, 0])
self.assertRaises(TypeError, operator.mul, a, "abc")
self.assertRaises(TypeError, operator.truediv, a, "abc")
class MyClass(object):
__array_priority__ = a.__array_priority__ + 1
def __mul__(self, other):
return "My mul"
def __rmul__(self, other):
return "My rmul"
me = MyClass()
assert_(me * a == "My mul")
assert_(a * me == "My rmul")
# and that __array_priority__ is respected
class MyClass2(object):
__array_priority__ = 100
def __mul__(self, other):
return "Me2mul"
def __rmul__(self, other):
return "Me2rmul"
def __rdiv__(self, other):
return "Me2rdiv"
__rtruediv__ = __rdiv__
me_too = MyClass2()
assert_(a.__mul__(me_too) is NotImplemented)
assert_(all(multiply.outer(a, me_too) == "Me2rmul"))
assert_(a.__truediv__(me_too) is NotImplemented)
assert_(me_too * a == "Me2mul")
assert_(a * me_too == "Me2rmul")
assert_(a / me_too == "Me2rdiv")
def test_no_masked_nan_warnings(self):
# check that a nan in masked position does not
# cause ufunc warnings
m = np.ma.array([0.5, np.nan], mask=[0,1])
with warnings.catch_warnings():
warnings.filterwarnings("error")
# test unary and binary ufuncs
exp(m)
add(m, 1)
m > 0
# test different unary domains
sqrt(m)
log(m)
tan(m)
arcsin(m)
arccos(m)
arccosh(m)
# test binary domains
divide(m, 2)
# also check that allclose uses ma ufuncs, to avoid warning
allclose(m, 0.5)
class TestMaskedArrayInPlaceArithmetics(TestCase):
# Test MaskedArray Arithmetics
def setUp(self):
x = arange(10)
y = arange(10)
xm = arange(10)
xm[2] = masked
self.intdata = (x, y, xm)
self.floatdata = (x.astype(float), y.astype(float), xm.astype(float))
self.othertypes = np.typecodes['AllInteger'] + np.typecodes['AllFloat']
self.othertypes = [np.dtype(_).type for _ in self.othertypes]
self.uint8data = (
x.astype(np.uint8),
y.astype(np.uint8),
xm.astype(np.uint8)
)
def test_inplace_addition_scalar(self):
# Test of inplace additions
(x, y, xm) = self.intdata
xm[2] = masked
x += 1
assert_equal(x, y + 1)
xm += 1
assert_equal(xm, y + 1)
(x, _, xm) = self.floatdata
id1 = x.data.ctypes._data
x += 1.
assert_(id1 == x.data.ctypes._data)
assert_equal(x, y + 1.)
def test_inplace_addition_array(self):
# Test of inplace additions
(x, y, xm) = self.intdata
m = xm.mask
a = arange(10, dtype=np.int16)
a[-1] = masked
x += a
xm += a
assert_equal(x, y + a)
assert_equal(xm, y + a)
assert_equal(xm.mask, mask_or(m, a.mask))
def test_inplace_subtraction_scalar(self):
# Test of inplace subtractions
(x, y, xm) = self.intdata
x -= 1
assert_equal(x, y - 1)
xm -= 1
assert_equal(xm, y - 1)
def test_inplace_subtraction_array(self):
# Test of inplace subtractions
(x, y, xm) = self.floatdata
m = xm.mask
a = arange(10, dtype=float)
a[-1] = masked
x -= a
xm -= a
assert_equal(x, y - a)
assert_equal(xm, y - a)
assert_equal(xm.mask, mask_or(m, a.mask))
def test_inplace_multiplication_scalar(self):
# Test of inplace multiplication
(x, y, xm) = self.floatdata
x *= 2.0
assert_equal(x, y * 2)
xm *= 2.0
assert_equal(xm, y * 2)
def test_inplace_multiplication_array(self):
# Test of inplace multiplication
(x, y, xm) = self.floatdata
m = xm.mask
a = arange(10, dtype=float)
a[-1] = masked
x *= a
xm *= a
assert_equal(x, y * a)
assert_equal(xm, y * a)
assert_equal(xm.mask, mask_or(m, a.mask))
def test_inplace_division_scalar_int(self):
# Test of inplace division
(x, y, xm) = self.intdata
x = arange(10) * 2
xm = arange(10) * 2
xm[2] = masked
x //= 2
assert_equal(x, y)
xm //= 2
assert_equal(xm, y)
def test_inplace_division_scalar_float(self):
# Test of inplace division
(x, y, xm) = self.floatdata
x /= 2.0
assert_equal(x, y / 2.0)
xm /= arange(10)
assert_equal(xm, ones((10,)))
def test_inplace_division_array_float(self):
# Test of inplace division
(x, y, xm) = self.floatdata
m = xm.mask
a = arange(10, dtype=float)
a[-1] = masked
x /= a
xm /= a
assert_equal(x, y / a)
assert_equal(xm, y / a)
assert_equal(xm.mask, mask_or(mask_or(m, a.mask), (a == 0)))
def test_inplace_division_misc(self):
x = [1., 1., 1., -2., pi / 2., 4., 5., -10., 10., 1., 2., 3.]
y = [5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.]
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
xm = masked_array(x, mask=m1)
ym = masked_array(y, mask=m2)
z = xm / ym
assert_equal(z._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1])
assert_equal(z._data,
[1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.])
xm = xm.copy()
xm /= ym
assert_equal(xm._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1])
assert_equal(z._data,
[1., 1., 1., -1., -pi / 2., 4., 5., 1., 1., 1., 2., 3.])
def test_datafriendly_add(self):
# Test keeping data w/ (inplace) addition
x = array([1, 2, 3], mask=[0, 0, 1])
# Test add w/ scalar
xx = x + 1
assert_equal(xx.data, [2, 3, 3])
assert_equal(xx.mask, [0, 0, 1])
# Test iadd w/ scalar
x += 1
assert_equal(x.data, [2, 3, 3])
assert_equal(x.mask, [0, 0, 1])
# Test add w/ array
x = array([1, 2, 3], mask=[0, 0, 1])
xx = x + array([1, 2, 3], mask=[1, 0, 0])
assert_equal(xx.data, [1, 4, 3])
assert_equal(xx.mask, [1, 0, 1])
# Test iadd w/ array
x = array([1, 2, 3], mask=[0, 0, 1])
x += array([1, 2, 3], mask=[1, 0, 0])
assert_equal(x.data, [1, 4, 3])
assert_equal(x.mask, [1, 0, 1])
def test_datafriendly_sub(self):
# Test keeping data w/ (inplace) subtraction
# Test sub w/ scalar
x = array([1, 2, 3], mask=[0, 0, 1])
xx = x - 1
assert_equal(xx.data, [0, 1, 3])
assert_equal(xx.mask, [0, 0, 1])
# Test isub w/ scalar
x = array([1, 2, 3], mask=[0, 0, 1])
x -= 1
assert_equal(x.data, [0, 1, 3])
assert_equal(x.mask, [0, 0, 1])
# Test sub w/ array
x = array([1, 2, 3], mask=[0, 0, 1])
xx = x - array([1, 2, 3], mask=[1, 0, 0])
assert_equal(xx.data, [1, 0, 3])
assert_equal(xx.mask, [1, 0, 1])
# Test isub w/ array
x = array([1, 2, 3], mask=[0, 0, 1])
x -= array([1, 2, 3], mask=[1, 0, 0])
assert_equal(x.data, [1, 0, 3])
assert_equal(x.mask, [1, 0, 1])
def test_datafriendly_mul(self):
# Test keeping data w/ (inplace) multiplication
# Test mul w/ scalar
x = array([1, 2, 3], mask=[0, 0, 1])
xx = x * 2
assert_equal(xx.data, [2, 4, 3])
assert_equal(xx.mask, [0, 0, 1])
# Test imul w/ scalar
x = array([1, 2, 3], mask=[0, 0, 1])
x *= 2
assert_equal(x.data, [2, 4, 3])
assert_equal(x.mask, [0, 0, 1])
# Test mul w/ array
x = array([1, 2, 3], mask=[0, 0, 1])
xx = x * array([10, 20, 30], mask=[1, 0, 0])
assert_equal(xx.data, [1, 40, 3])
assert_equal(xx.mask, [1, 0, 1])
# Test imul w/ array
x = array([1, 2, 3], mask=[0, 0, 1])
x *= array([10, 20, 30], mask=[1, 0, 0])
assert_equal(x.data, [1, 40, 3])
assert_equal(x.mask, [1, 0, 1])
def test_datafriendly_div(self):
# Test keeping data w/ (inplace) division
# Test div on scalar
x = array([1, 2, 3], mask=[0, 0, 1])
xx = x / 2.
assert_equal(xx.data, [1 / 2., 2 / 2., 3])
assert_equal(xx.mask, [0, 0, 1])
# Test idiv on scalar
x = array([1., 2., 3.], mask=[0, 0, 1])
x /= 2.
assert_equal(x.data, [1 / 2., 2 / 2., 3])
assert_equal(x.mask, [0, 0, 1])
# Test div on array
x = array([1., 2., 3.], mask=[0, 0, 1])
xx = x / array([10., 20., 30.], mask=[1, 0, 0])
assert_equal(xx.data, [1., 2. / 20., 3.])
assert_equal(xx.mask, [1, 0, 1])
# Test idiv on array
x = array([1., 2., 3.], mask=[0, 0, 1])
x /= array([10., 20., 30.], mask=[1, 0, 0])
assert_equal(x.data, [1., 2 / 20., 3.])
assert_equal(x.mask, [1, 0, 1])
def test_datafriendly_pow(self):
# Test keeping data w/ (inplace) power
# Test pow on scalar
x = array([1., 2., 3.], mask=[0, 0, 1])
xx = x ** 2.5
assert_equal(xx.data, [1., 2. ** 2.5, 3.])
assert_equal(xx.mask, [0, 0, 1])
# Test ipow on scalar
x **= 2.5
assert_equal(x.data, [1., 2. ** 2.5, 3])
assert_equal(x.mask, [0, 0, 1])
def test_datafriendly_add_arrays(self):
a = array([[1, 1], [3, 3]])
b = array([1, 1], mask=[0, 0])
a += b
assert_equal(a, [[2, 2], [4, 4]])
if a.mask is not nomask:
assert_equal(a.mask, [[0, 0], [0, 0]])
a = array([[1, 1], [3, 3]])
b = array([1, 1], mask=[0, 1])
a += b
assert_equal(a, [[2, 2], [4, 4]])
assert_equal(a.mask, [[0, 1], [0, 1]])
def test_datafriendly_sub_arrays(self):
a = array([[1, 1], [3, 3]])
b = array([1, 1], mask=[0, 0])
a -= b
assert_equal(a, [[0, 0], [2, 2]])
if a.mask is not nomask:
assert_equal(a.mask, [[0, 0], [0, 0]])
a = array([[1, 1], [3, 3]])
b = array([1, 1], mask=[0, 1])
a -= b
assert_equal(a, [[0, 0], [2, 2]])
assert_equal(a.mask, [[0, 1], [0, 1]])
def test_datafriendly_mul_arrays(self):
a = array([[1, 1], [3, 3]])
b = array([1, 1], mask=[0, 0])
a *= b
assert_equal(a, [[1, 1], [3, 3]])
if a.mask is not nomask:
assert_equal(a.mask, [[0, 0], [0, 0]])
a = array([[1, 1], [3, 3]])
b = array([1, 1], mask=[0, 1])
a *= b
assert_equal(a, [[1, 1], [3, 3]])
assert_equal(a.mask, [[0, 1], [0, 1]])
def test_inplace_addition_scalar_type(self):
# Test of inplace additions
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
xm[2] = masked
x += t(1)
assert_equal(x, y + t(1))
xm += t(1)
assert_equal(xm, y + t(1))
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_addition_array_type(self):
# Test of inplace additions
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
m = xm.mask
a = arange(10, dtype=t)
a[-1] = masked
x += a
xm += a
assert_equal(x, y + a)
assert_equal(xm, y + a)
assert_equal(xm.mask, mask_or(m, a.mask))
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_subtraction_scalar_type(self):
# Test of inplace subtractions
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
x -= t(1)
assert_equal(x, y - t(1))
xm -= t(1)
assert_equal(xm, y - t(1))
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_subtraction_array_type(self):
# Test of inplace subtractions
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
m = xm.mask
a = arange(10, dtype=t)
a[-1] = masked
x -= a
xm -= a
assert_equal(x, y - a)
assert_equal(xm, y - a)
assert_equal(xm.mask, mask_or(m, a.mask))
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_multiplication_scalar_type(self):
# Test of inplace multiplication
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
x *= t(2)
assert_equal(x, y * t(2))
xm *= t(2)
assert_equal(xm, y * t(2))
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_multiplication_array_type(self):
# Test of inplace multiplication
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
m = xm.mask
a = arange(10, dtype=t)
a[-1] = masked
x *= a
xm *= a
assert_equal(x, y * a)
assert_equal(xm, y * a)
assert_equal(xm.mask, mask_or(m, a.mask))
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_floor_division_scalar_type(self):
# Test of inplace division
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
x = arange(10, dtype=t) * t(2)
xm = arange(10, dtype=t) * t(2)
xm[2] = masked
x //= t(2)
xm //= t(2)
assert_equal(x, y)
assert_equal(xm, y)
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_floor_division_array_type(self):
# Test of inplace division
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
m = xm.mask
a = arange(10, dtype=t)
a[-1] = masked
x //= a
xm //= a
assert_equal(x, y // a)
assert_equal(xm, y // a)
assert_equal(
xm.mask,
mask_or(mask_or(m, a.mask), (a == t(0)))
)
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_division_scalar_type(self):
# Test of inplace division
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
x = arange(10, dtype=t) * t(2)
xm = arange(10, dtype=t) * t(2)
xm[2] = masked
# May get a DeprecationWarning or a TypeError.
#
# This is a consequence of the fact that this is true divide
# and will require casting to float for calculation and
# casting back to the original type. This will only be raised
# with integers. Whether it is an error or warning is only
# dependent on how stringent the casting rules are.
#
# Will handle the same way.
try:
x /= t(2)
assert_equal(x, y)
except (DeprecationWarning, TypeError) as e:
warnings.warn(str(e))
try:
xm /= t(2)
assert_equal(xm, y)
except (DeprecationWarning, TypeError) as e:
warnings.warn(str(e))
if issubclass(t, np.integer):
assert_equal(len(w), 2, "Failed on type=%s." % t)
else:
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_division_array_type(self):
# Test of inplace division
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
(x, y, xm) = (_.astype(t) for _ in self.uint8data)
m = xm.mask
a = arange(10, dtype=t)
a[-1] = masked
# May get a DeprecationWarning or a TypeError.
#
# This is a consequence of the fact that this is true divide
# and will require casting to float for calculation and
# casting back to the original type. This will only be raised
# with integers. Whether it is an error or warning is only
# dependent on how stringent the casting rules are.
#
# Will handle the same way.
try:
x /= a
assert_equal(x, y / a)
except (DeprecationWarning, TypeError) as e:
warnings.warn(str(e))
try:
xm /= a
assert_equal(xm, y / a)
assert_equal(
xm.mask,
mask_or(mask_or(m, a.mask), (a == t(0)))
)
except (DeprecationWarning, TypeError) as e:
warnings.warn(str(e))
if issubclass(t, np.integer):
assert_equal(len(w), 2, "Failed on type=%s." % t)
else:
assert_equal(len(w), 0, "Failed on type=%s." % t)
def test_inplace_pow_type(self):
# Test keeping data w/ (inplace) power
for t in self.othertypes:
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings("always")
# Test pow on scalar
x = array([1, 2, 3], mask=[0, 0, 1], dtype=t)
xx = x ** t(2)
xx_r = array([1, 2 ** 2, 3], mask=[0, 0, 1], dtype=t)
assert_equal(xx.data, xx_r.data)
assert_equal(xx.mask, xx_r.mask)
# Test ipow on scalar
x **= t(2)
assert_equal(x.data, xx_r.data)
assert_equal(x.mask, xx_r.mask)
assert_equal(len(w), 0, "Failed on type=%s." % t)
class TestMaskedArrayMethods(TestCase):
# Test class for miscellaneous MaskedArrays methods.
def setUp(self):
# Base data definition.
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
X = x.reshape(6, 6)
XX = x.reshape(3, 2, 2, 3)
m = np.array([0, 1, 0, 1, 0, 0,
1, 0, 1, 1, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, 1, 1, 1,
1, 0, 0, 1, 0, 0,
0, 0, 1, 0, 1, 0])
mx = array(data=x, mask=m)
mX = array(data=X, mask=m.reshape(X.shape))
mXX = array(data=XX, mask=m.reshape(XX.shape))
m2 = np.array([1, 1, 0, 1, 0, 0,
1, 1, 1, 1, 0, 1,
0, 0, 1, 1, 0, 1,
0, 0, 0, 1, 1, 1,
1, 0, 0, 1, 1, 0,
0, 0, 1, 0, 1, 1])
m2x = array(data=x, mask=m2)
m2X = array(data=X, mask=m2.reshape(X.shape))
m2XX = array(data=XX, mask=m2.reshape(XX.shape))
self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
def test_generic_methods(self):
# Tests some MaskedArray methods.
a = array([1, 3, 2])
assert_equal(a.any(), a._data.any())
assert_equal(a.all(), a._data.all())
assert_equal(a.argmax(), a._data.argmax())
assert_equal(a.argmin(), a._data.argmin())
assert_equal(a.choose(0, 1, 2, 3, 4), a._data.choose(0, 1, 2, 3, 4))
assert_equal(a.compress([1, 0, 1]), a._data.compress([1, 0, 1]))
assert_equal(a.conj(), a._data.conj())
assert_equal(a.conjugate(), a._data.conjugate())
m = array([[1, 2], [3, 4]])
assert_equal(m.diagonal(), m._data.diagonal())
assert_equal(a.sum(), a._data.sum())
assert_equal(a.take([1, 2]), a._data.take([1, 2]))
assert_equal(m.transpose(), m._data.transpose())
def test_allclose(self):
# Tests allclose on arrays
a = np.random.rand(10)
b = a + np.random.rand(10) * 1e-8
self.assertTrue(allclose(a, b))
# Test allclose w/ infs
a[0] = np.inf
self.assertTrue(not allclose(a, b))
b[0] = np.inf
self.assertTrue(allclose(a, b))
# Test allclose w/ masked
a = masked_array(a)
a[-1] = masked
self.assertTrue(allclose(a, b, masked_equal=True))
self.assertTrue(not allclose(a, b, masked_equal=False))
# Test comparison w/ scalar
a *= 1e-8
a[0] = 0
self.assertTrue(allclose(a, 0, masked_equal=True))
# Test that the function works for MIN_INT integer typed arrays
a = masked_array([np.iinfo(np.int_).min], dtype=np.int_)
self.assertTrue(allclose(a, a))
def test_allany(self):
# Checks the any/all methods/functions.
x = np.array([[0.13, 0.26, 0.90],
[0.28, 0.33, 0.63],
[0.31, 0.87, 0.70]])
m = np.array([[True, False, False],
[False, False, False],
[True, True, False]], dtype=np.bool_)
mx = masked_array(x, mask=m)
mxbig = (mx > 0.5)
mxsmall = (mx < 0.5)
self.assertFalse(mxbig.all())
self.assertTrue(mxbig.any())
assert_equal(mxbig.all(0), [False, False, True])
assert_equal(mxbig.all(1), [False, False, True])
assert_equal(mxbig.any(0), [False, False, True])
assert_equal(mxbig.any(1), [True, True, True])
self.assertFalse(mxsmall.all())
self.assertTrue(mxsmall.any())
assert_equal(mxsmall.all(0), [True, True, False])
assert_equal(mxsmall.all(1), [False, False, False])
assert_equal(mxsmall.any(0), [True, True, False])
assert_equal(mxsmall.any(1), [True, True, False])
def test_allany_onmatrices(self):
x = np.array([[0.13, 0.26, 0.90],
[0.28, 0.33, 0.63],
[0.31, 0.87, 0.70]])
X = np.matrix(x)
m = np.array([[True, False, False],
[False, False, False],
[True, True, False]], dtype=np.bool_)
mX = masked_array(X, mask=m)
mXbig = (mX > 0.5)
mXsmall = (mX < 0.5)
self.assertFalse(mXbig.all())
self.assertTrue(mXbig.any())
assert_equal(mXbig.all(0), np.matrix([False, False, True]))
assert_equal(mXbig.all(1), np.matrix([False, False, True]).T)
assert_equal(mXbig.any(0), np.matrix([False, False, True]))
assert_equal(mXbig.any(1), np.matrix([True, True, True]).T)
self.assertFalse(mXsmall.all())
self.assertTrue(mXsmall.any())
assert_equal(mXsmall.all(0), np.matrix([True, True, False]))
assert_equal(mXsmall.all(1), np.matrix([False, False, False]).T)
assert_equal(mXsmall.any(0), np.matrix([True, True, False]))
assert_equal(mXsmall.any(1), np.matrix([True, True, False]).T)
def test_allany_oddities(self):
# Some fun with all and any
store = empty((), dtype=bool)
full = array([1, 2, 3], mask=True)
self.assertTrue(full.all() is masked)
full.all(out=store)
self.assertTrue(store)
self.assertTrue(store._mask, True)
self.assertTrue(store is not masked)
store = empty((), dtype=bool)
self.assertTrue(full.any() is masked)
full.any(out=store)
self.assertTrue(not store)
self.assertTrue(store._mask, True)
self.assertTrue(store is not masked)
def test_argmax_argmin(self):
# Tests argmin & argmax on MaskedArrays.
(x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
assert_equal(mx.argmin(), 35)
assert_equal(mX.argmin(), 35)
assert_equal(m2x.argmin(), 4)
assert_equal(m2X.argmin(), 4)
assert_equal(mx.argmax(), 28)
assert_equal(mX.argmax(), 28)
assert_equal(m2x.argmax(), 31)
assert_equal(m2X.argmax(), 31)
assert_equal(mX.argmin(0), [2, 2, 2, 5, 0, 5])
assert_equal(m2X.argmin(0), [2, 2, 4, 5, 0, 4])
assert_equal(mX.argmax(0), [0, 5, 0, 5, 4, 0])
assert_equal(m2X.argmax(0), [5, 5, 0, 5, 1, 0])
assert_equal(mX.argmin(1), [4, 1, 0, 0, 5, 5, ])
assert_equal(m2X.argmin(1), [4, 4, 0, 0, 5, 3])
assert_equal(mX.argmax(1), [2, 4, 1, 1, 4, 1])
assert_equal(m2X.argmax(1), [2, 4, 1, 1, 1, 1])
def test_clip(self):
# Tests clip on MaskedArrays.
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
m = np.array([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1,
0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1,
1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0])
mx = array(x, mask=m)
clipped = mx.clip(2, 8)
assert_equal(clipped.mask, mx.mask)
assert_equal(clipped._data, x.clip(2, 8))
assert_equal(clipped._data, mx._data.clip(2, 8))
def test_compress(self):
# test compress
a = masked_array([1., 2., 3., 4., 5.], fill_value=9999)
condition = (a > 1.5) & (a < 3.5)
assert_equal(a.compress(condition), [2., 3.])
a[[2, 3]] = masked
b = a.compress(condition)
assert_equal(b._data, [2., 3.])
assert_equal(b._mask, [0, 1])
assert_equal(b.fill_value, 9999)
assert_equal(b, a[condition])
condition = (a < 4.)
b = a.compress(condition)
assert_equal(b._data, [1., 2., 3.])
assert_equal(b._mask, [0, 0, 1])
assert_equal(b.fill_value, 9999)
assert_equal(b, a[condition])
a = masked_array([[10, 20, 30], [40, 50, 60]],
mask=[[0, 0, 1], [1, 0, 0]])
b = a.compress(a.ravel() >= 22)
assert_equal(b._data, [30, 40, 50, 60])
assert_equal(b._mask, [1, 1, 0, 0])
x = np.array([3, 1, 2])
b = a.compress(x >= 2, axis=1)
assert_equal(b._data, [[10, 30], [40, 60]])
assert_equal(b._mask, [[0, 1], [1, 0]])
def test_compressed(self):
# Tests compressed
a = array([1, 2, 3, 4], mask=[0, 0, 0, 0])
b = a.compressed()
assert_equal(b, a)
a[0] = masked
b = a.compressed()
assert_equal(b, [2, 3, 4])
a = array(np.matrix([1, 2, 3, 4]), mask=[0, 0, 0, 0])
b = a.compressed()
assert_equal(b, a)
self.assertTrue(isinstance(b, np.matrix))
a[0, 0] = masked
b = a.compressed()
assert_equal(b, [[2, 3, 4]])
def test_empty(self):
# Tests empty/like
datatype = [('a', int), ('b', float), ('c', '|S8')]
a = masked_array([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')],
dtype=datatype)
assert_equal(len(a.fill_value.item()), len(datatype))
b = empty_like(a)
assert_equal(b.shape, a.shape)
assert_equal(b.fill_value, a.fill_value)
b = empty(len(a), dtype=datatype)
assert_equal(b.shape, a.shape)
assert_equal(b.fill_value, a.fill_value)
# check empty_like mask handling
a = masked_array([1, 2, 3], mask=[False, True, False])
b = empty_like(a)
assert_(not np.may_share_memory(a.mask, b.mask))
b = a.view(masked_array)
assert_(np.may_share_memory(a.mask, b.mask))
def test_put(self):
# Tests put.
d = arange(5)
n = [0, 0, 0, 1, 1]
m = make_mask(n)
x = array(d, mask=m)
self.assertTrue(x[3] is masked)
self.assertTrue(x[4] is masked)
x[[1, 4]] = [10, 40]
self.assertTrue(x[3] is masked)
self.assertTrue(x[4] is not masked)
assert_equal(x, [0, 10, 2, -1, 40])
x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2)
i = [0, 2, 4, 6]
x.put(i, [6, 4, 2, 0])
assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ]))
assert_equal(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])
x.put(i, masked_array([0, 2, 4, 6], [1, 0, 1, 0]))
assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ])
assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0])
x = masked_array(arange(10), mask=[1, 0, 0, 0, 0] * 2)
put(x, i, [6, 4, 2, 0])
assert_equal(x, asarray([6, 1, 4, 3, 2, 5, 0, 7, 8, 9, ]))
assert_equal(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])
put(x, i, masked_array([0, 2, 4, 6], [1, 0, 1, 0]))
assert_array_equal(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, ])
assert_equal(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0])
def test_put_nomask(self):
# GitHub issue 6425
x = zeros(10)
z = array([3., -1.], mask=[False, True])
x.put([1, 2], z)
self.assertTrue(x[0] is not masked)
assert_equal(x[0], 0)
self.assertTrue(x[1] is not masked)
assert_equal(x[1], 3)
self.assertTrue(x[2] is masked)
self.assertTrue(x[3] is not masked)
assert_equal(x[3], 0)
def test_put_hardmask(self):
# Tests put on hardmask
d = arange(5)
n = [0, 0, 0, 1, 1]
m = make_mask(n)
xh = array(d + 1, mask=m, hard_mask=True, copy=True)
xh.put([4, 2, 0, 1, 3], [1, 2, 3, 4, 5])
assert_equal(xh._data, [3, 4, 2, 4, 5])
def test_putmask(self):
x = arange(6) + 1
mx = array(x, mask=[0, 0, 0, 1, 1, 1])
mask = [0, 0, 1, 0, 0, 1]
# w/o mask, w/o masked values
xx = x.copy()
putmask(xx, mask, 99)
assert_equal(xx, [1, 2, 99, 4, 5, 99])
# w/ mask, w/o masked values
mxx = mx.copy()
putmask(mxx, mask, 99)
assert_equal(mxx._data, [1, 2, 99, 4, 5, 99])
assert_equal(mxx._mask, [0, 0, 0, 1, 1, 0])
# w/o mask, w/ masked values
values = array([10, 20, 30, 40, 50, 60], mask=[1, 1, 1, 0, 0, 0])
xx = x.copy()
putmask(xx, mask, values)
assert_equal(xx._data, [1, 2, 30, 4, 5, 60])
assert_equal(xx._mask, [0, 0, 1, 0, 0, 0])
# w/ mask, w/ masked values
mxx = mx.copy()
putmask(mxx, mask, values)
assert_equal(mxx._data, [1, 2, 30, 4, 5, 60])
assert_equal(mxx._mask, [0, 0, 1, 1, 1, 0])
# w/ mask, w/ masked values + hardmask
mxx = mx.copy()
mxx.harden_mask()
putmask(mxx, mask, values)
assert_equal(mxx, [1, 2, 30, 4, 5, 60])
def test_ravel(self):
# Tests ravel
a = array([[1, 2, 3, 4, 5]], mask=[[0, 1, 0, 0, 0]])
aravel = a.ravel()
assert_equal(aravel._mask.shape, aravel.shape)
a = array([0, 0], mask=[1, 1])
aravel = a.ravel()
assert_equal(aravel._mask.shape, a.shape)
a = array(np.matrix([1, 2, 3, 4, 5]), mask=[[0, 1, 0, 0, 0]])
aravel = a.ravel()
assert_equal(aravel.shape, (1, 5))
assert_equal(aravel._mask.shape, a.shape)
# Checks that small_mask is preserved
a = array([1, 2, 3, 4], mask=[0, 0, 0, 0], shrink=False)
assert_equal(a.ravel()._mask, [0, 0, 0, 0])
# Test that the fill_value is preserved
a.fill_value = -99
a.shape = (2, 2)
ar = a.ravel()
assert_equal(ar._mask, [0, 0, 0, 0])
assert_equal(ar._data, [1, 2, 3, 4])
assert_equal(ar.fill_value, -99)
# Test index ordering
assert_equal(a.ravel(order='C'), [1, 2, 3, 4])
assert_equal(a.ravel(order='F'), [1, 3, 2, 4])
def test_reshape(self):
# Tests reshape
x = arange(4)
x[0] = masked
y = x.reshape(2, 2)
assert_equal(y.shape, (2, 2,))
assert_equal(y._mask.shape, (2, 2,))
assert_equal(x.shape, (4,))
assert_equal(x._mask.shape, (4,))
def test_sort(self):
# Test sort
x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)
sortedx = sort(x)
assert_equal(sortedx._data, [1, 2, 3, 4])
assert_equal(sortedx._mask, [0, 0, 0, 1])
sortedx = sort(x, endwith=False)
assert_equal(sortedx._data, [4, 1, 2, 3])
assert_equal(sortedx._mask, [1, 0, 0, 0])
x.sort()
assert_equal(x._data, [1, 2, 3, 4])
assert_equal(x._mask, [0, 0, 0, 1])
x = array([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)
x.sort(endwith=False)
assert_equal(x._data, [4, 1, 2, 3])
assert_equal(x._mask, [1, 0, 0, 0])
x = [1, 4, 2, 3]
sortedx = sort(x)
self.assertTrue(not isinstance(sorted, MaskedArray))
x = array([0, 1, -1, -2, 2], mask=nomask, dtype=np.int8)
sortedx = sort(x, endwith=False)
assert_equal(sortedx._data, [-2, -1, 0, 1, 2])
x = array([0, 1, -1, -2, 2], mask=[0, 1, 0, 0, 1], dtype=np.int8)
sortedx = sort(x, endwith=False)
assert_equal(sortedx._data, [1, 2, -2, -1, 0])
assert_equal(sortedx._mask, [1, 1, 0, 0, 0])
def test_sort_2d(self):
# Check sort of 2D array.
# 2D array w/o mask
a = masked_array([[8, 4, 1], [2, 0, 9]])
a.sort(0)
assert_equal(a, [[2, 0, 1], [8, 4, 9]])
a = masked_array([[8, 4, 1], [2, 0, 9]])
a.sort(1)
assert_equal(a, [[1, 4, 8], [0, 2, 9]])
# 2D array w/mask
a = masked_array([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]])
a.sort(0)
assert_equal(a, [[2, 0, 1], [8, 4, 9]])
assert_equal(a._mask, [[0, 0, 0], [1, 0, 1]])
a = masked_array([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]])
a.sort(1)
assert_equal(a, [[1, 4, 8], [0, 2, 9]])
assert_equal(a._mask, [[0, 0, 1], [0, 0, 1]])
# 3D
a = masked_array([[[7, 8, 9], [4, 5, 6], [1, 2, 3]],
[[1, 2, 3], [7, 8, 9], [4, 5, 6]],
[[7, 8, 9], [1, 2, 3], [4, 5, 6]],
[[4, 5, 6], [1, 2, 3], [7, 8, 9]]])
a[a % 4 == 0] = masked
am = a.copy()
an = a.filled(99)
am.sort(0)
an.sort(0)
assert_equal(am, an)
am = a.copy()
an = a.filled(99)
am.sort(1)
an.sort(1)
assert_equal(am, an)
am = a.copy()
an = a.filled(99)
am.sort(2)
an.sort(2)
assert_equal(am, an)
def test_sort_flexible(self):
# Test sort on flexible dtype.
a = array(
data=[(3, 3), (3, 2), (2, 2), (2, 1), (1, 0), (1, 1), (1, 2)],
mask=[(0, 0), (0, 1), (0, 0), (0, 0), (1, 0), (0, 0), (0, 0)],
dtype=[('A', int), ('B', int)])
test = sort(a)
b = array(
data=[(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 2), (1, 0)],
mask=[(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (1, 0)],
dtype=[('A', int), ('B', int)])
assert_equal(test, b)
assert_equal(test.mask, b.mask)
test = sort(a, endwith=False)
b = array(
data=[(1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (3, 2), (3, 3), ],
mask=[(1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (0, 0), ],
dtype=[('A', int), ('B', int)])
assert_equal(test, b)
assert_equal(test.mask, b.mask)
def test_argsort(self):
# Test argsort
a = array([1, 5, 2, 4, 3], mask=[1, 0, 0, 1, 0])
assert_equal(np.argsort(a), argsort(a))
def test_squeeze(self):
# Check squeeze
data = masked_array([[1, 2, 3]])
assert_equal(data.squeeze(), [1, 2, 3])
data = masked_array([[1, 2, 3]], mask=[[1, 1, 1]])
assert_equal(data.squeeze(), [1, 2, 3])
assert_equal(data.squeeze()._mask, [1, 1, 1])
data = masked_array([[1]], mask=True)
self.assertTrue(data.squeeze() is masked)
def test_swapaxes(self):
# Tests swapaxes on MaskedArrays.
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
m = np.array([0, 1, 0, 1, 0, 0,
1, 0, 1, 1, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, 1, 1, 1,
1, 0, 0, 1, 0, 0,
0, 0, 1, 0, 1, 0])
mX = array(x, mask=m).reshape(6, 6)
mXX = mX.reshape(3, 2, 2, 3)
mXswapped = mX.swapaxes(0, 1)
assert_equal(mXswapped[-1], mX[:, -1])
mXXswapped = mXX.swapaxes(0, 2)
assert_equal(mXXswapped.shape, (2, 2, 3, 3))
def test_take(self):
# Tests take
x = masked_array([10, 20, 30, 40], [0, 1, 0, 1])
assert_equal(x.take([0, 0, 3]), masked_array([10, 10, 40], [0, 0, 1]))
assert_equal(x.take([0, 0, 3]), x[[0, 0, 3]])
assert_equal(x.take([[0, 1], [0, 1]]),
masked_array([[10, 20], [10, 20]], [[0, 1], [0, 1]]))
# assert_equal crashes when passed np.ma.mask
self.assertIs(x[1], np.ma.masked)
self.assertIs(x.take(1), np.ma.masked)
x = array([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0, ]])
assert_equal(x.take([0, 2], axis=1),
array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]]))
assert_equal(take(x, [0, 2], axis=1),
array([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]]))
def test_take_masked_indices(self):
# Test take w/ masked indices
a = np.array((40, 18, 37, 9, 22))
indices = np.arange(3)[None,:] + np.arange(5)[:, None]
mindices = array(indices, mask=(indices >= len(a)))
# No mask
test = take(a, mindices, mode='clip')
ctrl = array([[40, 18, 37],
[18, 37, 9],
[37, 9, 22],
[9, 22, 22],
[22, 22, 22]])
assert_equal(test, ctrl)
# Masked indices
test = take(a, mindices)
ctrl = array([[40, 18, 37],
[18, 37, 9],
[37, 9, 22],
[9, 22, 40],
[22, 40, 40]])
ctrl[3, 2] = ctrl[4, 1] = ctrl[4, 2] = masked
assert_equal(test, ctrl)
assert_equal(test.mask, ctrl.mask)
# Masked input + masked indices
a = array((40, 18, 37, 9, 22), mask=(0, 1, 0, 0, 0))
test = take(a, mindices)
ctrl[0, 1] = ctrl[1, 0] = masked
assert_equal(test, ctrl)
assert_equal(test.mask, ctrl.mask)
def test_tolist(self):
# Tests to list
# ... on 1D
x = array(np.arange(12))
x[[1, -2]] = masked
xlist = x.tolist()
self.assertTrue(xlist[1] is None)
self.assertTrue(xlist[-2] is None)
# ... on 2D
x.shape = (3, 4)
xlist = x.tolist()
ctrl = [[0, None, 2, 3], [4, 5, 6, 7], [8, 9, None, 11]]
assert_equal(xlist[0], [0, None, 2, 3])
assert_equal(xlist[1], [4, 5, 6, 7])
assert_equal(xlist[2], [8, 9, None, 11])
assert_equal(xlist, ctrl)
# ... on structured array w/ masked records
x = array(list(zip([1, 2, 3],
[1.1, 2.2, 3.3],
['one', 'two', 'thr'])),
dtype=[('a', int), ('b', float), ('c', '|S8')])
x[-1] = masked
assert_equal(x.tolist(),
[(1, 1.1, asbytes('one')),
(2, 2.2, asbytes('two')),
(None, None, None)])
# ... on structured array w/ masked fields
a = array([(1, 2,), (3, 4)], mask=[(0, 1), (0, 0)],
dtype=[('a', int), ('b', int)])
test = a.tolist()
assert_equal(test, [[1, None], [3, 4]])
# ... on mvoid
a = a[0]
test = a.tolist()
assert_equal(test, [1, None])
def test_tolist_specialcase(self):
# Test mvoid.tolist: make sure we return a standard Python object
a = array([(0, 1), (2, 3)], dtype=[('a', int), ('b', int)])
# w/o mask: each entry is a np.void whose elements are standard Python
for entry in a:
for item in entry.tolist():
assert_(not isinstance(item, np.generic))
# w/ mask: each entry is a ma.void whose elements should be
# standard Python
a.mask[0] = (0, 1)
for entry in a:
for item in entry.tolist():
assert_(not isinstance(item, np.generic))
def test_toflex(self):
# Test the conversion to records
data = arange(10)
record = data.toflex()
assert_equal(record['_data'], data._data)
assert_equal(record['_mask'], data._mask)
data[[0, 1, 2, -1]] = masked
record = data.toflex()
assert_equal(record['_data'], data._data)
assert_equal(record['_mask'], data._mask)
ndtype = [('i', int), ('s', '|S3'), ('f', float)]
data = array([(i, s, f) for (i, s, f) in zip(np.arange(10),
'ABCDEFGHIJKLM',
np.random.rand(10))],
dtype=ndtype)
data[[0, 1, 2, -1]] = masked
record = data.toflex()
assert_equal(record['_data'], data._data)
assert_equal(record['_mask'], data._mask)
ndtype = np.dtype("int, (2,3)float, float")
data = array([(i, f, ff) for (i, f, ff) in zip(np.arange(10),
np.random.rand(10),
np.random.rand(10))],
dtype=ndtype)
data[[0, 1, 2, -1]] = masked
record = data.toflex()
assert_equal_records(record['_data'], data._data)
assert_equal_records(record['_mask'], data._mask)
def test_fromflex(self):
# Test the reconstruction of a masked_array from a record
a = array([1, 2, 3])
test = fromflex(a.toflex())
assert_equal(test, a)
assert_equal(test.mask, a.mask)
a = array([1, 2, 3], mask=[0, 0, 1])
test = fromflex(a.toflex())
assert_equal(test, a)
assert_equal(test.mask, a.mask)
a = array([(1, 1.), (2, 2.), (3, 3.)], mask=[(1, 0), (0, 0), (0, 1)],
dtype=[('A', int), ('B', float)])
test = fromflex(a.toflex())
assert_equal(test, a)
assert_equal(test.data, a.data)
def test_arraymethod(self):
# Test a _arraymethod w/ n argument
marray = masked_array([[1, 2, 3, 4, 5]], mask=[0, 0, 1, 0, 0])
control = masked_array([[1], [2], [3], [4], [5]],
mask=[0, 0, 1, 0, 0])
assert_equal(marray.T, control)
assert_equal(marray.transpose(), control)
assert_equal(MaskedArray.cumsum(marray.T, 0), control.cumsum(0))
class TestMaskedArrayMathMethods(TestCase):
def setUp(self):
# Base data definition.
x = np.array([8.375, 7.545, 8.828, 8.5, 1.757, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
6.04, 9.63, 7.712, 3.382, 4.489, 6.479,
7.189, 9.645, 5.395, 4.961, 9.894, 2.893,
7.357, 9.828, 6.272, 3.758, 6.693, 0.993])
X = x.reshape(6, 6)
XX = x.reshape(3, 2, 2, 3)
m = np.array([0, 1, 0, 1, 0, 0,
1, 0, 1, 1, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, 1, 1, 1,
1, 0, 0, 1, 0, 0,
0, 0, 1, 0, 1, 0])
mx = array(data=x, mask=m)
mX = array(data=X, mask=m.reshape(X.shape))
mXX = array(data=XX, mask=m.reshape(XX.shape))
m2 = np.array([1, 1, 0, 1, 0, 0,
1, 1, 1, 1, 0, 1,
0, 0, 1, 1, 0, 1,
0, 0, 0, 1, 1, 1,
1, 0, 0, 1, 1, 0,
0, 0, 1, 0, 1, 1])
m2x = array(data=x, mask=m2)
m2X = array(data=X, mask=m2.reshape(X.shape))
m2XX = array(data=XX, mask=m2.reshape(XX.shape))
self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
def test_cumsumprod(self):
# Tests cumsum & cumprod on MaskedArrays.
(x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
mXcp = mX.cumsum(0)
assert_equal(mXcp._data, mX.filled(0).cumsum(0))
mXcp = mX.cumsum(1)
assert_equal(mXcp._data, mX.filled(0).cumsum(1))
mXcp = mX.cumprod(0)
assert_equal(mXcp._data, mX.filled(1).cumprod(0))
mXcp = mX.cumprod(1)
assert_equal(mXcp._data, mX.filled(1).cumprod(1))
def test_cumsumprod_with_output(self):
# Tests cumsum/cumprod w/ output
xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
xm[:, 0] = xm[0] = xm[-1, -1] = masked
for funcname in ('cumsum', 'cumprod'):
npfunc = getattr(np, funcname)
xmmeth = getattr(xm, funcname)
# A ndarray as explicit input
output = np.empty((3, 4), dtype=float)
output.fill(-9999)
result = npfunc(xm, axis=0, out=output)
# ... the result should be the given output
self.assertTrue(result is output)
assert_equal(result, xmmeth(axis=0, out=output))
output = empty((3, 4), dtype=int)
result = xmmeth(axis=0, out=output)
self.assertTrue(result is output)
def test_ptp(self):
# Tests ptp on MaskedArrays.
(x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
(n, m) = X.shape
assert_equal(mx.ptp(), mx.compressed().ptp())
rows = np.zeros(n, np.float)
cols = np.zeros(m, np.float)
for k in range(m):
cols[k] = mX[:, k].compressed().ptp()
for k in range(n):
rows[k] = mX[k].compressed().ptp()
assert_equal(mX.ptp(0), cols)
assert_equal(mX.ptp(1), rows)
def test_add_object(self):
x = masked_array(['a', 'b'], mask=[1, 0], dtype=object)
y = x + 'x'
assert_equal(y[1], 'bx')
assert_(y.mask[0])
def test_sum_object(self):
# Test sum on object dtype
a = masked_array([1, 2, 3], mask=[1, 0, 0], dtype=np.object)
assert_equal(a.sum(), 5)
a = masked_array([[1, 2, 3], [4, 5, 6]], dtype=object)
assert_equal(a.sum(axis=0), [5, 7, 9])
def test_prod_object(self):
# Test prod on object dtype
a = masked_array([1, 2, 3], mask=[1, 0, 0], dtype=np.object)
assert_equal(a.prod(), 2 * 3)
a = masked_array([[1, 2, 3], [4, 5, 6]], dtype=object)
assert_equal(a.prod(axis=0), [4, 10, 18])
def test_meananom_object(self):
# Test mean/anom on object dtype
a = masked_array([1, 2, 3], dtype=np.object)
assert_equal(a.mean(), 2)
assert_equal(a.anom(), [-1, 0, 1])
def test_trace(self):
# Tests trace on MaskedArrays.
(x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
mXdiag = mX.diagonal()
assert_equal(mX.trace(), mX.diagonal().compressed().sum())
assert_almost_equal(mX.trace(),
X.trace() - sum(mXdiag.mask * X.diagonal(),
axis=0))
assert_equal(np.trace(mX), mX.trace())
def test_dot(self):
# Tests dot on MaskedArrays.
(x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
fx = mx.filled(0)
r = mx.dot(mx)
assert_almost_equal(r.filled(0), fx.dot(fx))
assert_(r.mask is nomask)
fX = mX.filled(0)
r = mX.dot(mX)
assert_almost_equal(r.filled(0), fX.dot(fX))
assert_(r.mask[1,3])
r1 = empty_like(r)
mX.dot(mX, out=r1)
assert_almost_equal(r, r1)
mYY = mXX.swapaxes(-1, -2)
fXX, fYY = mXX.filled(0), mYY.filled(0)
r = mXX.dot(mYY)
assert_almost_equal(r.filled(0), fXX.dot(fYY))
r1 = empty_like(r)
mXX.dot(mYY, out=r1)
assert_almost_equal(r, r1)
def test_dot_shape_mismatch(self):
# regression test
x = masked_array([[1,2],[3,4]], mask=[[0,1],[0,0]])
y = masked_array([[1,2],[3,4]], mask=[[0,1],[0,0]])
z = masked_array([[0,1],[3,3]])
x.dot(y, out=z)
assert_almost_equal(z.filled(0), [[1, 0], [15, 16]])
assert_almost_equal(z.mask, [[0, 1], [0, 0]])
def test_varstd(self):
# Tests var & std on MaskedArrays.
(x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
assert_almost_equal(mX.var(axis=None), mX.compressed().var())
assert_almost_equal(mX.std(axis=None), mX.compressed().std())
assert_almost_equal(mX.std(axis=None, ddof=1),
mX.compressed().std(ddof=1))
assert_almost_equal(mX.var(axis=None, ddof=1),
mX.compressed().var(ddof=1))
assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape)
assert_equal(mX.var().shape, X.var().shape)
(mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
assert_almost_equal(mX.var(axis=None, ddof=2),
mX.compressed().var(ddof=2))
assert_almost_equal(mX.std(axis=None, ddof=2),
mX.compressed().std(ddof=2))
for k in range(6):
assert_almost_equal(mXvar1[k], mX[k].compressed().var())
assert_almost_equal(mXvar0[k], mX[:, k].compressed().var())
assert_almost_equal(np.sqrt(mXvar0[k]),
mX[:, k].compressed().std())
def test_varstd_specialcases(self):
# Test a special case for var
nout = np.array(-1, dtype=float)
mout = array(-1, dtype=float)
x = array(arange(10), mask=True)
for methodname in ('var', 'std'):
method = getattr(x, methodname)
self.assertTrue(method() is masked)
self.assertTrue(method(0) is masked)
self.assertTrue(method(-1) is masked)
# Using a masked array as explicit output
with warnings.catch_warnings():
warnings.simplefilter('ignore')
method(out=mout)
self.assertTrue(mout is not masked)
assert_equal(mout.mask, True)
# Using a ndarray as explicit output
with warnings.catch_warnings():
warnings.simplefilter('ignore')
method(out=nout)
self.assertTrue(np.isnan(nout))
x = array(arange(10), mask=True)
x[-1] = 9
for methodname in ('var', 'std'):
method = getattr(x, methodname)
self.assertTrue(method(ddof=1) is masked)
self.assertTrue(method(0, ddof=1) is masked)
self.assertTrue(method(-1, ddof=1) is masked)
# Using a masked array as explicit output
method(out=mout, ddof=1)
self.assertTrue(mout is not masked)
assert_equal(mout.mask, True)
# Using a ndarray as explicit output
method(out=nout, ddof=1)
self.assertTrue(np.isnan(nout))
def test_varstd_ddof(self):
a = array([[1, 1, 0], [1, 1, 0]], mask=[[0, 0, 1], [0, 0, 1]])
test = a.std(axis=0, ddof=0)
assert_equal(test.filled(0), [0, 0, 0])
assert_equal(test.mask, [0, 0, 1])
test = a.std(axis=0, ddof=1)
assert_equal(test.filled(0), [0, 0, 0])
assert_equal(test.mask, [0, 0, 1])
test = a.std(axis=0, ddof=2)
assert_equal(test.filled(0), [0, 0, 0])
assert_equal(test.mask, [1, 1, 1])
def test_diag(self):
# Test diag
x = arange(9).reshape((3, 3))
x[1, 1] = masked
out = np.diag(x)
assert_equal(out, [0, 4, 8])
out = diag(x)
assert_equal(out, [0, 4, 8])
assert_equal(out.mask, [0, 1, 0])
out = diag(out)
control = array([[0, 0, 0], [0, 4, 0], [0, 0, 8]],
mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]])
assert_equal(out, control)
def test_axis_methods_nomask(self):
# Test the combination nomask & methods w/ axis
a = array([[1, 2, 3], [4, 5, 6]])
assert_equal(a.sum(0), [5, 7, 9])
assert_equal(a.sum(-1), [6, 15])
assert_equal(a.sum(1), [6, 15])
assert_equal(a.prod(0), [4, 10, 18])
assert_equal(a.prod(-1), [6, 120])
assert_equal(a.prod(1), [6, 120])
assert_equal(a.min(0), [1, 2, 3])
assert_equal(a.min(-1), [1, 4])
assert_equal(a.min(1), [1, 4])
assert_equal(a.max(0), [4, 5, 6])
assert_equal(a.max(-1), [3, 6])
assert_equal(a.max(1), [3, 6])
class TestMaskedArrayMathMethodsComplex(TestCase):
# Test class for miscellaneous MaskedArrays methods.
def setUp(self):
# Base data definition.
x = np.array([8.375j, 7.545j, 8.828j, 8.5j, 1.757j, 5.928,
8.43, 7.78, 9.865, 5.878, 8.979, 4.732,
3.012, 6.022, 5.095, 3.116, 5.238, 3.957,
6.04, 9.63, 7.712, 3.382, 4.489, 6.479j,
7.189j, 9.645, 5.395, 4.961, 9.894, 2.893,
7.357, 9.828, 6.272, 3.758, 6.693, 0.993j])
X = x.reshape(6, 6)
XX = x.reshape(3, 2, 2, 3)
m = np.array([0, 1, 0, 1, 0, 0,
1, 0, 1, 1, 0, 1,
0, 0, 0, 1, 0, 1,
0, 0, 0, 1, 1, 1,
1, 0, 0, 1, 0, 0,
0, 0, 1, 0, 1, 0])
mx = array(data=x, mask=m)
mX = array(data=X, mask=m.reshape(X.shape))
mXX = array(data=XX, mask=m.reshape(XX.shape))
m2 = np.array([1, 1, 0, 1, 0, 0,
1, 1, 1, 1, 0, 1,
0, 0, 1, 1, 0, 1,
0, 0, 0, 1, 1, 1,
1, 0, 0, 1, 1, 0,
0, 0, 1, 0, 1, 1])
m2x = array(data=x, mask=m2)
m2X = array(data=X, mask=m2.reshape(X.shape))
m2XX = array(data=XX, mask=m2.reshape(XX.shape))
self.d = (x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX)
def test_varstd(self):
# Tests var & std on MaskedArrays.
(x, X, XX, m, mx, mX, mXX, m2x, m2X, m2XX) = self.d
assert_almost_equal(mX.var(axis=None), mX.compressed().var())
assert_almost_equal(mX.std(axis=None), mX.compressed().std())
assert_equal(mXX.var(axis=3).shape, XX.var(axis=3).shape)
assert_equal(mX.var().shape, X.var().shape)
(mXvar0, mXvar1) = (mX.var(axis=0), mX.var(axis=1))
assert_almost_equal(mX.var(axis=None, ddof=2),
mX.compressed().var(ddof=2))
assert_almost_equal(mX.std(axis=None, ddof=2),
mX.compressed().std(ddof=2))
for k in range(6):
assert_almost_equal(mXvar1[k], mX[k].compressed().var())
assert_almost_equal(mXvar0[k], mX[:, k].compressed().var())
assert_almost_equal(np.sqrt(mXvar0[k]),
mX[:, k].compressed().std())
class TestMaskedArrayFunctions(TestCase):
# Test class for miscellaneous functions.
def setUp(self):
x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
xm = masked_array(x, mask=m1)
ym = masked_array(y, mask=m2)
xm.set_fill_value(1e+20)
self.info = (xm, ym)
def test_masked_where_bool(self):
x = [1, 2]
y = masked_where(False, x)
assert_equal(y, [1, 2])
assert_equal(y[1], 2)
def test_masked_equal_wlist(self):
x = [1, 2, 3]
mx = masked_equal(x, 3)
assert_equal(mx, x)
assert_equal(mx._mask, [0, 0, 1])
mx = masked_not_equal(x, 3)
assert_equal(mx, x)
assert_equal(mx._mask, [1, 1, 0])
def test_masked_equal_fill_value(self):
x = [1, 2, 3]
mx = masked_equal(x, 3)
assert_equal(mx._mask, [0, 0, 1])
assert_equal(mx.fill_value, 3)
def test_masked_where_condition(self):
# Tests masking functions.
x = array([1., 2., 3., 4., 5.])
x[2] = masked
assert_equal(masked_where(greater(x, 2), x), masked_greater(x, 2))
assert_equal(masked_where(greater_equal(x, 2), x),
masked_greater_equal(x, 2))
assert_equal(masked_where(less(x, 2), x), masked_less(x, 2))
assert_equal(masked_where(less_equal(x, 2), x),
masked_less_equal(x, 2))
assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))
assert_equal(masked_where(equal(x, 2), x), masked_equal(x, 2))
assert_equal(masked_where(not_equal(x, 2), x), masked_not_equal(x, 2))
assert_equal(masked_where([1, 1, 0, 0, 0], [1, 2, 3, 4, 5]),
[99, 99, 3, 4, 5])
def test_masked_where_oddities(self):
# Tests some generic features.
atest = ones((10, 10, 10), dtype=float)
btest = zeros(atest.shape, MaskType)
ctest = masked_where(btest, atest)
assert_equal(atest, ctest)
def test_masked_where_shape_constraint(self):
a = arange(10)
try:
test = masked_equal(1, a)
except IndexError:
pass
else:
raise AssertionError("Should have failed...")
test = masked_equal(a, 1)
assert_equal(test.mask, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0])
def test_masked_where_structured(self):
# test that masked_where on a structured array sets a structured
# mask (see issue #2972)
a = np.zeros(10, dtype=[("A", "<f2"), ("B", "<f4")])
am = np.ma.masked_where(a["A"] < 5, a)
assert_equal(am.mask.dtype.names, am.dtype.names)
assert_equal(am["A"],
np.ma.masked_array(np.zeros(10), np.ones(10)))
def test_masked_otherfunctions(self):
assert_equal(masked_inside(list(range(5)), 1, 3),
[0, 199, 199, 199, 4])
assert_equal(masked_outside(list(range(5)), 1, 3), [199, 1, 2, 3, 199])
assert_equal(masked_inside(array(list(range(5)),
mask=[1, 0, 0, 0, 0]), 1, 3).mask,
[1, 1, 1, 1, 0])
assert_equal(masked_outside(array(list(range(5)),
mask=[0, 1, 0, 0, 0]), 1, 3).mask,
[1, 1, 0, 0, 1])
assert_equal(masked_equal(array(list(range(5)),
mask=[1, 0, 0, 0, 0]), 2).mask,
[1, 0, 1, 0, 0])
assert_equal(masked_not_equal(array([2, 2, 1, 2, 1],
mask=[1, 0, 0, 0, 0]), 2).mask,
[1, 0, 1, 0, 1])
def test_round(self):
a = array([1.23456, 2.34567, 3.45678, 4.56789, 5.67890],
mask=[0, 1, 0, 0, 0])
assert_equal(a.round(), [1., 2., 3., 5., 6.])
assert_equal(a.round(1), [1.2, 2.3, 3.5, 4.6, 5.7])
assert_equal(a.round(3), [1.235, 2.346, 3.457, 4.568, 5.679])
b = empty_like(a)
a.round(out=b)
assert_equal(b, [1., 2., 3., 5., 6.])
x = array([1., 2., 3., 4., 5.])
c = array([1, 1, 1, 0, 0])
x[2] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
c[0] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
assert_(z[0] is masked)
assert_(z[1] is not masked)
assert_(z[2] is masked)
def test_round_with_output(self):
# Testing round with an explicit output
xm = array(np.random.uniform(0, 10, 12)).reshape(3, 4)
xm[:, 0] = xm[0] = xm[-1, -1] = masked
# A ndarray as explicit input
output = np.empty((3, 4), dtype=float)
output.fill(-9999)
result = np.round(xm, decimals=2, out=output)
# ... the result should be the given output
self.assertTrue(result is output)
assert_equal(result, xm.round(decimals=2, out=output))
output = empty((3, 4), dtype=float)
result = xm.round(decimals=2, out=output)
self.assertTrue(result is output)
def test_round_with_scalar(self):
# Testing round with scalar/zero dimension input
# GH issue 2244
a = array(1.1, mask=[False])
assert_equal(a.round(), 1)
a = array(1.1, mask=[True])
assert_(a.round() is masked)
a = array(1.1, mask=[False])
output = np.empty(1, dtype=float)
output.fill(-9999)
a.round(out=output)
assert_equal(output, 1)
a = array(1.1, mask=[False])
output = array(-9999., mask=[True])
a.round(out=output)
assert_equal(output[()], 1)
a = array(1.1, mask=[True])
output = array(-9999., mask=[False])
a.round(out=output)
assert_(output[()] is masked)
def test_identity(self):
a = identity(5)
self.assertTrue(isinstance(a, MaskedArray))
assert_equal(a, np.identity(5))
def test_power(self):
x = -1.1
assert_almost_equal(power(x, 2.), 1.21)
self.assertTrue(power(x, masked) is masked)
x = array([-1.1, -1.1, 1.1, 1.1, 0.])
b = array([0.5, 2., 0.5, 2., -1.], mask=[0, 0, 0, 0, 1])
y = power(x, b)
assert_almost_equal(y, [0, 1.21, 1.04880884817, 1.21, 0.])
assert_equal(y._mask, [1, 0, 0, 0, 1])
b.mask = nomask
y = power(x, b)
assert_equal(y._mask, [1, 0, 0, 0, 1])
z = x ** b
assert_equal(z._mask, y._mask)
assert_almost_equal(z, y)
assert_almost_equal(z._data, y._data)
x **= b
assert_equal(x._mask, y._mask)
assert_almost_equal(x, y)
assert_almost_equal(x._data, y._data)
def test_power_w_broadcasting(self):
# Test power w/ broadcasting
a2 = np.array([[1., 2., 3.], [4., 5., 6.]])
a2m = array(a2, mask=[[1, 0, 0], [0, 0, 1]])
b1 = np.array([2, 4, 3])
b2 = np.array([b1, b1])
b2m = array(b2, mask=[[0, 1, 0], [0, 1, 0]])
ctrl = array([[1 ** 2, 2 ** 4, 3 ** 3], [4 ** 2, 5 ** 4, 6 ** 3]],
mask=[[1, 1, 0], [0, 1, 1]])
# No broadcasting, base & exp w/ mask
test = a2m ** b2m
assert_equal(test, ctrl)
assert_equal(test.mask, ctrl.mask)
# No broadcasting, base w/ mask, exp w/o mask
test = a2m ** b2
assert_equal(test, ctrl)
assert_equal(test.mask, a2m.mask)
# No broadcasting, base w/o mask, exp w/ mask
test = a2 ** b2m
assert_equal(test, ctrl)
assert_equal(test.mask, b2m.mask)
ctrl = array([[2 ** 2, 4 ** 4, 3 ** 3], [2 ** 2, 4 ** 4, 3 ** 3]],
mask=[[0, 1, 0], [0, 1, 0]])
test = b1 ** b2m
assert_equal(test, ctrl)
assert_equal(test.mask, ctrl.mask)
test = b2m ** b1
assert_equal(test, ctrl)
assert_equal(test.mask, ctrl.mask)
def test_where(self):
# Test the where function
x = np.array([1., 1., 1., -2., pi/2.0, 4., 5., -10., 10., 1., 2., 3.])
y = np.array([5., 0., 3., 2., -1., -4., 0., -10., 10., 1., 0., 3.])
m1 = [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]
m2 = [0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 1]
xm = masked_array(x, mask=m1)
ym = masked_array(y, mask=m2)
xm.set_fill_value(1e+20)
d = where(xm > 2, xm, -9)
assert_equal(d, [-9., -9., -9., -9., -9., 4.,
-9., -9., 10., -9., -9., 3.])
assert_equal(d._mask, xm._mask)
d = where(xm > 2, -9, ym)
assert_equal(d, [5., 0., 3., 2., -1., -9.,
-9., -10., -9., 1., 0., -9.])
assert_equal(d._mask, [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0])
d = where(xm > 2, xm, masked)
assert_equal(d, [-9., -9., -9., -9., -9., 4.,
-9., -9., 10., -9., -9., 3.])
tmp = xm._mask.copy()
tmp[(xm <= 2).filled(True)] = True
assert_equal(d._mask, tmp)
ixm = xm.astype(int)
d = where(ixm > 2, ixm, masked)
assert_equal(d, [-9, -9, -9, -9, -9, 4, -9, -9, 10, -9, -9, 3])
assert_equal(d.dtype, ixm.dtype)
def test_where_object(self):
a = np.array(None)
b = masked_array(None)
r = b.copy()
assert_equal(np.ma.where(True, a, a), r)
assert_equal(np.ma.where(True, b, b), r)
def test_where_with_masked_choice(self):
x = arange(10)
x[3] = masked
c = x >= 8
# Set False to masked
z = where(c, x, masked)
assert_(z.dtype is x.dtype)
assert_(z[3] is masked)
assert_(z[4] is masked)
assert_(z[7] is masked)
assert_(z[8] is not masked)
assert_(z[9] is not masked)
assert_equal(x, z)
# Set True to masked
z = where(c, masked, x)
assert_(z.dtype is x.dtype)
assert_(z[3] is masked)
assert_(z[4] is not masked)
assert_(z[7] is not masked)
assert_(z[8] is masked)
assert_(z[9] is masked)
def test_where_with_masked_condition(self):
x = array([1., 2., 3., 4., 5.])
c = array([1, 1, 1, 0, 0])
x[2] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
c[0] = masked
z = where(c, x, -x)
assert_equal(z, [1., 2., 0., -4., -5])
assert_(z[0] is masked)
assert_(z[1] is not masked)
assert_(z[2] is masked)
x = arange(1, 6)
x[-1] = masked
y = arange(1, 6) * 10
y[2] = masked
c = array([1, 1, 1, 0, 0], mask=[1, 0, 0, 0, 0])
cm = c.filled(1)
z = where(c, x, y)
zm = where(cm, x, y)
assert_equal(z, zm)
assert_(getmask(zm) is nomask)
assert_equal(zm, [1, 2, 3, 40, 50])
z = where(c, masked, 1)
assert_equal(z, [99, 99, 99, 1, 1])
z = where(c, 1, masked)
assert_equal(z, [99, 1, 1, 99, 99])
def test_where_type(self):
# Test the type conservation with where
x = np.arange(4, dtype=np.int32)
y = np.arange(4, dtype=np.float32) * 2.2
test = where(x > 1.5, y, x).dtype
control = np.find_common_type([np.int32, np.float32], [])
assert_equal(test, control)
def test_choose(self):
# Test choose
choices = [[0, 1, 2, 3], [10, 11, 12, 13],
[20, 21, 22, 23], [30, 31, 32, 33]]
chosen = choose([2, 3, 1, 0], choices)
assert_equal(chosen, array([20, 31, 12, 3]))
chosen = choose([2, 4, 1, 0], choices, mode='clip')
assert_equal(chosen, array([20, 31, 12, 3]))
chosen = choose([2, 4, 1, 0], choices, mode='wrap')
assert_equal(chosen, array([20, 1, 12, 3]))
# Check with some masked indices
indices_ = array([2, 4, 1, 0], mask=[1, 0, 0, 1])
chosen = choose(indices_, choices, mode='wrap')
assert_equal(chosen, array([99, 1, 12, 99]))
assert_equal(chosen.mask, [1, 0, 0, 1])
# Check with some masked choices
choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1],
[1, 0, 0, 0], [0, 0, 0, 0]])
indices_ = [2, 3, 1, 0]
chosen = choose(indices_, choices, mode='wrap')
assert_equal(chosen, array([20, 31, 12, 3]))
assert_equal(chosen.mask, [1, 0, 0, 1])
def test_choose_with_out(self):
# Test choose with an explicit out keyword
choices = [[0, 1, 2, 3], [10, 11, 12, 13],
[20, 21, 22, 23], [30, 31, 32, 33]]
store = empty(4, dtype=int)
chosen = choose([2, 3, 1, 0], choices, out=store)
assert_equal(store, array([20, 31, 12, 3]))
self.assertTrue(store is chosen)
# Check with some masked indices + out
store = empty(4, dtype=int)
indices_ = array([2, 3, 1, 0], mask=[1, 0, 0, 1])
chosen = choose(indices_, choices, mode='wrap', out=store)
assert_equal(store, array([99, 31, 12, 99]))
assert_equal(store.mask, [1, 0, 0, 1])
# Check with some masked choices + out ina ndarray !
choices = array(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1],
[1, 0, 0, 0], [0, 0, 0, 0]])
indices_ = [2, 3, 1, 0]
store = empty(4, dtype=int).view(ndarray)
chosen = choose(indices_, choices, mode='wrap', out=store)
assert_equal(store, array([999999, 31, 12, 999999]))
def test_reshape(self):
a = arange(10)
a[0] = masked
# Try the default
b = a.reshape((5, 2))
assert_equal(b.shape, (5, 2))
self.assertTrue(b.flags['C'])
# Try w/ arguments as list instead of tuple
b = a.reshape(5, 2)
assert_equal(b.shape, (5, 2))
self.assertTrue(b.flags['C'])
# Try w/ order
b = a.reshape((5, 2), order='F')
assert_equal(b.shape, (5, 2))
self.assertTrue(b.flags['F'])
# Try w/ order
b = a.reshape(5, 2, order='F')
assert_equal(b.shape, (5, 2))
self.assertTrue(b.flags['F'])
c = np.reshape(a, (2, 5))
self.assertTrue(isinstance(c, MaskedArray))
assert_equal(c.shape, (2, 5))
self.assertTrue(c[0, 0] is masked)
self.assertTrue(c.flags['C'])
def test_make_mask_descr(self):
# Test make_mask_descr
# Flexible
ntype = [('a', np.float), ('b', np.float)]
test = make_mask_descr(ntype)
assert_equal(test, [('a', np.bool), ('b', np.bool)])
# Standard w/ shape
ntype = (np.float, 2)
test = make_mask_descr(ntype)
assert_equal(test, (np.bool, 2))
# Standard standard
ntype = np.float
test = make_mask_descr(ntype)
assert_equal(test, np.dtype(np.bool))
# Nested
ntype = [('a', np.float), ('b', [('ba', np.float), ('bb', np.float)])]
test = make_mask_descr(ntype)
control = np.dtype([('a', 'b1'), ('b', [('ba', 'b1'), ('bb', 'b1')])])
assert_equal(test, control)
# Named+ shape
ntype = [('a', (np.float, 2))]
test = make_mask_descr(ntype)
assert_equal(test, np.dtype([('a', (np.bool, 2))]))
# 2 names
ntype = [(('A', 'a'), float)]
test = make_mask_descr(ntype)
assert_equal(test, np.dtype([(('A', 'a'), bool)]))
def test_make_mask(self):
# Test make_mask
# w/ a list as an input
mask = [0, 1]
test = make_mask(mask)
assert_equal(test.dtype, MaskType)
assert_equal(test, [0, 1])
# w/ a ndarray as an input
mask = np.array([0, 1], dtype=np.bool)
test = make_mask(mask)
assert_equal(test.dtype, MaskType)
assert_equal(test, [0, 1])
# w/ a flexible-type ndarray as an input - use default
mdtype = [('a', np.bool), ('b', np.bool)]
mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
test = make_mask(mask)
assert_equal(test.dtype, MaskType)
assert_equal(test, [1, 1])
# w/ a flexible-type ndarray as an input - use input dtype
mdtype = [('a', np.bool), ('b', np.bool)]
mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
test = make_mask(mask, dtype=mask.dtype)
assert_equal(test.dtype, mdtype)
assert_equal(test, mask)
# w/ a flexible-type ndarray as an input - use input dtype
mdtype = [('a', np.float), ('b', np.float)]
bdtype = [('a', np.bool), ('b', np.bool)]
mask = np.array([(0, 0), (0, 1)], dtype=mdtype)
test = make_mask(mask, dtype=mask.dtype)
assert_equal(test.dtype, bdtype)
assert_equal(test, np.array([(0, 0), (0, 1)], dtype=bdtype))
# test that nomask is returned when m is nomask.
bools = [True, False]
dtypes = [MaskType, np.float]
msgformat = 'copy=%s, shrink=%s, dtype=%s'
for cpy, shr, dt in itertools.product(bools, bools, dtypes):
res = make_mask(nomask, copy=cpy, shrink=shr, dtype=dt)
assert_(res is nomask, msgformat % (cpy, shr, dt))
def test_mask_or(self):
# Initialize
mtype = [('a', np.bool), ('b', np.bool)]
mask = np.array([(0, 0), (0, 1), (1, 0), (0, 0)], dtype=mtype)
# Test using nomask as input
test = mask_or(mask, nomask)
assert_equal(test, mask)
test = mask_or(nomask, mask)
assert_equal(test, mask)
# Using False as input
test = mask_or(mask, False)
assert_equal(test, mask)
# Using another array w / the same dtype
other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=mtype)
test = mask_or(mask, other)
control = np.array([(0, 1), (0, 1), (1, 1), (0, 1)], dtype=mtype)
assert_equal(test, control)
# Using another array w / a different dtype
othertype = [('A', np.bool), ('B', np.bool)]
other = np.array([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=othertype)
try:
test = mask_or(mask, other)
except ValueError:
pass
# Using nested arrays
dtype = [('a', np.bool), ('b', [('ba', np.bool), ('bb', np.bool)])]
amask = np.array([(0, (1, 0)), (0, (1, 0))], dtype=dtype)
bmask = np.array([(1, (0, 1)), (0, (0, 0))], dtype=dtype)
cntrl = np.array([(1, (1, 1)), (0, (1, 0))], dtype=dtype)
assert_equal(mask_or(amask, bmask), cntrl)
def test_flatten_mask(self):
# Tests flatten mask
# Standard dtype
mask = np.array([0, 0, 1], dtype=np.bool)
assert_equal(flatten_mask(mask), mask)
# Flexible dtype
mask = np.array([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])
test = flatten_mask(mask)
control = np.array([0, 0, 0, 1], dtype=bool)
assert_equal(test, control)
mdtype = [('a', bool), ('b', [('ba', bool), ('bb', bool)])]
data = [(0, (0, 0)), (0, (0, 1))]
mask = np.array(data, dtype=mdtype)
test = flatten_mask(mask)
control = np.array([0, 0, 0, 0, 0, 1], dtype=bool)
assert_equal(test, control)
def test_on_ndarray(self):
# Test functions on ndarrays
a = np.array([1, 2, 3, 4])
m = array(a, mask=False)
test = anom(a)
assert_equal(test, m.anom())
test = reshape(a, (2, 2))
assert_equal(test, m.reshape(2, 2))
def test_compress(self):
# Test compress function on ndarray and masked array
# Address Github #2495.
arr = np.arange(8)
arr.shape = 4, 2
cond = np.array([True, False, True, True])
control = arr[[0, 2, 3]]
test = np.ma.compress(cond, arr, axis=0)
assert_equal(test, control)
marr = np.ma.array(arr)
test = np.ma.compress(cond, marr, axis=0)
assert_equal(test, control)
def test_compressed(self):
# Test ma.compressed function.
# Address gh-4026
a = np.ma.array([1, 2])
test = np.ma.compressed(a)
assert_(type(test) is np.ndarray)
# Test case when input data is ndarray subclass
class A(np.ndarray):
pass
a = np.ma.array(A(shape=0))
test = np.ma.compressed(a)
assert_(type(test) is A)
# Test that compress flattens
test = np.ma.compressed([[1],[2]])
assert_equal(test.ndim, 1)
test = np.ma.compressed([[[[[1]]]]])
assert_equal(test.ndim, 1)
# Test case when input is MaskedArray subclass
class M(MaskedArray):
pass
test = np.ma.compressed(M(shape=(0,1,2)))
assert_equal(test.ndim, 1)
# with .compressed() overridden
class M(MaskedArray):
def compressed(self):
return 42
test = np.ma.compressed(M(shape=(0,1,2)))
assert_equal(test, 42)
class TestMaskedFields(TestCase):
def setUp(self):
ilist = [1, 2, 3, 4, 5]
flist = [1.1, 2.2, 3.3, 4.4, 5.5]
slist = ['one', 'two', 'three', 'four', 'five']
ddtype = [('a', int), ('b', float), ('c', '|S8')]
mdtype = [('a', bool), ('b', bool), ('c', bool)]
mask = [0, 1, 0, 0, 1]
base = array(list(zip(ilist, flist, slist)), mask=mask, dtype=ddtype)
self.data = dict(base=base, mask=mask, ddtype=ddtype, mdtype=mdtype)
def test_set_records_masks(self):
base = self.data['base']
mdtype = self.data['mdtype']
# Set w/ nomask or masked
base.mask = nomask
assert_equal_records(base._mask, np.zeros(base.shape, dtype=mdtype))
base.mask = masked
assert_equal_records(base._mask, np.ones(base.shape, dtype=mdtype))
# Set w/ simple boolean
base.mask = False
assert_equal_records(base._mask, np.zeros(base.shape, dtype=mdtype))
base.mask = True
assert_equal_records(base._mask, np.ones(base.shape, dtype=mdtype))
# Set w/ list
base.mask = [0, 0, 0, 1, 1]
assert_equal_records(base._mask,
np.array([(x, x, x) for x in [0, 0, 0, 1, 1]],
dtype=mdtype))
def test_set_record_element(self):
# Check setting an element of a record)
base = self.data['base']
(base_a, base_b, base_c) = (base['a'], base['b'], base['c'])
base[0] = (pi, pi, 'pi')
assert_equal(base_a.dtype, int)
assert_equal(base_a._data, [3, 2, 3, 4, 5])
assert_equal(base_b.dtype, float)
assert_equal(base_b._data, [pi, 2.2, 3.3, 4.4, 5.5])
assert_equal(base_c.dtype, '|S8')
assert_equal(base_c._data,
asbytes_nested(['pi', 'two', 'three', 'four', 'five']))
def test_set_record_slice(self):
base = self.data['base']
(base_a, base_b, base_c) = (base['a'], base['b'], base['c'])
base[:3] = (pi, pi, 'pi')
assert_equal(base_a.dtype, int)
assert_equal(base_a._data, [3, 3, 3, 4, 5])
assert_equal(base_b.dtype, float)
assert_equal(base_b._data, [pi, pi, pi, 4.4, 5.5])
assert_equal(base_c.dtype, '|S8')
assert_equal(base_c._data,
asbytes_nested(['pi', 'pi', 'pi', 'four', 'five']))
def test_mask_element(self):
"Check record access"
base = self.data['base']
base[0] = masked
for n in ('a', 'b', 'c'):
assert_equal(base[n].mask, [1, 1, 0, 0, 1])
assert_equal(base[n]._data, base._data[n])
def test_getmaskarray(self):
# Test getmaskarray on flexible dtype
ndtype = [('a', int), ('b', float)]
test = empty(3, dtype=ndtype)
assert_equal(getmaskarray(test),
np.array([(0, 0), (0, 0), (0, 0)],
dtype=[('a', '|b1'), ('b', '|b1')]))
test[:] = masked
assert_equal(getmaskarray(test),
np.array([(1, 1), (1, 1), (1, 1)],
dtype=[('a', '|b1'), ('b', '|b1')]))
def test_view(self):
# Test view w/ flexible dtype
iterator = list(zip(np.arange(10), np.random.rand(10)))
data = np.array(iterator)
a = array(iterator, dtype=[('a', float), ('b', float)])
a.mask[0] = (1, 0)
controlmask = np.array([1] + 19 * [0], dtype=bool)
# Transform globally to simple dtype
test = a.view(float)
assert_equal(test, data.ravel())
assert_equal(test.mask, controlmask)
# Transform globally to dty
test = a.view((float, 2))
assert_equal(test, data)
assert_equal(test.mask, controlmask.reshape(-1, 2))
test = a.view((float, 2), np.matrix)
assert_equal(test, data)
self.assertTrue(isinstance(test, np.matrix))
def test_getitem(self):
ndtype = [('a', float), ('b', float)]
a = array(list(zip(np.random.rand(10), np.arange(10))), dtype=ndtype)
a.mask = np.array(list(zip([0, 0, 0, 0, 0, 0, 0, 0, 1, 1],
[1, 0, 0, 0, 0, 0, 0, 0, 1, 0])),
dtype=[('a', bool), ('b', bool)])
# No mask
self.assertTrue(isinstance(a[1], MaskedArray))
# One element masked
self.assertTrue(isinstance(a[0], MaskedArray))
assert_equal_records(a[0]._data, a._data[0])
assert_equal_records(a[0]._mask, a._mask[0])
# All element masked
self.assertTrue(isinstance(a[-2], MaskedArray))
assert_equal_records(a[-2]._data, a._data[-2])
assert_equal_records(a[-2]._mask, a._mask[-2])
def test_setitem(self):
# Issue 4866: check that one can set individual items in [record][col]
# and [col][record] order
ndtype = np.dtype([('a', float), ('b', int)])
ma = np.ma.MaskedArray([(1.0, 1), (2.0, 2)], dtype=ndtype)
ma['a'][1] = 3.0
assert_equal(ma['a'], np.array([1.0, 3.0]))
ma[1]['a'] = 4.0
assert_equal(ma['a'], np.array([1.0, 4.0]))
# Issue 2403
mdtype = np.dtype([('a', bool), ('b', bool)])
# soft mask
control = np.array([(False, True), (True, True)], dtype=mdtype)
a = np.ma.masked_all((2,), dtype=ndtype)
a['a'][0] = 2
assert_equal(a.mask, control)
a = np.ma.masked_all((2,), dtype=ndtype)
a[0]['a'] = 2
assert_equal(a.mask, control)
# hard mask
control = np.array([(True, True), (True, True)], dtype=mdtype)
a = np.ma.masked_all((2,), dtype=ndtype)
a.harden_mask()
a['a'][0] = 2
assert_equal(a.mask, control)
a = np.ma.masked_all((2,), dtype=ndtype)
a.harden_mask()
a[0]['a'] = 2
assert_equal(a.mask, control)
def test_element_len(self):
# check that len() works for mvoid (Github issue #576)
for rec in self.data['base']:
assert_equal(len(rec), len(self.data['ddtype']))
class TestMaskedView(TestCase):
def setUp(self):
iterator = list(zip(np.arange(10), np.random.rand(10)))
data = np.array(iterator)
a = array(iterator, dtype=[('a', float), ('b', float)])
a.mask[0] = (1, 0)
controlmask = np.array([1] + 19 * [0], dtype=bool)
self.data = (data, a, controlmask)
def test_view_to_nothing(self):
(data, a, controlmask) = self.data
test = a.view()
self.assertTrue(isinstance(test, MaskedArray))
assert_equal(test._data, a._data)
assert_equal(test._mask, a._mask)
def test_view_to_type(self):
(data, a, controlmask) = self.data
test = a.view(np.ndarray)
self.assertTrue(not isinstance(test, MaskedArray))
assert_equal(test, a._data)
assert_equal_records(test, data.view(a.dtype).squeeze())
def test_view_to_simple_dtype(self):
(data, a, controlmask) = self.data
# View globally
test = a.view(float)
self.assertTrue(isinstance(test, MaskedArray))
assert_equal(test, data.ravel())
assert_equal(test.mask, controlmask)
def test_view_to_flexible_dtype(self):
(data, a, controlmask) = self.data
test = a.view([('A', float), ('B', float)])
assert_equal(test.mask.dtype.names, ('A', 'B'))
assert_equal(test['A'], a['a'])
assert_equal(test['B'], a['b'])
test = a[0].view([('A', float), ('B', float)])
self.assertTrue(isinstance(test, MaskedArray))
assert_equal(test.mask.dtype.names, ('A', 'B'))
assert_equal(test['A'], a['a'][0])
assert_equal(test['B'], a['b'][0])
test = a[-1].view([('A', float), ('B', float)])
self.assertTrue(isinstance(test, MaskedArray))
assert_equal(test.dtype.names, ('A', 'B'))
assert_equal(test['A'], a['a'][-1])
assert_equal(test['B'], a['b'][-1])
def test_view_to_subdtype(self):
(data, a, controlmask) = self.data
# View globally
test = a.view((float, 2))
self.assertTrue(isinstance(test, MaskedArray))
assert_equal(test, data)
assert_equal(test.mask, controlmask.reshape(-1, 2))
# View on 1 masked element
test = a[0].view((float, 2))
self.assertTrue(isinstance(test, MaskedArray))
assert_equal(test, data[0])
assert_equal(test.mask, (1, 0))
# View on 1 unmasked element
test = a[-1].view((float, 2))
self.assertTrue(isinstance(test, MaskedArray))
assert_equal(test, data[-1])
def test_view_to_dtype_and_type(self):
(data, a, controlmask) = self.data
test = a.view((float, 2), np.matrix)
assert_equal(test, data)
self.assertTrue(isinstance(test, np.matrix))
self.assertTrue(not isinstance(test, MaskedArray))
class TestOptionalArgs(TestCase):
def test_ndarrayfuncs(self):
# test axis arg behaves the same as ndarray (including mutliple axes)
d = np.arange(24.0).reshape((2,3,4))
m = np.zeros(24, dtype=bool).reshape((2,3,4))
# mask out last element of last dimension
m[:,:,-1] = True
a = np.ma.array(d, mask=m)
def testaxis(f, a, d):
numpy_f = numpy.__getattribute__(f)
ma_f = np.ma.__getattribute__(f)
# test axis arg
assert_equal(ma_f(a, axis=1)[...,:-1], numpy_f(d[...,:-1], axis=1))
assert_equal(ma_f(a, axis=(0,1))[...,:-1],
numpy_f(d[...,:-1], axis=(0,1)))
def testkeepdims(f, a, d):
numpy_f = numpy.__getattribute__(f)
ma_f = np.ma.__getattribute__(f)
# test keepdims arg
assert_equal(ma_f(a, keepdims=True).shape,
numpy_f(d, keepdims=True).shape)
assert_equal(ma_f(a, keepdims=False).shape,
numpy_f(d, keepdims=False).shape)
# test both at once
assert_equal(ma_f(a, axis=1, keepdims=True)[...,:-1],
numpy_f(d[...,:-1], axis=1, keepdims=True))
assert_equal(ma_f(a, axis=(0,1), keepdims=True)[...,:-1],
numpy_f(d[...,:-1], axis=(0,1), keepdims=True))
for f in ['sum', 'prod', 'mean', 'var', 'std']:
testaxis(f, a, d)
testkeepdims(f, a, d)
for f in ['min', 'max']:
testaxis(f, a, d)
d = (np.arange(24).reshape((2,3,4))%2 == 0)
a = np.ma.array(d, mask=m)
for f in ['all', 'any']:
testaxis(f, a, d)
testkeepdims(f, a, d)
def test_count(self):
# test np.ma.count specially
d = np.arange(24.0).reshape((2,3,4))
m = np.zeros(24, dtype=bool).reshape((2,3,4))
m[:,0,:] = True
a = np.ma.array(d, mask=m)
assert_equal(count(a), 16)
assert_equal(count(a, axis=1), 2*ones((2,4)))
assert_equal(count(a, axis=(0,1)), 4*ones((4,)))
assert_equal(count(a, keepdims=True), 16*ones((1,1,1)))
assert_equal(count(a, axis=1, keepdims=True), 2*ones((2,1,4)))
assert_equal(count(a, axis=(0,1), keepdims=True), 4*ones((1,1,4)))
assert_equal(count(a, axis=-2), 2*ones((2,4)))
assert_raises(ValueError, count, a, axis=(1,1))
assert_raises(ValueError, count, a, axis=3)
# check the 'nomask' path
a = np.ma.array(d, mask=nomask)
assert_equal(count(a), 24)
assert_equal(count(a, axis=1), 3*ones((2,4)))
assert_equal(count(a, axis=(0,1)), 6*ones((4,)))
assert_equal(count(a, keepdims=True), 24*ones((1,1,1)))
assert_equal(count(a, axis=1, keepdims=True), 3*ones((2,1,4)))
assert_equal(count(a, axis=(0,1), keepdims=True), 6*ones((1,1,4)))
assert_equal(count(a, axis=-2), 3*ones((2,4)))
assert_raises(ValueError, count, a, axis=(1,1))
assert_raises(ValueError, count, a, axis=3)
# check the 'masked' singleton
assert_equal(count(np.ma.masked), 0)
# check 0-d arrays do not allow axis > 0
assert_raises(ValueError, count, np.ma.array(1), axis=1)
def test_masked_array():
a = np.ma.array([0, 1, 2, 3], mask=[0, 0, 1, 0])
assert_equal(np.argwhere(a), [[1], [3]])
def test_append_masked_array():
a = np.ma.masked_equal([1,2,3], value=2)
b = np.ma.masked_equal([4,3,2], value=2)
result = np.ma.append(a, b)
expected_data = [1, 2, 3, 4, 3, 2]
expected_mask = [False, True, False, False, False, True]
assert_array_equal(result.data, expected_data)
assert_array_equal(result.mask, expected_mask)
a = np.ma.masked_all((2,2))
b = np.ma.ones((3,1))
result = np.ma.append(a, b)
expected_data = [1] * 3
expected_mask = [True] * 4 + [False] * 3
assert_array_equal(result.data[-3], expected_data)
assert_array_equal(result.mask, expected_mask)
result = np.ma.append(a, b, axis=None)
assert_array_equal(result.data[-3], expected_data)
assert_array_equal(result.mask, expected_mask)
def test_append_masked_array_along_axis():
a = np.ma.masked_equal([1,2,3], value=2)
b = np.ma.masked_values([[4, 5, 6], [7, 8, 9]], 7)
# When `axis` is specified, `values` must have the correct shape.
assert_raises(ValueError, np.ma.append, a, b, axis=0)
result = np.ma.append(a[np.newaxis,:], b, axis=0)
expected = np.ma.arange(1, 10)
expected[[1, 6]] = np.ma.masked
expected = expected.reshape((3,3))
assert_array_equal(result.data, expected.data)
assert_array_equal(result.mask, expected.mask)
def test_default_fill_value_complex():
# regression test for Python 3, where 'unicode' was not defined
assert_(default_fill_value(1 + 1j) == 1.e20 + 0.0j)
###############################################################################
if __name__ == "__main__":
run_module_suite()
|
[
"numpy.ma.core.make_mask",
"numpy.ma.core.fix_invalid",
"numpy.arctan2",
"numpy.sum",
"numpy.ravel",
"numpy.ma.core.make_mask_descr",
"numpy.ma.core.empty_like",
"numpy.ma.core.greater_equal",
"numpy.ma.testutils.assert_equal_records",
"numpy.ones",
"numpy.argsort",
"numpy.arange",
"numpy.exp",
"numpy.ma.core.sometrue",
"numpy.ma.core.masked_greater",
"numpy.diag",
"numpy.conjugate",
"numpy.maximum.reduce",
"numpy.ma.core.reshape",
"numpy.may_share_memory",
"numpy.ma.core.empty",
"numpy.ma.__getattribute__",
"numpy.add.reduce",
"numpy.ma.core.masked_less_equal",
"numpy.identity",
"numpy.maximum.outer",
"warnings.catch_warnings",
"numpy.ma.core.arctan2",
"numpy.add.accumulate",
"numpy.ma.core.allclose",
"datetime.datetime.now",
"numpy.ma.core.MaskedArray.cumsum",
"numpy.less_equal",
"numpy.minimum",
"numpy.ma.core.less",
"numpy.ma.core.shape",
"numpy.ma.core.max",
"numpy.ma.core.less_equal",
"numpy.cosh",
"numpy.ma.core.divide",
"numpy.greater_equal",
"numpy.ma.core.count",
"numpy.ma.masked_values",
"numpy.ma.masked_all",
"numpy.ma.core.log",
"numpy.ma.core.identity",
"numpy.ma.core.tan",
"numpy.ma.core.flatten_structured_array",
"numpy.ma.core.ravel",
"numpy.ma.append",
"numpy.ma.array",
"numpy.ma.core.minimum_fill_value",
"numpy.ma.core.equal",
"numpy.array",
"numpy.ma.core.transpose",
"numpy.ma.core.abs",
"functools.reduce",
"numpy.ma.core.filled",
"numpy.sinh",
"numpy.minimum.outer",
"numpy.ma.core.minimum.outer",
"numpy.ma.core.allequal",
"numpy.ma.core.arctan",
"numpy.trace",
"numpy.ma.core.array",
"numpy.ma.core.sin",
"numpy.geterr",
"numpy.angle",
"numpy.ma.where",
"numpy.greater",
"numpy.isnan",
"numpy.ma.core.tanh",
"numpy.ma.core.anom",
"numpy.ma.testutils.fail_if_equal",
"numpy.transpose",
"itertools.product",
"numpy.arccos",
"numpy.ma.testutils.assert_",
"numpy.ma.testutils.assert_equal",
"copy.deepcopy",
"numpy.ma.core.outer",
"numpy.ma.compress",
"numpy.ma.core.exp",
"numpy.divide",
"numpy.ma.core.masked_equal",
"numpy.ma.arange",
"numpy.mod",
"numpy.not_equal",
"numpy.ma.core.maximum_fill_value",
"numpy.argwhere",
"numpy.ma.core.argsort",
"numpy.ma.core.mask_or",
"numpy.all",
"numpy.matrix",
"numpy.ma.masked_equal",
"numpy.dtype",
"numpy.ma.core.not_equal",
"numpy.find_common_type",
"numpy.ma.core.repeat",
"numpy.ma.core.MaskedArray",
"numpy.eye",
"numpy.ma.core.multiply.outer",
"numpy.ma.core.inner",
"numpy.ma.compressed",
"numpy.ma.core.arccos",
"numpy.maximum",
"numpy.ma.core.masked_less",
"numpy.ma.core.resize",
"numpy.empty",
"numpy.ma.core.sum",
"numpy.iinfo",
"numpy.shape",
"numpy.product",
"numpy.sin",
"numpy.ma.testutils.assert_mask_equal",
"numpy.ma.core.isMaskedArray",
"numpy.ndarray",
"numpy.ma.core.choose",
"numpy.ma.core.diag",
"warnings.simplefilter",
"numpy.ma.MaskedArray",
"numpy.equal",
"numpy.finfo",
"numpy.ma.core.sort",
"numpy.tan",
"numpy.ma.core.min",
"numpy.ma.core.mvoid",
"numpy.ma.core.masked_not_equal",
"numpy.ma.core.default_fill_value",
"numpy.ma.core.power",
"pickle.dumps",
"numpy.compat.asbytes",
"numpy.ma.core.cos",
"numpy.testing.assert_raises",
"numpy.ma.core.masked_print_option.set_display",
"numpy.ma.core.add.accumulate",
"numpy.ma.core.sinh",
"numpy.ma.core.sqrt",
"numpy.ma.core.masked_where",
"numpy.random.uniform",
"numpy.ma.core.cosh",
"numpy.log",
"numpy.ma.testutils.assert_almost_equal",
"numpy.ma.core.maximum",
"numpy.zeros",
"numpy.errstate",
"numpy.ma.core.conjugate",
"numpy.ma.core.where",
"numpy.ma.core.take",
"numpy.ma.core.putmask",
"numpy.compat.asbytes_nested",
"numpy.ma.core.getmask",
"numpy.ma.core.add",
"numpy.ma.core.greater",
"numpy.ma.core.arcsin",
"numpy.ma.core.mod",
"numpy.absolute",
"numpy.ma.core.add.reduce",
"numpy.ma.core.subtract",
"numpy.round",
"numpy.multiply",
"numpy.ma.testutils.assert_array_equal",
"numpy.testing.run_module_suite",
"numpy.ma.core.arccosh",
"numpy.ma.testutils.assert_not_equal",
"numpy.ma.core.getmaskarray",
"numpy.arcsin",
"numpy.ma.core.maximum.outer",
"numpy.ma.core.zeros",
"numpy.reshape",
"numpy.ma.core.log10",
"numpy.less",
"numpy.add",
"numpy.tanh",
"numpy.ma.masked_where",
"numpy.ma.core.masked_values",
"numpy.ma.core.put",
"numpy.asarray",
"numpy.ma.core.masked_array",
"numpy.ma.core.alltrue",
"numpy.ma.core.ones",
"numpy.sort",
"numpy.ma.core.angle",
"numpy.ma.core.asarray",
"numpy.cos",
"numpy.arctan",
"numpy.ma.core.concatenate",
"numpy.concatenate",
"numpy.ma.core.masked_greater_equal",
"numpy.ma.core.minimum",
"numpy.ma.core.product",
"numpy.ma.core.absolute",
"warnings.filterwarnings",
"numpy.seterr",
"numpy.subtract",
"numpy.ma.core.multiply",
"numpy.where",
"numpy.ma.ones",
"numpy.ma.core.flatten_mask",
"numpy.take",
"numpy.random.rand",
"numpy.ma.core.arange",
"numpy.sqrt"
] |
[((166569, 166613), 'numpy.ma.array', 'np.ma.array', (['[0, 1, 2, 3]'], {'mask': '[0, 0, 1, 0]'}), '([0, 1, 2, 3], mask=[0, 0, 1, 0])\n', (166580, 166613), True, 'import numpy as np\n'), ((166700, 166738), 'numpy.ma.masked_equal', 'np.ma.masked_equal', (['[1, 2, 3]'], {'value': '(2)'}), '([1, 2, 3], value=2)\n', (166718, 166738), True, 'import numpy as np\n'), ((166745, 166783), 'numpy.ma.masked_equal', 'np.ma.masked_equal', (['[4, 3, 2]'], {'value': '(2)'}), '([4, 3, 2], value=2)\n', (166763, 166783), True, 'import numpy as np\n'), ((166796, 166814), 'numpy.ma.append', 'np.ma.append', (['a', 'b'], {}), '(a, b)\n', (166808, 166814), True, 'import numpy as np\n'), ((166919, 166965), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['result.data', 'expected_data'], {}), '(result.data, expected_data)\n', (166937, 166965), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((166970, 167016), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['result.mask', 'expected_mask'], {}), '(result.mask, expected_mask)\n', (166988, 167016), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((167026, 167050), 'numpy.ma.masked_all', 'np.ma.masked_all', (['(2, 2)'], {}), '((2, 2))\n', (167042, 167050), True, 'import numpy as np\n'), ((167058, 167076), 'numpy.ma.ones', 'np.ma.ones', (['(3, 1)'], {}), '((3, 1))\n', (167068, 167076), True, 'import numpy as np\n'), ((167090, 167108), 'numpy.ma.append', 'np.ma.append', (['a', 'b'], {}), '(a, b)\n', (167102, 167108), True, 'import numpy as np\n'), ((167186, 167236), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['result.data[-3]', 'expected_data'], {}), '(result.data[-3], expected_data)\n', (167204, 167236), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((167241, 167287), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['result.mask', 'expected_mask'], {}), '(result.mask, expected_mask)\n', (167259, 167287), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((167302, 167331), 'numpy.ma.append', 'np.ma.append', (['a', 'b'], {'axis': 'None'}), '(a, b, axis=None)\n', (167314, 167331), True, 'import numpy as np\n'), ((167336, 167386), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['result.data[-3]', 'expected_data'], {}), '(result.data[-3], expected_data)\n', (167354, 167386), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((167391, 167437), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['result.mask', 'expected_mask'], {}), '(result.mask, expected_mask)\n', (167409, 167437), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((167491, 167529), 'numpy.ma.masked_equal', 'np.ma.masked_equal', (['[1, 2, 3]'], {'value': '(2)'}), '([1, 2, 3], value=2)\n', (167509, 167529), True, 'import numpy as np\n'), ((167536, 167582), 'numpy.ma.masked_values', 'np.ma.masked_values', (['[[4, 5, 6], [7, 8, 9]]', '(7)'], {}), '([[4, 5, 6], [7, 8, 9]], 7)\n', (167555, 167582), True, 'import numpy as np\n'), ((167658, 167711), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'np.ma.append', 'a', 'b'], {'axis': '(0)'}), '(ValueError, np.ma.append, a, b, axis=0)\n', (167671, 167711), False, 'from numpy.testing import TestCase, run_module_suite, assert_raises\n'), ((167726, 167767), 'numpy.ma.append', 'np.ma.append', (['a[np.newaxis, :]', 'b'], {'axis': '(0)'}), '(a[np.newaxis, :], b, axis=0)\n', (167738, 167767), True, 'import numpy as np\n'), ((167782, 167801), 'numpy.ma.arange', 'np.ma.arange', (['(1)', '(10)'], {}), '(1, 10)\n', (167794, 167801), True, 'import numpy as np\n'), ((167881, 167927), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['result.data', 'expected.data'], {}), '(result.data, expected.data)\n', (167899, 167927), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((167932, 167978), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['result.mask', 'expected.mask'], {}), '(result.mask, expected.mask)\n', (167950, 167978), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((168256, 168274), 'numpy.testing.run_module_suite', 'run_module_suite', ([], {}), '()\n', (168272, 168274), False, 'from numpy.testing import TestCase, run_module_suite, assert_raises\n'), ((2048, 2127), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0]'], {}), '([1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0])\n', (2056, 2127), True, 'import numpy as np\n'), ((2127, 2202), 'numpy.array', 'np.array', (['[5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0]'], {}), '([5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0])\n', (2135, 2202), True, 'import numpy as np\n'), ((2322, 2346), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': 'm1'}), '(x, mask=m1)\n', (2334, 2346), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((2360, 2384), 'numpy.ma.core.masked_array', 'masked_array', (['y'], {'mask': 'm2'}), '(y, mask=m2)\n', (2372, 2384), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((2397, 2428), 'numpy.array', 'np.array', (['[-0.5, 0.0, 0.5, 0.8]'], {}), '([-0.5, 0.0, 0.5, 0.8])\n', (2405, 2428), True, 'import numpy as np\n'), ((2438, 2472), 'numpy.ma.core.masked_array', 'masked_array', (['z'], {'mask': '[0, 1, 0, 0]'}), '(z, mask=[0, 1, 0, 0])\n', (2450, 2472), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((2486, 2508), 'numpy.where', 'np.where', (['m1', '(1e+20)', 'x'], {}), '(m1, 1e+20, x)\n', (2494, 2508), True, 'import numpy as np\n'), ((2692, 2708), 'numpy.ma.core.array', 'array', (['[1, 3, 2]'], {}), '([1, 3, 2])\n', (2697, 2708), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((2721, 2753), 'numpy.ma.core.array', 'array', (['[1, 3, 2]'], {'mask': '[1, 0, 1]'}), '([1, 3, 2], mask=[1, 0, 1])\n', (2726, 2753), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((2762, 2785), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.ndim', '(1)'], {}), '(a.ndim, 1)\n', (2774, 2785), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((2794, 2817), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.ndim', '(1)'], {}), '(b.ndim, 1)\n', (2806, 2817), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((2826, 2849), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.size', '(3)'], {}), '(a.size, 3)\n', (2838, 2849), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((2858, 2881), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.size', '(3)'], {}), '(b.size, 3)\n', (2870, 2881), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((2890, 2917), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.shape', '(3,)'], {}), '(a.shape, (3,))\n', (2902, 2917), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((2926, 2953), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.shape', '(3,)'], {}), '(b.shape, (3,))\n', (2938, 2953), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((3029, 3044), 'numpy.ma.core.masked_array', 'masked_array', (['(0)'], {}), '(0)\n', (3041, 3044), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((3091, 3117), 'numpy.ma.core.masked_array', 'masked_array', (['(0)'], {'mask': '(True)'}), '(0, mask=True)\n', (3103, 3117), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((3185, 3212), 'numpy.ma.core.masked_array', 'masked_array', (['(0)'], {'mask': '(False)'}), '(0, mask=False)\n', (3197, 3212), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((3259, 3275), 'numpy.ma.core.array', 'array', (['(0)'], {'mask': '(1)'}), '(0, mask=1)\n', (3264, 3275), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((3760, 3785), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm.shape', 's'], {}), '(xm.shape, s)\n', (3772, 3785), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((3794, 3825), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm.dtype', 'x.dtype'], {}), '(xm.dtype, x.dtype)\n', (3806, 3825), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((3834, 3865), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['zm.dtype', 'z.dtype'], {}), '(zm.dtype, z.dtype)\n', (3846, 3865), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((4007, 4033), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['xm', 'xf'], {}), '(xm, xf)\n', (4025, 4033), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((4092, 4117), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['x', 'xm'], {}), '(x, xm)\n', (4110, 4117), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((5645, 5669), 'numpy.ma.core.concatenate', 'concatenate', (['(xm, ym)', '(1)'], {}), '((xm, ym), 1)\n', (5656, 5669), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((5809, 5817), 'numpy.ma.core.zeros', 'zeros', (['(2)'], {}), '(2)\n', (5814, 5817), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((5877, 5896), 'numpy.ma.core.concatenate', 'concatenate', (['(x, y)'], {}), '((x, y))\n', (5888, 5896), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((5905, 5940), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['z', '[0, 0, 1, 1]'], {}), '(z, [0, 0, 1, 1])\n', (5923, 5940), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((5949, 6004), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['z.mask', '[False, False, False, True]'], {}), '(z.mask, [False, False, False, True])\n', (5967, 6004), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((6017, 6036), 'numpy.ma.core.concatenate', 'concatenate', (['(y, x)'], {}), '((y, x))\n', (6028, 6036), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((6045, 6080), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['z', '[1, 1, 0, 0]'], {}), '(z, [1, 1, 0, 0])\n', (6063, 6080), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((6089, 6144), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['z.mask', '[False, True, False, False]'], {}), '(z.mask, [False, True, False, False])\n', (6107, 6144), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((6430, 6463), 'numpy.ma.core.concatenate', 'concatenate', (['[data[:5], data[5:]]'], {}), '([data[:5], data[5:]])\n', (6441, 6463), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((6472, 6504), 'numpy.ma.testutils.assert_equal_records', 'assert_equal_records', (['test', 'data'], {}), '(test, data)\n', (6492, 6504), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((6586, 6627), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]', 'ndmin': '(2)'}), '([1, 2, 3], mask=[1, 0, 0], ndmin=2)\n', (6591, 6627), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((6636, 6665), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.shape', '(1, 3)'], {}), '(x.shape, (1, 3))\n', (6648, 6665), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((6674, 6708), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._data', '[[1, 2, 3]]'], {}), '(x._data, [[1, 2, 3]])\n', (6686, 6708), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((6717, 6751), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._mask', '[[1, 0, 0]]'], {}), '(x._mask, [[1, 0, 0]])\n', (6729, 6751), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((6881, 6897), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (6886, 6897), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((6934, 6964), 'numpy.ma.core.array', 'array', (['x'], {'ndmin': '(2)', 'dtype': 'float'}), '(x, ndmin=2, dtype=float)\n', (6939, 6964), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((6973, 7009), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.shape', 'x._mask.shape'], {}), '(x.shape, x._mask.shape)\n', (6985, 7009), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((7018, 7056), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.shape', 'xx._mask.shape'], {}), '(xx.shape, xx._mask.shape)\n', (7030, 7056), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((7190, 7213), 'numpy.ma.core.arange', 'arange', (['(24)'], {'dtype': 'float'}), '(24, dtype=float)\n', (7196, 7213), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7264, 7281), 'numpy.ma.core.MaskedArray', 'MaskedArray', (['data'], {}), '(data)\n', (7275, 7281), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7290, 7325), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['dma_1.mask', 'data.mask'], {}), '(dma_1.mask, data.mask)\n', (7302, 7325), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((7342, 7360), 'numpy.ma.core.MaskedArray', 'MaskedArray', (['dma_1'], {}), '(dma_1)\n', (7353, 7360), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7369, 7405), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['dma_2.mask', 'dma_1.mask'], {}), '(dma_2.mask, dma_1.mask)\n', (7381, 7405), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((7422, 7463), 'numpy.ma.core.MaskedArray', 'MaskedArray', (['dma_1'], {'mask': '([1, 0, 0, 0] * 6)'}), '(dma_1, mask=[1, 0, 0, 0] * 6)\n', (7433, 7463), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7472, 7509), 'numpy.ma.testutils.fail_if_equal', 'fail_if_equal', (['dma_3.mask', 'dma_1.mask'], {}), '(dma_3.mask, dma_1.mask)\n', (7485, 7509), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((7523, 7550), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '(True)'}), '([1, 2, 3], mask=True)\n', (7528, 7550), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7559, 7600), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._mask', '[True, True, True]'], {}), '(x._mask, [True, True, True])\n', (7571, 7600), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((7613, 7641), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '(False)'}), '([1, 2, 3], mask=False)\n', (7618, 7641), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7650, 7694), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._mask', '[False, False, False]'], {}), '(x._mask, [False, False, False])\n', (7662, 7694), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((7707, 7749), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': 'x._mask', 'copy': '(False)'}), '([1, 2, 3], mask=x._mask, copy=False)\n', (7712, 7749), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7815, 7856), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': 'x._mask', 'copy': '(True)'}), '([1, 2, 3], mask=x._mask, copy=True)\n', (7820, 7856), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((8109, 8128), 'numpy.ma.core.array', 'array', (['(x, x[::-1])'], {}), '((x, x[::-1]))\n', (8114, 8128), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((8137, 8191), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['data', '[[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]]'], {}), '(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])\n', (8149, 8191), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((8200, 8260), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['data._mask', '[[1, 0, 0, 0, 0], [0, 0, 0, 0, 1]]'], {}), '(data._mask, [[1, 0, 0, 0, 0], [0, 0, 0, 0, 1]])\n', (8212, 8260), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((8301, 8320), 'numpy.ma.core.array', 'array', (['(x, x[::-1])'], {}), '((x, x[::-1]))\n', (8306, 8320), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((8329, 8383), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['data', '[[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]]'], {}), '(data, [[0, 1, 2, 3, 4], [4, 3, 2, 1, 0]])\n', (8341, 8383), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((8586, 8597), 'numpy.ma.core.asarray', 'asarray', (['xm'], {}), '(xm)\n', (8593, 8597), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((8606, 8639), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xmm._data', 'xm._data'], {}), '(xmm._data, xm._data)\n', (8618, 8639), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((8648, 8681), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xmm._mask', 'xm._mask'], {}), '(xmm._mask, xm._mask)\n', (8660, 8681), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((8690, 8733), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xmm.fill_value', 'xm.fill_value'], {}), '(xmm.fill_value, xm.fill_value)\n', (8702, 8733), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((8742, 8783), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xmm._hardmask', 'xm._hardmask'], {}), '(xmm._hardmask, xm._hardmask)\n', (8754, 8783), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((8941, 8951), 'numpy.ma.core.asarray', 'asarray', (['m'], {}), '(m)\n', (8948, 8951), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((9159, 9180), 'numpy.ma.core.asarray', 'asarray', (['m'], {'order': '"""C"""'}), "(m, order='C')\n", (9166, 9180), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((9654, 9663), 'numpy.ma.core.arange', 'arange', (['(6)'], {}), '(6)\n', (9660, 9663), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((9912, 9934), 'numpy.ma.core.empty', 'empty', (['(1)'], {'dtype': 'object'}), '(1, dtype=object)\n', (9917, 9934), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((9988, 10009), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a[0]', 'x'], {}), '(a[0], x)\n', (10000, 10009), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10083, 10106), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (10104, 10106), False, 'import datetime\n'), ((10245, 10267), 'numpy.array', 'np.array', (['[1, 2, 4, 3]'], {}), '([1, 2, 4, 3])\n', (10253, 10267), True, 'import numpy as np\n'), ((10281, 10309), 'numpy.ma.core.array', 'array', (['x1'], {'mask': '[1, 0, 0, 0]'}), '(x1, mask=[1, 0, 0, 0])\n', (10286, 10309), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((10323, 10351), 'numpy.ma.core.array', 'array', (['x1'], {'mask': '[0, 1, 0, 1]'}), '(x1, mask=[0, 1, 0, 1])\n', (10328, 10351), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((10365, 10374), 'numpy.ma.core.array', 'array', (['x1'], {}), '(x1)\n', (10370, 10374), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((10606, 10629), 'numpy.ma.testutils.assert_', 'assert_', (['(x1[1] == x2[1])'], {}), '(x1[1] == x2[1])\n', (10613, 10629), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10638, 10662), 'numpy.ma.testutils.assert_', 'assert_', (['(x2[0] is masked)'], {}), '(x2[0] is masked)\n', (10645, 10662), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10671, 10697), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[2]', 'x2[2]'], {}), '(x1[2], x2[2])\n', (10683, 10697), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10706, 10736), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[2:5]', 'x2[2:5]'], {}), '(x1[2:5], x2[2:5])\n', (10718, 10736), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10745, 10771), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[:]', 'x2[:]'], {}), '(x1[:], x2[:])\n', (10757, 10771), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10780, 10808), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[1:]', 'x3[1:]'], {}), '(x1[1:], x3[1:])\n', (10792, 10808), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10853, 10873), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (10865, 10873), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10924, 10944), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (10936, 10944), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((10976, 10996), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (10988, 10996), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((11030, 11050), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (11042, 11050), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((11169, 11209), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3, 4]', '[0, 1, 1, 0]'], {}), '([1, 2, 3, 4], [0, 1, 1, 0])\n', (11181, 11209), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11286, 11326), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3, 4]', '[0, 1, 1, 0]'], {}), '([1, 2, 3, 4], [0, 1, 1, 0])\n', (11298, 11326), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11483, 11505), 'numpy.ma.core.masked_values', 'masked_values', (['x1', '(3.0)'], {}), '(x1, 3.0)\n', (11496, 11505), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11514, 11534), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (11526, 11534), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((11612, 11644), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(3.0)', 'x2.fill_value'], {}), '(3.0, x2.fill_value)\n', (11624, 11644), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((11658, 11691), 'numpy.ma.core.array', 'array', (["[1, 'hello', 2, 3]", 'object'], {}), "([1, 'hello', 2, 3], object)\n", (11663, 11691), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11705, 11741), 'numpy.array', 'np.array', (["[1, 'hello', 2, 3]", 'object'], {}), "([1, 'hello', 2, 3], object)\n", (11713, 11741), True, 'import numpy as np\n'), ((11860, 11880), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['s1', 's2'], {}), '(s1, s2)\n', (11872, 11880), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((11889, 11919), 'numpy.ma.testutils.assert_', 'assert_', (['(x1[1:1].shape == (0,))'], {}), '(x1[1:1].shape == (0,))\n', (11896, 11919), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12011, 12044), 'numpy.matrix', 'np.matrix', (['[[1, 2, 3], [4, 3, 2]]'], {}), '([[1, 2, 3], [4, 3, 2]])\n', (12020, 12044), True, 'import numpy as np\n'), ((12058, 12096), 'numpy.ma.core.array', 'array', (['x1'], {'mask': '[[1, 0, 0], [0, 1, 0]]'}), '(x1, mask=[[1, 0, 0], [0, 1, 0]])\n', (12063, 12096), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((12110, 12148), 'numpy.ma.core.array', 'array', (['x1'], {'mask': '[[0, 1, 0], [1, 0, 0]]'}), '(x1, mask=[[0, 1, 0], [1, 0, 0]])\n', (12115, 12148), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((12162, 12171), 'numpy.ma.core.array', 'array', (['x1'], {}), '(x1)\n', (12167, 12171), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((12350, 12379), 'numpy.ma.testutils.assert_', 'assert_', (['(x1[1, 0] == x2[1, 0])'], {}), '(x1[1, 0] == x2[1, 0])\n', (12357, 12379), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12388, 12415), 'numpy.ma.testutils.assert_', 'assert_', (['(x2[1, 1] is masked)'], {}), '(x2[1, 1] is masked)\n', (12395, 12415), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12424, 12456), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[0, 2]', 'x2[0, 2]'], {}), '(x1[0, 2], x2[0, 2])\n', (12436, 12456), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12465, 12499), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[0, 1:]', 'x2[0, 1:]'], {}), '(x1[0, 1:], x2[0, 1:])\n', (12477, 12499), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12508, 12540), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[:, 2]', 'x2[:, 2]'], {}), '(x1[:, 2], x2[:, 2])\n', (12520, 12540), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12549, 12575), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[:]', 'x2[:]'], {}), '(x1[:], x2[:])\n', (12561, 12575), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12584, 12612), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1[1:]', 'x3[1:]'], {}), '(x1[1:], x3[1:])\n', (12596, 12612), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12663, 12683), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (12675, 12683), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12738, 12758), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (12750, 12758), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12793, 12813), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (12805, 12813), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((12849, 12869), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (12861, 12869), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((13016, 13050), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]', '[1, 1, 0]'], {}), '([1, 2, 3], [1, 1, 0])\n', (13028, 13050), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13190, 13224), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]', '[1, 1, 0]'], {}), '([1, 2, 3], [1, 1, 0])\n', (13202, 13224), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13392, 13414), 'numpy.ma.core.masked_values', 'masked_values', (['x1', '(3.0)'], {}), '(x1, 3.0)\n', (13405, 13414), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13423, 13443), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x1', 'x2'], {}), '(x1, x2)\n', (13435, 13443), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((13521, 13553), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(3.0)', 'x2.fill_value'], {}), '(3.0, x2.fill_value)\n', (13533, 13553), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((13681, 13693), 'numpy.ma.core.make_mask', 'make_mask', (['n'], {}), '(n)\n', (13690, 13693), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13707, 13719), 'numpy.ma.core.make_mask', 'make_mask', (['m'], {}), '(m)\n', (13716, 13719), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13766, 13786), 'numpy.ma.core.make_mask', 'make_mask', (['m'], {'copy': '(1)'}), '(m, copy=1)\n', (13775, 13786), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13838, 13850), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (13847, 13850), True, 'import numpy as np\n'), ((13864, 13881), 'numpy.ma.core.array', 'array', (['x1'], {'mask': 'm'}), '(x1, mask=m)\n', (13869, 13881), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13890, 13956), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y1._data.__array_interface__', 'x1.__array_interface__'], {}), '(y1._data.__array_interface__, x1.__array_interface__)\n', (13902, 13956), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((14012, 14077), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y1._mask.__array_interface__', 'm.__array_interface__'], {}), '(y1._mask.__array_interface__, m.__array_interface__)\n', (14024, 14077), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((14093, 14102), 'numpy.ma.core.array', 'array', (['y1'], {}), '(y1)\n', (14098, 14102), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14273, 14290), 'numpy.ma.core.array', 'array', (['x1'], {'mask': 'm'}), '(x1, mask=m)\n', (14278, 14290), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14693, 14716), 'numpy.ma.core.array', 'array', (['(x1 * 1.0)'], {'mask': 'm'}), '(x1 * 1.0, mask=m)\n', (14698, 14716), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14793, 14802), 'numpy.ma.core.arange', 'arange', (['(4)'], {}), '(4)\n', (14799, 14802), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14839, 14855), 'numpy.ma.core.resize', 'resize', (['x4', '(8,)'], {}), '(x4, (8,))\n', (14845, 14855), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14977, 15009), 'numpy.ma.core.repeat', 'repeat', (['x4', '(2, 2, 2, 2)'], {'axis': '(0)'}), '(x4, (2, 2, 2, 2), axis=0)\n', (14983, 15009), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((15018, 15060), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y5', '[0, 0, 1, 1, 2, 2, 3, 3]'], {}), '(y5, [0, 0, 1, 1, 2, 2, 3, 3])\n', (15030, 15060), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15074, 15095), 'numpy.ma.core.repeat', 'repeat', (['x4', '(2)'], {'axis': '(0)'}), '(x4, 2, axis=0)\n', (15080, 15095), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((15104, 15124), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y5', 'y6'], {}), '(y5, y6)\n', (15116, 15124), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15178, 15198), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y5', 'y7'], {}), '(y5, y7)\n', (15190, 15198), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15236, 15256), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y5', 'y8'], {}), '(y5, y8)\n', (15248, 15256), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15289, 15321), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y9._data', 'x4._data'], {}), '(y9._data, x4._data)\n', (15301, 15321), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15330, 15362), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y9._mask', 'x4._mask'], {}), '(y9._mask, x4._mask)\n', (15342, 15362), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15376, 15415), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]'], {'mask': '[0, 1, 0]'}), '([1, 2, 3], mask=[0, 1, 0])\n', (15388, 15415), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((15463, 15478), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {}), '(x)\n', (15475, 15478), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((15487, 15541), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y._data.ctypes.data', 'x._data.ctypes.data'], {}), '(y._data.ctypes.data, x._data.ctypes.data)\n', (15499, 15541), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15550, 15604), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y._mask.ctypes.data', 'x._mask.ctypes.data'], {}), '(y._mask.ctypes.data, x._mask.ctypes.data)\n', (15562, 15604), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15617, 15643), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'copy': '(True)'}), '(x, copy=True)\n', (15629, 15643), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((15652, 15710), 'numpy.ma.testutils.assert_not_equal', 'assert_not_equal', (['y._data.ctypes.data', 'x._data.ctypes.data'], {}), '(y._data.ctypes.data, x._data.ctypes.data)\n', (15668, 15710), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15719, 15777), 'numpy.ma.testutils.assert_not_equal', 'assert_not_equal', (['y._mask.ctypes.data', 'x._mask.ctypes.data'], {}), '(y._mask.ctypes.data, x._mask.ctypes.data)\n', (15735, 15777), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((15896, 15918), 'numpy.ma.array', 'np.ma.array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (15907, 15918), True, 'import numpy as np\n'), ((15931, 15953), 'numpy.ma.array', 'np.ma.array', (['[4, 5, 6]'], {}), '([4, 5, 6])\n', (15942, 15953), True, 'import numpy as np\n'), ((16125, 16168), 'numpy.ma.core.array', 'array', (['[0, 1, 2]'], {'mask': '[False, True, False]'}), '([0, 1, 2], mask=[False, True, False])\n', (16130, 16168), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((16186, 16197), 'copy.deepcopy', 'deepcopy', (['a'], {}), '(a)\n', (16194, 16197), False, 'from copy import deepcopy\n'), ((16206, 16239), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['copied.mask', 'a.mask'], {}), '(copied.mask, a.mask)\n', (16218, 16239), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((16327, 16363), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['copied.mask', '[0, 0, 0]'], {}), '(copied.mask, [0, 0, 0])\n', (16339, 16363), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((16372, 16403), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[0, 1, 0]'], {}), '(a.mask, [0, 1, 0])\n', (16384, 16403), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((16422, 16433), 'copy.deepcopy', 'deepcopy', (['a'], {}), '(a)\n', (16430, 16433), False, 'from copy import deepcopy\n'), ((16442, 16475), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['copied.mask', 'a.mask'], {}), '(copied.mask, a.mask)\n', (16454, 16475), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((16515, 16551), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['copied.mask', '[0, 0, 0]'], {}), '(copied.mask, [0, 0, 0])\n', (16527, 16551), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((16560, 16591), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[0, 1, 0]'], {}), '(a.mask, [0, 1, 0])\n', (16572, 16591), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((16634, 16677), 'numpy.ma.core.array', 'array', (['[0, 1, 2]'], {'mask': '[False, True, False]'}), '([0, 1, 2], mask=[False, True, False])\n', (16639, 16677), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((16934, 16952), 'numpy.ma.arange', 'np.ma.arange', (['(2000)'], {}), '(2000)\n', (16946, 16952), True, 'import numpy as np\n'), ((17295, 17305), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (17301, 17305), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((17409, 17447), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a_pickled._mask', 'a._mask'], {}), '(a_pickled._mask, a._mask)\n', (17421, 17447), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((17456, 17494), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a_pickled._data', 'a._data'], {}), '(a_pickled._data, a._data)\n', (17468, 17494), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((17503, 17542), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a_pickled.fill_value', '(999)'], {}), '(a_pickled.fill_value, 999)\n', (17515, 17542), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((17759, 17797), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a_pickled._mask', 'a._mask'], {}), '(a_pickled._mask, a._mask)\n', (17771, 17797), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((17806, 17832), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a_pickled', 'a'], {}), '(a_pickled, a)\n', (17818, 17832), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((18061, 18111), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mc_pickled._baseclass', 'mc._baseclass'], {}), '(mc_pickled._baseclass, mc._baseclass)\n', (18073, 18111), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((18120, 18160), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mc_pickled._mask', 'mc._mask'], {}), '(mc_pickled._mask, mc._mask)\n', (18132, 18160), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((18169, 18209), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mc_pickled._data', 'mc._data'], {}), '(mc_pickled._data, mc._data)\n', (18181, 18209), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((18309, 18397), 'numpy.ma.core.array', 'array', (['[(1, 1.0), (2, 2.0)]'], {'mask': '[(0, 0), (0, 1)]', 'dtype': "[('a', int), ('b', float)]"}), "([(1, 1.0), (2, 2.0)], mask=[(0, 0), (0, 1)], dtype=[('a', int), ('b',\n float)])\n", (18314, 18397), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((18462, 18500), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a_pickled._mask', 'a._mask'], {}), '(a_pickled._mask, a._mask)\n', (18474, 18500), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((18509, 18535), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a_pickled', 'a'], {}), '(a_pickled, a)\n', (18521, 18535), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((18640, 18650), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (18646, 18650), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((18746, 18767), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'b'], {}), '(test, b)\n', (18758, 18767), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((18885, 18901), 'numpy.ma.core.array', 'array', (['[1, 3, 2]'], {}), '([1, 3, 2])\n', (18890, 18901), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((18914, 18946), 'numpy.ma.core.array', 'array', (['[1, 3, 2]'], {'mask': '[1, 0, 1]'}), '([1, 3, 2], mask=[1, 0, 1])\n', (18919, 18946), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((18955, 18983), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a[0].shape', '()'], {}), '(a[0].shape, ())\n', (18967, 18983), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((18992, 19020), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b[0].shape', '()'], {}), '(b[0].shape, ())\n', (19004, 19020), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((19029, 19057), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b[1].shape', '()'], {}), '(b[1].shape, ())\n', (19041, 19057), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((19546, 19578), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]'}), '([1, 2, 3], mask=[1, 0, 0])\n', (19551, 19578), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((19937, 19947), 'numpy.ma.core.arange', 'arange', (['(20)'], {}), '(20)\n', (19943, 19947), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20007, 20029), 'numpy.ma.testutils.assert_', 'assert_', (['(x[1, 0] == 12)'], {}), '(x[1, 0] == 12)\n', (20014, 20029), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20062, 20085), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z.real', 'x'], {}), '(z.real, x)\n', (20074, 20085), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20094, 20122), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z.imag', '(10 * x)'], {}), '(z.imag, 10 * x)\n', (20106, 20122), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20221, 20231), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (20227, 20231), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20442, 20460), 'numpy.ma.core.masked_where', 'masked_where', (['c', 'x'], {}), '(c, x)\n', (20454, 20460), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20469, 20496), 'numpy.ma.testutils.assert_', 'assert_', (['(z.dtype is x.dtype)'], {}), '(z.dtype is x.dtype)\n', (20476, 20496), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20505, 20528), 'numpy.ma.testutils.assert_', 'assert_', (['(z[3] is masked)'], {}), '(z[3] is masked)\n', (20512, 20528), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20537, 20564), 'numpy.ma.testutils.assert_', 'assert_', (['(z[4] is not masked)'], {}), '(z[4] is not masked)\n', (20544, 20564), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20573, 20600), 'numpy.ma.testutils.assert_', 'assert_', (['(z[7] is not masked)'], {}), '(z[7] is not masked)\n', (20580, 20600), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20609, 20632), 'numpy.ma.testutils.assert_', 'assert_', (['(z[8] is masked)'], {}), '(z[8] is masked)\n', (20616, 20632), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20641, 20664), 'numpy.ma.testutils.assert_', 'assert_', (['(z[9] is masked)'], {}), '(z[9] is masked)\n', (20648, 20664), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20673, 20691), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', 'z'], {}), '(x, z)\n', (20685, 20691), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20775, 20807), 'numpy.ma.core.array', 'array', (['[1.0, 2.0, 3.0, 4.0, 5.0]'], {}), '([1.0, 2.0, 3.0, 4.0, 5.0])\n', (20780, 20807), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20815, 20837), 'numpy.ma.core.array', 'array', (['[1, 1, 1, 0, 0]'], {}), '([1, 1, 1, 0, 0])\n', (20820, 20837), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20872, 20887), 'numpy.ma.core.where', 'where', (['c', 'x', '(-x)'], {}), '(c, x, -x)\n', (20877, 20887), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20896, 20938), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[1.0, 2.0, 0.0, -4.0, -5]'], {}), '(z, [1.0, 2.0, 0.0, -4.0, -5])\n', (20908, 20938), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((20969, 20984), 'numpy.ma.core.where', 'where', (['c', 'x', '(-x)'], {}), '(c, x, -x)\n', (20974, 20984), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20993, 21035), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[1.0, 2.0, 0.0, -4.0, -5]'], {}), '(z, [1.0, 2.0, 0.0, -4.0, -5])\n', (21005, 21035), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((21040, 21063), 'numpy.ma.testutils.assert_', 'assert_', (['(z[0] is masked)'], {}), '(z[0] is masked)\n', (21047, 21063), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((21072, 21099), 'numpy.ma.testutils.assert_', 'assert_', (['(z[1] is not masked)'], {}), '(z[1] is not masked)\n', (21079, 21099), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((21108, 21131), 'numpy.ma.testutils.assert_', 'assert_', (['(z[2] is masked)'], {}), '(z[2] is masked)\n', (21115, 21131), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((21221, 21243), 'numpy.ma.core.array', 'array', (['[10]'], {'mask': '(True)'}), '([10], mask=True)\n', (21226, 21243), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((21260, 21271), 'numpy.ma.core.array', 'array', (['[20]'], {}), '([20])\n', (21265, 21271), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((21337, 21362), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['atest', '[20]'], {}), '(atest, [20])\n', (21349, 21362), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((21418, 21448), 'numpy.ma.masked_all', 'np.ma.masked_all', (['(1)'], {'dtype': '"""O"""'}), "(1, dtype='O')\n", (21434, 21448), True, 'import numpy as np\n'), ((21594, 21660), 'numpy.ma.core.array', 'array', (['[(1, 1, 1)]'], {'dtype': "[('i', int), ('s', '|S8'), ('f', float)]"}), "([(1, 1, 1)], dtype=[('i', int), ('s', '|S8'), ('f', float)])\n", (21599, 21660), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((22190, 22234), 'numpy.ma.core.mvoid', 'mvoid', (['(1, 2.0)'], {'mask': '[(0, 1)]', 'dtype': 'ndtype'}), '((1, 2.0), mask=[(0, 1)], dtype=ndtype)\n', (22195, 22234), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((22748, 22833), 'numpy.ma.core.array', 'array', (['[(1, (1, 1)), (2, (2, 2))]'], {'mask': '[(0, (1, 0)), (0, (0, 1))]', 'dtype': 'ndtype'}), '([(1, (1, 1)), (2, (2, 2))], mask=[(0, (1, 0)), (0, (0, 1))], dtype=ndtype\n )\n', (22753, 22833), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((22892, 22942), 'numpy.array', 'np.array', (['[(1, (0, 1)), (2, (2, 0))]'], {'dtype': 'ndtype'}), '([(1, (0, 1)), (2, (2, 0))], dtype=ndtype)\n', (22900, 22942), True, 'import numpy as np\n'), ((22951, 22978), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (22963, 22978), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((23030, 23076), 'numpy.array', 'np.array', (['[(0, 1), (2, 0)]'], {'dtype': "a['B'].dtype"}), "([(0, 1), (2, 0)], dtype=a['B'].dtype)\n", (23038, 23076), True, 'import numpy as np\n'), ((23085, 23112), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (23097, 23112), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((24046, 24075), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'dtype': 'float'}), '([1, 2, 3], dtype=float)\n', (24051, 24075), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((24142, 24181), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["y._optinfo['info']", '"""???"""'], {}), "(y._optinfo['info'], '???')\n", (24154, 24181), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((24225, 24264), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["x._optinfo['info']", '"""???"""'], {}), "(x._optinfo['info'], '???')\n", (24237, 24264), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((24381, 24438), 'numpy.dtype', 'np.dtype', (["[('x', int), ('y', [('t', int), ('s', float)])]"], {}), "([('x', int), ('y', [('t', int), ('s', float)])])\n", (24389, 24438), True, 'import numpy as np\n'), ((24454, 24546), 'numpy.ma.core.array', 'array', (['[(1, (2, 3.0)), (4, (5, 6.0))]'], {'mask': '[(1, (0, 1)), (0, (1, 0))]', 'dtype': 'fancydtype'}), '([(1, (2, 3.0)), (4, (5, 6.0))], mask=[(1, (0, 1)), (0, (1, 0))],\n dtype=fancydtype)\n', (24459, 24546), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((24748, 24918), 'numpy.ma.core.masked_array', 'masked_array', ([], {'data': '(0, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], 0.0)', 'mask': '(False, [[True, False, True], [False, False, True]], False)', 'dtype': '"""int, (2,3)float, float"""'}), "(data=(0, [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]], 0.0), mask=(False,\n [[True, False, True], [False, False, True]], False), dtype=\n 'int, (2,3)float, float')\n", (24760, 24918), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((25410, 25450), 'numpy.array', 'np.array', (['[(1, 1), (2, 2)]'], {'dtype': 'ndtype'}), '([(1, 1), (2, 2)], dtype=ndtype)\n', (25418, 25450), True, 'import numpy as np\n'), ((25466, 25493), 'numpy.ma.core.flatten_structured_array', 'flatten_structured_array', (['a'], {}), '(a)\n', (25490, 25493), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((25512, 25562), 'numpy.array', 'np.array', (['[[1.0, 1.0], [2.0, 2.0]]'], {'dtype': 'np.float'}), '([[1.0, 1.0], [2.0, 2.0]], dtype=np.float)\n', (25520, 25562), True, 'import numpy as np\n'), ((25567, 25594), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (25579, 25594), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((25603, 25642), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'control.dtype'], {}), '(test.dtype, control.dtype)\n', (25615, 25642), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((25681, 25741), 'numpy.ma.core.array', 'array', (['[(1, 1), (2, 2)]'], {'mask': '[(0, 1), (1, 0)]', 'dtype': 'ndtype'}), '([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)\n', (25686, 25741), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((25757, 25784), 'numpy.ma.core.flatten_structured_array', 'flatten_structured_array', (['a'], {}), '(a)\n', (25781, 25784), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((25803, 25873), 'numpy.ma.core.array', 'array', (['[[1.0, 1.0], [2.0, 2.0]]'], {'mask': '[[0, 1], [1, 0]]', 'dtype': 'np.float'}), '([[1.0, 1.0], [2.0, 2.0]], mask=[[0, 1], [1, 0]], dtype=np.float)\n', (25808, 25873), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((25902, 25929), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (25914, 25929), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((25938, 25977), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'control.dtype'], {}), '(test.dtype, control.dtype)\n', (25950, 25977), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((25986, 26023), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (25998, 26023), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((26151, 26239), 'numpy.ma.core.array', 'array', (['[(1, (1, 1.1)), (2, (2, 2.2))]'], {'mask': '[(0, (1, 0)), (1, (0, 1))]', 'dtype': 'ndtype'}), '([(1, (1, 1.1)), (2, (2, 2.2))], mask=[(0, (1, 0)), (1, (0, 1))],\n dtype=ndtype)\n', (26156, 26239), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((26269, 26296), 'numpy.ma.core.flatten_structured_array', 'flatten_structured_array', (['a'], {}), '(a)\n', (26293, 26296), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((26315, 26405), 'numpy.ma.core.array', 'array', (['[[1.0, 1.0, 1.1], [2.0, 2.0, 2.2]]'], {'mask': '[[0, 1, 0], [1, 0, 1]]', 'dtype': 'np.float'}), '([[1.0, 1.0, 1.1], [2.0, 2.0, 2.2]], mask=[[0, 1, 0], [1, 0, 1]],\n dtype=np.float)\n', (26320, 26405), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((26430, 26457), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (26442, 26457), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((26466, 26505), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'control.dtype'], {}), '(test.dtype, control.dtype)\n', (26478, 26505), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((26514, 26551), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (26526, 26551), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((26644, 26688), 'numpy.array', 'np.array', (['[[(1, 1)], [(2, 2)]]'], {'dtype': 'ndtype'}), '([[(1, 1)], [(2, 2)]], dtype=ndtype)\n', (26652, 26688), True, 'import numpy as np\n'), ((26708, 26735), 'numpy.ma.core.flatten_structured_array', 'flatten_structured_array', (['a'], {}), '(a)\n', (26732, 26735), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((26754, 26808), 'numpy.array', 'np.array', (['[[[1.0, 1.0]], [[2.0, 2.0]]]'], {'dtype': 'np.float'}), '([[[1.0, 1.0]], [[2.0, 2.0]]], dtype=np.float)\n', (26762, 26808), True, 'import numpy as np\n'), ((26817, 26844), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (26829, 26844), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((26853, 26892), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'control.dtype'], {}), '(test.dtype, control.dtype)\n', (26865, 26892), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((27063, 27071), 'numpy.ma.core.mvoid', 'mvoid', (['a'], {}), '(a)\n', (27068, 27071), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((27229, 27296), 'numpy.ma.core.masked_array', 'masked_array', (['[(1, 2), (1, 2)]'], {'mask': '[(1, 0), (0, 0)]', 'dtype': 'ndtype'}), '([(1, 2), (1, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)\n', (27241, 27296), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((27309, 27338), 'numpy.ma.core.mvoid', 'mvoid', (['a._data[0]', 'a._mask[0]'], {}), '(a._data[0], a._mask[0])\n', (27314, 27338), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((27499, 27566), 'numpy.ma.core.masked_array', 'masked_array', (['[(1, 2), (3, 4)]'], {'mask': '[(0, 0), (1, 0)]', 'dtype': 'ndtype'}), '([(1, 2), (3, 4)], mask=[(0, 0), (1, 0)], dtype=ndtype)\n', (27511, 27566), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((27683, 27719), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["(f[0], f['a'])", '(1, 1)'], {}), "((f[0], f['a']), (1, 1))\n", (27695, 27719), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((27728, 27751), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["f['b']", '(2)'], {}), "(f['b'], 2)\n", (27740, 27751), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((27923, 27944), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['f[1]', '(4)'], {}), '(f[1], 4)\n', (27935, 27944), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((27981, 28068), 'numpy.ma.core.masked_array', 'masked_array', ([], {'data': '[([0, 1],)]', 'mask': '[([True, False],)]', 'dtype': "[('A', '>i2', (2,))]"}), "(data=[([0, 1],)], mask=[([True, False],)], dtype=[('A', '>i2',\n (2,))])\n", (27993, 28068), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((28122, 28156), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["A[0]['A']", "A['A'][0]"], {}), "(A[0]['A'], A['A'][0])\n", (28134, 28156), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((28400, 28467), 'numpy.ma.core.masked_array', 'masked_array', (['[(1, 2), (3, 4)]'], {'mask': '[(0, 0), (1, 0)]', 'dtype': 'ndtype'}), '([(1, 2), (3, 4)], mask=[(0, 0), (1, 0)], dtype=ndtype)\n', (28412, 28467), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((28696, 28751), 'numpy.ma.core.array', 'array', (['[(1, 1), (2, 2)]'], {'dtype': "[('a', int), ('b', int)]"}), "([(1, 1), (2, 2)], dtype=[('a', int), ('b', int)])\n", (28701, 28751), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((28882, 28920), 'numpy.ma.core.masked_print_option.set_display', 'masked_print_option.set_display', (['"""-X-"""'], {}), "('-X-')\n", (28913, 28920), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((29186, 29225), 'numpy.ma.core.array', 'array', (['[(1,), (2,)]'], {'dtype': "[('a', 'O')]"}), "([(1,), (2,)], dtype=[('a', 'O')])\n", (29191, 29225), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((29363, 29500), 'numpy.ma.core.masked_array', 'masked_array', ([], {'data': '[([1, 2, 3],)]', 'mask': '[([False, True, False],)]', 'fill_value': '([999999, 999999, 999999],)', 'dtype': "[('a', '<i4', (3,))]"}), "(data=[([1, 2, 3],)], mask=[([False, True, False],)],\n fill_value=([999999, 999999, 999999],), dtype=[('a', '<i4', (3,))])\n", (29375, 29500), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((29755, 29872), 'numpy.ma.core.masked_array', 'masked_array', ([], {'data': '[([[1, 2], [3, 4]],)]', 'mask': '[([[False, True], [True, False]],)]', 'dtype': "[('a', '<i4', (2, 2))]"}), "(data=[([[1, 2], [3, 4]],)], mask=[([[False, True], [True, \n False]],)], dtype=[('a', '<i4', (2, 2))])\n", (29767, 29872), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((30059, 30148), 'numpy.ma.core.masked_array', 'masked_array', ([], {'data': '[(1, 2)]', 'mask': '[(True, False)]', 'dtype': "[('a', '<i4'), ('b', '<i4')]"}), "(data=[(1, 2)], mask=[(True, False)], dtype=[('a', '<i4'), ('b',\n '<i4')])\n", (30071, 30148), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((30308, 30447), 'numpy.ma.core.masked_array', 'masked_array', ([], {'data': '[([[1, 2], [3, 4]], 1)]', 'mask': '[([[False, True], [True, False]], False)]', 'dtype': "[('a', '<i4', (2, 2)), ('b', float)]"}), "(data=[([[1, 2], [3, 4]], 1)], mask=[([[False, True], [True, \n False]], False)], dtype=[('a', '<i4', (2, 2)), ('b', float)])\n", (30320, 30447), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((30642, 30746), 'numpy.ma.core.masked_array', 'masked_array', ([], {'data': '[(1, (1, 1))]', 'mask': '[(True, (True, False))]', 'dtype': "[('a', '<i4'), ('b', 'i4,i4')]"}), "(data=[(1, (1, 1))], mask=[(True, (True, False))], dtype=[('a',\n '<i4'), ('b', 'i4,i4')])\n", (30654, 30746), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((30953, 30985), 'numpy.ma.core.masked_array', 'masked_array', (['[1.0]'], {'mask': '[True]'}), '([1.0], mask=[True])\n', (30965, 30985), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((30999, 31023), 'numpy.ma.core.masked_array', 'masked_array', (['[1.0, 2.0]'], {}), '([1.0, 2.0])\n', (31011, 31023), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((31035, 31079), 'numpy.ma.core.masked_array', 'masked_array', (['[mx1, mx2]'], {'mask': '[False, True]'}), '([mx1, mx2], mask=[False, True])\n', (31047, 31079), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((31088, 31109), 'numpy.ma.testutils.assert_', 'assert_', (['(mx[0] is mx1)'], {}), '(mx[0] is mx1)\n', (31095, 31109), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((31118, 31143), 'numpy.ma.testutils.assert_', 'assert_', (['(mx[1] is not mx2)'], {}), '(mx[1] is not mx2)\n', (31125, 31143), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((31302, 31324), 'numpy.ma.testutils.assert_', 'assert_', (['(mx2[0] == 0.0)'], {}), '(mx2[0] == 0.0)\n', (31309, 31324), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((31475, 31554), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0]'], {}), '([1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0])\n', (31483, 31554), True, 'import numpy as np\n'), ((31554, 31629), 'numpy.array', 'np.array', (['[5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0]'], {}), '([5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0])\n', (31562, 31629), True, 'import numpy as np\n'), ((31749, 31773), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': 'm1'}), '(x, mask=m1)\n', (31761, 31773), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((31787, 31811), 'numpy.ma.core.masked_array', 'masked_array', (['y'], {'mask': 'm2'}), '(y, mask=m2)\n', (31799, 31811), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((31824, 31855), 'numpy.array', 'np.array', (['[-0.5, 0.0, 0.5, 0.8]'], {}), '([-0.5, 0.0, 0.5, 0.8])\n', (31832, 31855), True, 'import numpy as np\n'), ((31865, 31899), 'numpy.ma.core.masked_array', 'masked_array', (['z'], {'mask': '[0, 1, 0, 0]'}), '(z, mask=[0, 1, 0, 0])\n', (31877, 31899), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((31913, 31935), 'numpy.where', 'np.where', (['m1', '(1e+20)', 'x'], {}), '(m1, 1e+20, x)\n', (31921, 31935), True, 'import numpy as np\n'), ((32051, 32062), 'numpy.geterr', 'np.geterr', ([], {}), '()\n', (32060, 32062), True, 'import numpy as np\n'), ((32071, 32115), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (32080, 32115), True, 'import numpy as np\n'), ((32149, 32177), 'numpy.seterr', 'np.seterr', ([], {}), '(**self.err_status)\n', (32158, 32177), True, 'import numpy as np\n'), ((32322, 32345), 'numpy.ma.core.array', 'array', (['[[1, 2], [0, 4]]'], {}), '([[1, 2], [0, 4]])\n', (32327, 32345), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((32361, 32396), 'numpy.ma.core.masked_array', 'masked_array', (['a2d', '[[0, 0], [1, 0]]'], {}), '(a2d, [[0, 0], [1, 0]])\n', (32373, 32396), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((32405, 32440), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a2d * a2d)', '(a2d * a2dm)'], {}), '(a2d * a2d, a2d * a2dm)\n', (32417, 32440), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((32449, 32484), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a2d + a2d)', '(a2d + a2dm)'], {}), '(a2d + a2d, a2d + a2dm)\n', (32461, 32484), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((32493, 32528), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a2d - a2d)', '(a2d - a2dm)'], {}), '(a2d - a2d, a2d - a2dm)\n', (32505, 32528), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33707, 33729), 'numpy.ma.core.arange', 'arange', (['(6)'], {'dtype': 'float'}), '(6, dtype=float)\n', (33713, 33729), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((33767, 33789), 'numpy.ma.core.arange', 'arange', (['(3)'], {'dtype': 'float'}), '(3, dtype=float)\n', (33773, 33789), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((33817, 33870), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[[-1.0, 1.0, 1.0], [-1.0, 4.0, 2.5]]'], {}), '(z, [[-1.0, 1.0, 1.0], [-1.0, 4.0, 2.5]])\n', (33829, 33870), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33874, 33918), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z.mask', '[[1, 0, 0], [1, 0, 0]]'], {}), '(z.mask, [[1, 0, 0], [1, 0, 0]])\n', (33886, 33918), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33954, 34007), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[[-1.0, 1.0, 1.0], [-1.0, 4.0, 2.5]]'], {}), '(z, [[-1.0, 1.0, 1.0], [-1.0, 4.0, 2.5]])\n', (33966, 34007), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((34011, 34055), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z.mask', '[[1, 0, 0], [1, 0, 0]]'], {}), '(z.mask, [[1, 0, 0], [1, 0, 0]])\n', (34023, 34055), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((34069, 34091), 'numpy.ma.core.arange', 'arange', (['(2)'], {'dtype': 'float'}), '(2, dtype=float)\n', (34075, 34091), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((34127, 34181), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[[-1.0, -1.0, -1.0], [3.0, 4.0, 5.0]]'], {}), '(z, [[-1.0, -1.0, -1.0], [3.0, 4.0, 5.0]])\n', (34139, 34181), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((34184, 34228), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z.mask', '[[1, 1, 1], [0, 0, 0]]'], {}), '(z.mask, [[1, 1, 1], [0, 0, 0]])\n', (34196, 34228), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((34315, 34328), 'numpy.array', 'np.array', (['[1]'], {}), '([1])\n', (34323, 34328), True, 'import numpy as np\n'), ((34342, 34352), 'numpy.ma.core.array', 'array', (['[1]'], {}), '([1])\n', (34347, 34352), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((34556, 34586), 'numpy.ma.core.array', 'array', (['[tiny, 1.0 / tiny, 0.0]'], {}), '([tiny, 1.0 / tiny, 0.0])\n', (34561, 34586), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((34873, 34889), 'numpy.ma.core.array', 'array', (['(0)'], {'mask': '(1)'}), '(0, mask=1)\n', (34878, 34889), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((35210, 35242), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 1, 0]'}), '([1, 2, 3], mask=[1, 1, 0])\n', (35215, 35242), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((35251, 35281), 'numpy.ma.testutils.assert_', 'assert_', (['((a[0] == 0) is masked)'], {}), '((a[0] == 0) is masked)\n', (35258, 35281), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35290, 35320), 'numpy.ma.testutils.assert_', 'assert_', (['((a[0] != 0) is masked)'], {}), '((a[0] != 0) is masked)\n', (35297, 35320), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35329, 35360), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a[-1] == 0)', '(False)'], {}), '(a[-1] == 0, False)\n', (35341, 35360), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35371, 35401), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a[-1] != 0)', '(True)'], {}), '(a[-1] != 0, True)\n', (35383, 35401), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35524, 35544), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2]'], {}), '([1, 2])\n', (35536, 35544), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((35576, 35606), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y.shape', 'x.shape'], {}), '(y.shape, x.shape)\n', (35588, 35606), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35615, 35650), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y._mask', '[True, True]'], {}), '(y._mask, [True, True])\n', (35627, 35650), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35685, 35705), 'numpy.ma.testutils.assert_', 'assert_', (['(y is masked)'], {}), '(y is masked)\n', (35692, 35705), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35737, 35767), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y.shape', 'x.shape'], {}), '(y.shape, x.shape)\n', (35749, 35767), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35776, 35811), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y._mask', '[True, True]'], {}), '(y._mask, [True, True])\n', (35788, 35811), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((35957, 35974), 'numpy.ma.core.masked_array', 'masked_array', (['[1]'], {}), '([1])\n', (35969, 35974), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36008, 36038), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y.shape', 'x.shape'], {}), '(y.shape, x.shape)\n', (36020, 36038), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((36047, 36075), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y.mask', '[True]'], {}), '(y.mask, [True])\n', (36059, 36075), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((36129, 36145), 'numpy.ma.core.array', 'array', (['(0)'], {'mask': '(0)'}), '(0, mask=0)\n', (36134, 36145), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36312, 36340), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm.shape', '(2,)'], {}), '(xm.shape, (2,))\n', (36324, 36340), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((36349, 36378), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm.mask', '[1, 1]'], {}), '(xm.mask, [1, 1])\n', (36361, 36378), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((37893, 37939), 'numpy.ma.core.array', 'array', (['[0.0, 1.0, 2.0, 3.0]'], {'mask': '[1, 0, 0, 0]'}), '([0.0, 1.0, 2.0, 3.0], mask=[1, 0, 0, 0])\n', (37898, 37939), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37950, 37960), 'numpy.ma.core.count', 'count', (['ott'], {}), '(ott)\n', (37955, 37960), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38020, 38040), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(3)', 'res'], {}), '(3, res)\n', (38032, 38040), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((38090, 38100), 'numpy.ma.core.count', 'count', (['ott'], {}), '(ott)\n', (38095, 38100), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38109, 38143), 'numpy.ma.testutils.assert_', 'assert_', (['(res.dtype.type is np.intp)'], {}), '(res.dtype.type is np.intp)\n', (38116, 38143), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((38152, 38172), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(3)', 'res'], {}), '(3, res)\n', (38164, 38172), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((38187, 38200), 'numpy.ma.core.count', 'count', (['ott', '(0)'], {}), '(ott, 0)\n', (38192, 38200), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38251, 38276), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['[1, 2]', 'res'], {}), '([1, 2], res)\n', (38263, 38276), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((38332, 38359), 'numpy.ma.core.array', 'array', (['[0.0, 1.0, 2.0, 3.0]'], {}), '([0.0, 1.0, 2.0, 3.0])\n', (38337, 38359), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38370, 38383), 'numpy.ma.core.count', 'count', (['ott', '(0)'], {}), '(ott, 0)\n', (38375, 38383), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38434, 38468), 'numpy.ma.testutils.assert_', 'assert_', (['(res.dtype.type is np.intp)'], {}), '(res.dtype.type is np.intp)\n', (38441, 38468), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((38477, 38521), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'ott.count'], {'axis': '(1)'}), '(ValueError, ott.count, axis=1)\n', (38490, 38521), False, 'from numpy.testing import TestCase, run_module_suite, assert_raises\n'), ((38698, 38709), 'numpy.ravel', 'np.ravel', (['x'], {}), '(x)\n', (38706, 38709), True, 'import numpy as np\n'), ((38724, 38733), 'numpy.ma.core.ravel', 'ravel', (['xm'], {}), '(xm)\n', (38729, 38733), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39027, 39036), 'numpy.ma.core.arange', 'arange', (['(5)'], {}), '(5)\n', (39033, 39036), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39451, 39466), 'numpy.ones', 'np.ones', (['(2, 2)'], {}), '((2, 2))\n', (39458, 39466), True, 'import numpy as np\n'), ((39486, 39499), 'numpy.ma.core.minimum', 'minimum', (['a', 'a'], {}), '(a, a)\n', (39493, 39499), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39628, 39647), 'numpy.ma.core.minimum.outer', 'minimum.outer', (['a', 'a'], {}), '(a, a)\n', (39641, 39647), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39782, 39795), 'numpy.ma.core.maximum', 'maximum', (['a', 'a'], {}), '(a, a)\n', (39789, 39795), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39924, 39943), 'numpy.ma.core.maximum.outer', 'maximum.outer', (['a', 'a'], {}), '(a, a)\n', (39937, 39943), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((40170, 40214), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[False, False, False]'}), '([1, 2, 3], mask=[False, False, False])\n', (40175, 40214), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((40227, 40247), 'numpy.maximum.reduce', 'np.maximum.reduce', (['a'], {}), '(a)\n', (40244, 40247), True, 'import numpy as np\n'), ((40256, 40274), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b', '(3)'], {}), '(b, 3)\n', (40268, 40274), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((41873, 41900), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '(True)'}), '([1, 2, 3], mask=True)\n', (41878, 41900), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((43161, 43221), 'numpy.ma.core.array', 'array', (['[[1.0], [2.0], [3.0]]'], {'mask': '[[False], [True], [True]]'}), '([[1.0], [2.0], [3.0]], mask=[[False], [True], [True]])\n', (43166, 43221), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((43231, 43274), 'numpy.ma.core.array', 'array', (['[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]]'], {}), '([[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]])\n', (43236, 43274), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((43309, 43383), 'numpy.ma.core.array', 'array', (['[[2.0, 3.0], [2.0, 2.0], [3.0, 3.0]]'], {'mask': '[[0, 0], [1, 1], [1, 1]]'}), '([[2.0, 3.0], [2.0, 2.0], [3.0, 3.0]], mask=[[0, 0], [1, 1], [1, 1]])\n', (43314, 43383), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((43410, 43437), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (43422, 43437), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((43446, 43483), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'control.data'], {}), '(test.data, control.data)\n', (43458, 43483), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((43492, 43529), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (43504, 43529), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((43570, 43644), 'numpy.ma.core.array', 'array', (['[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]]'], {'mask': '[[0, 0], [1, 1], [1, 1]]'}), '([[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]], mask=[[0, 0], [1, 1], [1, 1]])\n', (43575, 43644), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((43671, 43698), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (43683, 43698), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((43707, 43744), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'control.data'], {}), '(test.data, control.data)\n', (43719, 43744), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((43753, 43790), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (43765, 43790), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((43804, 43832), 'numpy.ma.core.array', 'array', (['[[1.0], [2.0], [3.0]]'], {}), '([[1.0], [2.0], [3.0]])\n', (43809, 43832), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((43842, 43916), 'numpy.ma.core.array', 'array', (['[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]]'], {'mask': '[[0, 0], [0, 0], [0, 1]]'}), '([[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]], mask=[[0, 0], [0, 0], [0, 1]])\n', (43847, 43916), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((43968, 44032), 'numpy.ma.core.array', 'array', (['[[2, 3], [8, 10], [18, 3]]'], {'mask': '[[0, 0], [0, 0], [0, 1]]'}), '([[2, 3], [8, 10], [18, 3]], mask=[[0, 0], [0, 0], [0, 1]])\n', (43973, 44032), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((44065, 44092), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (44077, 44092), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44101, 44138), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'control.data'], {}), '(test.data, control.data)\n', (44113, 44138), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44147, 44184), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (44159, 44184), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44225, 44289), 'numpy.ma.core.array', 'array', (['[[2, 3], [8, 10], [18, 7]]'], {'mask': '[[0, 0], [0, 0], [0, 1]]'}), '([[2, 3], [8, 10], [18, 7]], mask=[[0, 0], [0, 0], [0, 1]])\n', (44230, 44289), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((44322, 44349), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (44334, 44349), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44358, 44395), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'control.data'], {}), '(test.data, control.data)\n', (44370, 44395), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44404, 44441), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (44416, 44441), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44548, 44608), 'numpy.ma.core.array', 'array', (['[[1.0], [2.0], [3.0]]'], {'mask': '[[False], [True], [True]]'}), '([[1.0], [2.0], [3.0]], mask=[[False], [True], [True]])\n', (44553, 44608), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((44618, 44661), 'numpy.ma.core.array', 'array', (['[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]]'], {}), '([[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]])\n', (44623, 44661), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((44696, 44787), 'numpy.ma.core.array', 'array', (['[[1.0 / 2.0, 1.0 / 3.0], [2.0, 2.0], [3.0, 3.0]]'], {'mask': '[[0, 0], [1, 1], [1, 1]]'}), '([[1.0 / 2.0, 1.0 / 3.0], [2.0, 2.0], [3.0, 3.0]], mask=[[0, 0], [1, 1\n ], [1, 1]])\n', (44701, 44787), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((44807, 44834), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (44819, 44834), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44843, 44880), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'control.data'], {}), '(test.data, control.data)\n', (44855, 44880), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44889, 44926), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (44901, 44926), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((44967, 45058), 'numpy.ma.core.array', 'array', (['[[2.0 / 1.0, 3.0 / 1.0], [4.0, 5.0], [6.0, 7.0]]'], {'mask': '[[0, 0], [1, 1], [1, 1]]'}), '([[2.0 / 1.0, 3.0 / 1.0], [4.0, 5.0], [6.0, 7.0]], mask=[[0, 0], [1, 1\n ], [1, 1]])\n', (44972, 45058), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((45078, 45105), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (45090, 45105), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((45114, 45151), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'control.data'], {}), '(test.data, control.data)\n', (45126, 45151), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((45160, 45197), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (45172, 45197), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((45211, 45239), 'numpy.ma.core.array', 'array', (['[[1.0], [2.0], [3.0]]'], {}), '([[1.0], [2.0], [3.0]])\n', (45216, 45239), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((45249, 45323), 'numpy.ma.core.array', 'array', (['[[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]]'], {'mask': '[[0, 0], [0, 0], [0, 1]]'}), '([[2.0, 3.0], [4.0, 5.0], [6.0, 7.0]], mask=[[0, 0], [0, 0], [0, 1]])\n', (45254, 45323), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((45375, 45471), 'numpy.ma.core.array', 'array', (['[[1.0 / 2, 1.0 / 3], [2.0 / 4, 2.0 / 5], [3.0 / 6, 3]]'], {'mask': '[[0, 0], [0, 0], [0, 1]]'}), '([[1.0 / 2, 1.0 / 3], [2.0 / 4, 2.0 / 5], [3.0 / 6, 3]], mask=[[0, 0],\n [0, 0], [0, 1]])\n', (45380, 45471), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((45495, 45522), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (45507, 45522), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((45531, 45568), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'control.data'], {}), '(test.data, control.data)\n', (45543, 45568), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((45577, 45614), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (45589, 45614), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((45655, 45751), 'numpy.ma.core.array', 'array', (['[[2 / 1.0, 3 / 1.0], [4 / 2.0, 5 / 2.0], [6 / 3.0, 7]]'], {'mask': '[[0, 0], [0, 0], [0, 1]]'}), '([[2 / 1.0, 3 / 1.0], [4 / 2.0, 5 / 2.0], [6 / 3.0, 7]], mask=[[0, 0],\n [0, 0], [0, 1]])\n', (45660, 45751), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((45775, 45802), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (45787, 45802), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((45811, 45848), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'control.data'], {}), '(test.data, control.data)\n', (45823, 45848), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((45857, 45894), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (45869, 45894), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((46028, 46099), 'numpy.ma.core.masked_array', 'masked_array', (['[1.0, 2.0, 3.0]'], {'mask': '[False, False, False]', 'shrink': '(False)'}), '([1.0, 2.0, 3.0], mask=[False, False, False], shrink=False)\n', (46040, 46099), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((46148, 46179), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.mask', '[0, 0, 0]'], {}), '(b.mask, [0, 0, 0])\n', (46160, 46179), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((46239, 46270), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[0, 0, 0]'], {}), '(a.mask, [0, 0, 0])\n', (46251, 46270), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((46334, 46365), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.mask', '[0, 0, 0]'], {}), '(b.mask, [0, 0, 0])\n', (46346, 46365), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((46426, 46457), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[0, 0, 0]'], {}), '(a.mask, [0, 0, 0])\n', (46438, 46457), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((46589, 46644), 'numpy.ma.masked_values', 'np.ma.masked_values', (['[1.0, 2.5, 3.1]', '(1.5)'], {'shrink': '(False)'}), '([1.0, 2.5, 3.1], 1.5, shrink=False)\n', (46608, 46644), True, 'import numpy as np\n'), ((46652, 46683), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[0, 0, 0]'], {}), '(a.mask, [0, 0, 0])\n', (46664, 46683), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((46845, 46856), 'numpy.ma.core.mod', 'mod', (['ym', 'xm'], {}), '(ym, xm)\n', (46848, 46856), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((46974, 46985), 'numpy.ma.core.mod', 'mod', (['xm', 'ym'], {}), '(xm, ym)\n', (46977, 46985), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47222, 47232), 'numpy.ma.core.arange', 'arange', (['(24)'], {}), '(24)\n', (47228, 47232), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47245, 47258), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (47254, 47258), True, 'import numpy as np\n'), ((47687, 47725), 'numpy.ma.core.array', 'array', (["['abc', 1, 'def', 2, 3]", 'object'], {}), "(['abc', 1, 'def', 2, 3], object)\n", (47692, 47725), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47760, 47778), 'numpy.ma.core.take', 'take', (['y', '[0, 3, 4]'], {}), '(y, [0, 3, 4])\n', (47764, 47778), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47787, 47809), 'numpy.ma.testutils.assert_', 'assert_', (["(t[0] == 'abc')"], {}), "(t[0] == 'abc')\n", (47794, 47809), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((47818, 47836), 'numpy.ma.testutils.assert_', 'assert_', (['(t[1] == 2)'], {}), '(t[1] == 2)\n', (47825, 47836), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((47845, 47863), 'numpy.ma.testutils.assert_', 'assert_', (['(t[2] == 3)'], {}), '(t[2] == 3)\n', (47852, 47863), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((47932, 47974), 'numpy.ma.core.array', 'array', (['[1 + 10.0j, 20 + 2.0j]'], {'mask': '[1, 0]'}), '([1 + 10.0j, 20 + 2.0j], mask=[1, 0])\n', (47937, 47974), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47979, 48009), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.imag', '[10, 2]'], {}), '(xx.imag, [10, 2])\n', (47991, 48009), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((48069, 48117), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.imag.dtype', 'xx._data.imag.dtype'], {}), '(xx.imag.dtype, xx._data.imag.dtype)\n', (48081, 48117), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((48126, 48156), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.real', '[1, 20]'], {}), '(xx.real, [1, 20])\n', (48138, 48156), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((48217, 48265), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.real.dtype', 'xx._data.real.dtype'], {}), '(xx.real.dtype, xx._data.real.dtype)\n', (48229, 48265), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((49633, 49693), 'numpy.ma.core.array', 'array', (['[(1, 1), (2, 2)]'], {'mask': '[(0, 1), (0, 0)]', 'dtype': 'ndtype'}), '([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype)\n', (49638, 49693), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((49726, 49758), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[True, True]'], {}), '(test, [True, True])\n', (49738, 49758), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((49767, 49806), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[False, False]'], {}), '(test.mask, [False, False])\n', (49779, 49806), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((49819, 49879), 'numpy.ma.core.array', 'array', (['[(1, 1), (2, 2)]'], {'mask': '[(1, 0), (0, 0)]', 'dtype': 'ndtype'}), '([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)\n', (49824, 49879), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((49912, 49945), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[False, True]'], {}), '(test, [False, True])\n', (49924, 49945), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((49954, 49992), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[True, False]'], {}), '(test.mask, [True, False])\n', (49966, 49992), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((50005, 50065), 'numpy.ma.core.array', 'array', (['[(1, 1), (2, 2)]'], {'mask': '[(0, 1), (1, 0)]', 'dtype': 'ndtype'}), '([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)\n', (50010, 50065), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((50098, 50131), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[True, False]'], {}), '(test, [True, False])\n', (50110, 50131), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((50140, 50179), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[False, False]'], {}), '(test.mask, [False, False])\n', (50152, 50179), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((50321, 50381), 'numpy.ma.core.array', 'array', (['[(1, 1), (2, 2)]'], {'mask': '[(0, 1), (0, 0)]', 'dtype': 'ndtype'}), '([(1, 1), (2, 2)], mask=[(0, 1), (0, 0)], dtype=ndtype)\n', (50326, 50381), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((50414, 50448), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[False, False]'], {}), '(test, [False, False])\n', (50426, 50448), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((50457, 50496), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[False, False]'], {}), '(test.mask, [False, False])\n', (50469, 50496), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((50509, 50569), 'numpy.ma.core.array', 'array', (['[(1, 1), (2, 2)]'], {'mask': '[(1, 0), (0, 0)]', 'dtype': 'ndtype'}), '([(1, 1), (2, 2)], mask=[(1, 0), (0, 0)], dtype=ndtype)\n', (50514, 50569), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((50602, 50635), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[True, False]'], {}), '(test, [True, False])\n', (50614, 50635), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((50644, 50682), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[True, False]'], {}), '(test.mask, [True, False])\n', (50656, 50682), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((50695, 50755), 'numpy.ma.core.array', 'array', (['[(1, 1), (2, 2)]'], {'mask': '[(0, 1), (1, 0)]', 'dtype': 'ndtype'}), '([(1, 1), (2, 2)], mask=[(0, 1), (1, 0)], dtype=ndtype)\n', (50700, 50755), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((50788, 50821), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[False, True]'], {}), '(test, [False, True])\n', (50800, 50821), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((50830, 50869), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[False, False]'], {}), '(test.mask, [False, False])\n', (50842, 50869), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51073, 51099), 'numpy.ma.core.array', 'array', (['[1, 2]'], {'mask': '[0, 1]'}), '([1, 2], mask=[0, 1])\n', (51078, 51099), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((51108, 51138), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a == None)', '(False)'], {}), '(a == None, False)\n', (51120, 51138), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51147, 51182), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a.data == None)', '(False)'], {}), '(a.data == None, False)\n', (51159, 51182), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51191, 51226), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a.mask == None)', '(False)'], {}), '(a.mask == None, False)\n', (51203, 51226), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51235, 51264), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a != None)', '(True)'], {}), '(a != None, True)\n', (51247, 51264), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51299, 51324), 'numpy.ma.core.array', 'array', (['[1, 2]'], {'mask': '(False)'}), '([1, 2], mask=False)\n', (51304, 51324), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((51333, 51363), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a == None)', '(False)'], {}), '(a == None, False)\n', (51345, 51363), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51372, 51401), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a != None)', '(True)'], {}), '(a != None, True)\n', (51384, 51401), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51443, 51467), 'numpy.ma.core.array', 'array', (['[1, 2]'], {'mask': '(True)'}), '([1, 2], mask=True)\n', (51448, 51467), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((51476, 51506), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a == None)', '(False)'], {}), '(a == None, False)\n', (51488, 51506), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51515, 51544), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a != None)', '(True)'], {}), '(a != None, True)\n', (51527, 51544), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51643, 51674), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a == None)', 'masked'], {}), '(a == None, masked)\n', (51655, 51674), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51720, 51728), 'numpy.ma.core.array', 'array', (['(1)'], {}), '(1)\n', (51725, 51728), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((51737, 51763), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a == 1)', '(True)'], {}), '(a == 1, True)\n', (51749, 51763), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51772, 51799), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a == 0)', '(False)'], {}), '(a == 0, False)\n', (51784, 51799), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51808, 51835), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a != 1)', '(False)'], {}), '(a != 1, False)\n', (51820, 51835), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((51844, 51870), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a != 0)', '(True)'], {}), '(a != 0, True)\n', (51856, 51870), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52001, 52053), 'numpy.ma.core.masked_array', 'masked_array', (['[-1, 0, 1, 2, 3]'], {'mask': '[0, 0, 0, 0, 1]'}), '([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1])\n', (52013, 52053), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((52190, 52196), 'numpy.ma.core.log', 'log', (['a'], {}), '(a)\n', (52193, 52196), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((52205, 52232), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (52217, 52232), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52241, 52278), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (52253, 52278), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52287, 52324), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[0, 0, 0, 0, 1]'], {}), '(a.mask, [0, 0, 0, 0, 1])\n', (52299, 52324), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52341, 52350), 'numpy.log', 'np.log', (['a'], {}), '(a)\n', (52347, 52350), True, 'import numpy as np\n'), ((52359, 52386), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (52371, 52386), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52395, 52432), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (52407, 52432), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52441, 52478), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[0, 0, 0, 0, 1]'], {}), '(a.mask, [0, 0, 0, 0, 1])\n', (52453, 52478), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52601, 52640), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]'}), '([1, 2, 3], mask=[1, 0, 0])\n', (52613, 52640), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((52654, 52669), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {}), '(x)\n', (52666, 52669), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((52678, 52707), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx.mask', 'x.mask'], {}), '(mx.mask, x.mask)\n', (52690, 52707), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52721, 52769), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': '[0, 1, 0]', 'keep_mask': '(False)'}), '(x, mask=[0, 1, 0], keep_mask=False)\n', (52733, 52769), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((52778, 52810), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx.mask', '[0, 1, 0]'], {}), '(mx.mask, [0, 1, 0])\n', (52790, 52810), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52824, 52871), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': '[0, 1, 0]', 'keep_mask': '(True)'}), '(x, mask=[0, 1, 0], keep_mask=True)\n', (52836, 52871), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((52880, 52912), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx.mask', '[1, 1, 0]'], {}), '(mx.mask, [1, 1, 0])\n', (52892, 52912), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((52955, 52986), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': '[0, 1, 0]'}), '(x, mask=[0, 1, 0])\n', (52967, 52986), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((52995, 53027), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx.mask', '[1, 1, 0]'], {}), '(mx.mask, [1, 1, 0])\n', (53007, 53027), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53095, 53104), 'numpy.ma.core.arange', 'arange', (['(5)'], {}), '(5)\n', (53101, 53104), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((53145, 53157), 'numpy.ma.core.make_mask', 'make_mask', (['n'], {}), '(n)\n', (53154, 53157), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((53171, 53203), 'numpy.ma.core.array', 'array', (['d'], {'mask': 'm', 'hard_mask': '(True)'}), '(d, mask=m, hard_mask=True)\n', (53176, 53203), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((53272, 53316), 'numpy.ma.core.array', 'array', (['d'], {'mask': 'm', 'hard_mask': '(False)', 'copy': '(True)'}), '(d, mask=m, hard_mask=False, copy=True)\n', (53277, 53316), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((53385, 53425), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[0, 10, 2, 3, 4]'], {}), '(xh._data, [0, 10, 2, 3, 4])\n', (53397, 53425), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53434, 53475), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xs._data', '[0, 10, 2, 3, 40]'], {}), '(xs._data, [0, 10, 2, 3, 40])\n', (53446, 53475), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53484, 53522), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xs.mask', '[0, 0, 0, 1, 0]'], {}), '(xs.mask, [0, 0, 0, 1, 0])\n', (53496, 53522), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53673, 53714), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[0, 10, 20, 3, 4]'], {}), '(xh._data, [0, 10, 20, 3, 4])\n', (53685, 53714), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53723, 53766), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xs._data', '[0, 10, 20, 30, 40]'], {}), '(xs._data, [0, 10, 20, 30, 40])\n', (53735, 53766), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53775, 53804), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xs.mask', 'nomask'], {}), '(xs.mask, nomask)\n', (53787, 53804), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53859, 53897), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh.mask', '[1, 0, 0, 1, 1]'], {}), '(xh.mask, [1, 0, 0, 1, 1])\n', (53871, 53897), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53906, 53944), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xs.mask', '[1, 0, 0, 0, 0]'], {}), '(xs.mask, [1, 0, 0, 0, 0])\n', (53918, 53944), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((53989, 54028), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[0, 1, 1, 3, 4]'], {}), '(xh._data, [0, 1, 1, 3, 4])\n', (54001, 54028), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54037, 54076), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xs._data', '[1, 1, 1, 1, 1]'], {}), '(xs._data, [1, 1, 1, 1, 1])\n', (54049, 54076), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54085, 54123), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh.mask', '[1, 0, 0, 1, 1]'], {}), '(xh.mask, [1, 0, 0, 1, 1])\n', (54097, 54123), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54132, 54161), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xs.mask', 'nomask'], {}), '(xs.mask, nomask)\n', (54144, 54161), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54233, 54242), 'numpy.ma.core.arange', 'arange', (['(5)'], {}), '(5)\n', (54239, 54242), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((54251, 54290), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[0, 1, 2, 3, 4]'], {}), '(xh._data, [0, 1, 2, 3, 4])\n', (54263, 54290), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54299, 54328), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh.mask', 'nomask'], {}), '(xh.mask, nomask)\n', (54311, 54328), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54425, 54464), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[0, 1, 2, 3, 4]'], {}), '(xh._data, [0, 1, 2, 3, 4])\n', (54437, 54464), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54473, 54512), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._mask', '[1, 1, 1, 0, 0]'], {}), '(xh._mask, [1, 1, 1, 0, 0])\n', (54485, 54512), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54559, 54598), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[0, 1, 2, 5, 5]'], {}), '(xh._data, [0, 1, 2, 5, 5])\n', (54571, 54598), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54607, 54646), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._mask', '[1, 1, 1, 0, 0]'], {}), '(xh._mask, [1, 1, 1, 0, 0])\n', (54619, 54646), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54661, 54723), 'numpy.ma.core.array', 'array', (['[[1, 2], [3, 4]]'], {'mask': '[[1, 0], [0, 0]]', 'hard_mask': '(True)'}), '([[1, 2], [3, 4]], mask=[[1, 0], [0, 0]], hard_mask=True)\n', (54666, 54723), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((54750, 54790), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[[1, 0], [3, 4]]'], {}), '(xh._data, [[1, 0], [3, 4]])\n', (54762, 54790), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54799, 54839), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._mask', '[[1, 0], [0, 0]]'], {}), '(xh._mask, [[1, 0], [0, 0]])\n', (54811, 54839), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54871, 54911), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[[1, 0], [3, 5]]'], {}), '(xh._data, [[1, 0], [3, 5]])\n', (54883, 54911), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((54920, 54960), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._mask', '[[1, 0], [0, 0]]'], {}), '(xh._mask, [[1, 0], [0, 0]])\n', (54932, 54960), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((55007, 55047), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[[1, 2], [2, 5]]'], {}), '(xh._data, [[1, 2], [2, 5]])\n', (55019, 55047), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((55056, 55096), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._mask', '[[1, 0], [0, 0]]'], {}), '(xh._mask, [[1, 0], [0, 0]])\n', (55068, 55096), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((55180, 55189), 'numpy.ma.core.arange', 'arange', (['(5)'], {}), '(5)\n', (55186, 55189), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((55230, 55242), 'numpy.ma.core.make_mask', 'make_mask', (['n'], {}), '(n)\n', (55239, 55242), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((55256, 55288), 'numpy.ma.core.array', 'array', (['d'], {'mask': 'm', 'hard_mask': '(True)'}), '(d, mask=m, hard_mask=True)\n', (55261, 55288), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((55341, 55382), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[999, 1, 2, 3, 4]'], {}), '(xh._data, [999, 1, 2, 3, 4])\n', (55353, 55382), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((55557, 55589), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]'}), '([1, 2, 3], mask=[1, 0, 0])\n', (55562, 55589), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((55626, 55644), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', 'b'], {}), '(a, b)\n', (55638, 55644), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((55670, 55688), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', 'b'], {}), '(a, b)\n', (55682, 55688), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((55800, 55818), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', 'b'], {}), '(a, b)\n', (55812, 55818), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((55965, 55975), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (55971, 55975), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((56023, 56052), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a._mask', 'nomask'], {}), '(a._mask, nomask)\n', (56035, 56052), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((56065, 56075), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (56071, 56075), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((56261, 56293), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 0]'}), '([1, 2, 3], mask=[0, 0, 0])\n', (56266, 56293), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((56330, 56348), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', 'b'], {}), '(a, b)\n', (56342, 56348), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((56357, 56385), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', 'nomask'], {}), '(a.mask, nomask)\n', (56369, 56385), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((56587, 56616), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.flat[1]', '(2)'], {}), '(test.flat[1], 2)\n', (56599, 56616), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((56625, 56659), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.flat[2]', 'masked'], {}), '(test.flat[2], masked)\n', (56637, 56659), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((56851, 56890), 'numpy.ma.core.masked_array', 'masked_array', (['[3, 2, 1]'], {'mask': '[1, 0, 0]'}), '([3, 2, 1], mask=[1, 0, 0])\n', (56863, 56890), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((56970, 56997), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (56982, 56997), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57168, 57195), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (57180, 57195), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57228, 57255), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test[0, 0]', '(9)'], {}), '(test[0, 0], 9)\n', (57240, 57255), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57352, 57522), 'numpy.ma.core.array', 'array', (["[[(1, 1.1, 'one'), (2, 2.2, 'two'), (3, 3.3, 'thr')], [(4, 4.4, 'fou'), (5,\n 5.5, 'fiv'), (6, 6.6, 'six')]]"], {'dtype': "[('a', int), ('b', float), ('c', '|S8')]"}), "([[(1, 1.1, 'one'), (2, 2.2, 'two'), (3, 3.3, 'thr')], [(4, 4.4, 'fou'\n ), (5, 5.5, 'fiv'), (6, 6.6, 'six')]], dtype=[('a', int), ('b', float),\n ('c', '|S8')])\n", (57357, 57522), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((57699, 57730), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[0]', 'x[0, 0]'], {}), '(xflat[0], x[0, 0])\n', (57711, 57730), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57739, 57770), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[1]', 'x[0, 1]'], {}), '(xflat[1], x[0, 1])\n', (57751, 57770), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57779, 57810), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[2]', 'x[0, 2]'], {}), '(xflat[2], x[0, 2])\n', (57791, 57810), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57819, 57848), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[:3]', 'x[0]'], {}), '(xflat[:3], x[0])\n', (57831, 57848), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57857, 57888), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[3]', 'x[1, 0]'], {}), '(xflat[3], x[1, 0])\n', (57869, 57888), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57897, 57928), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[4]', 'x[1, 1]'], {}), '(xflat[4], x[1, 1])\n', (57909, 57928), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57937, 57968), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[5]', 'x[1, 2]'], {}), '(xflat[5], x[1, 2])\n', (57949, 57968), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((57977, 58006), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[3:]', 'x[1]'], {}), '(xflat[3:], x[1])\n', (57989, 58006), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((58015, 58049), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xflat[-1]', 'x[-1, -1]'], {}), '(xflat[-1], x[-1, -1])\n', (58027, 58049), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((58615, 58641), 'numpy.zeros', 'np.zeros', (['(4)'], {'dtype': '"""f4,i4"""'}), "(4, dtype='f4,i4')\n", (58623, 58641), True, 'import numpy as np\n'), ((58655, 58669), 'numpy.ma.array', 'np.ma.array', (['a'], {}), '(a)\n', (58666, 58669), True, 'import numpy as np\n'), ((58688, 58702), 'numpy.dtype', 'np.dtype', (['"""f4"""'], {}), "('f4')\n", (58696, 58702), True, 'import numpy as np\n'), ((58971, 59004), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'assign'], {}), '(ValueError, assign)\n', (58984, 59004), False, 'from numpy.testing import TestCase, run_module_suite, assert_raises\n'), ((59172, 59195), 'numpy.zeros', 'np.zeros', (['(4)'], {'dtype': '"""f4"""'}), "(4, dtype='f4')\n", (59180, 59195), True, 'import numpy as np\n'), ((59208, 59222), 'numpy.ma.array', 'np.ma.array', (['a'], {}), '(a)\n', (59219, 59222), True, 'import numpy as np\n'), ((59241, 59258), 'numpy.dtype', 'np.dtype', (['"""f4,i4"""'], {}), "('f4,i4')\n", (59249, 59258), True, 'import numpy as np\n'), ((59316, 59351), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['m._mask', 'np.ma.nomask'], {}), '(m._mask, np.ma.nomask)\n', (59328, 59351), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((59598, 59619), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['fval', '(0)'], {}), '(fval, 0)\n', (59610, 59619), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((60912, 60962), 'numpy.array', 'np.array', (["(-999, -12345678.9, '???')"], {'dtype': 'ndtype'}), "((-999, -12345678.9, '???'), dtype=ndtype)\n", (60920, 60962), True, 'import numpy as np\n'), ((61505, 61593), 'numpy.array', 'np.array', (["('???', -999, -12345678.9)"], {'dtype': "[('c', '|S3'), ('a', int), ('b', float)]"}), "(('???', -999, -12345678.9), dtype=[('c', '|S3'), ('a', int), ('b',\n float)])\n", (61513, 61593), True, 'import numpy as np\n'), ((61873, 61909), 'numpy.ndarray', 'np.ndarray', ([], {'shape': '(1,)', 'dtype': 'object'}), '(shape=(1,), dtype=object)\n', (61883, 61909), True, 'import numpy as np\n'), ((63080, 63099), 'numpy.ma.core.array', 'array', (['a'], {'dtype': 'int'}), '(a, dtype=int)\n', (63085, 63099), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((63108, 63140), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._data', '[3, 4, 5]'], {}), '(b._data, [3, 4, 5])\n', (63120, 63140), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((63212, 63233), 'numpy.ma.core.array', 'array', (['a'], {'dtype': 'float'}), '(a, dtype=float)\n', (63217, 63233), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((63242, 63274), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._data', '[3, 4, 5]'], {}), '(b._data, [3, 4, 5])\n', (63254, 63274), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((63369, 63401), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._data', '[3, 4, 5]'], {}), '(b._data, [3, 4, 5])\n', (63381, 63401), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((63468, 63515), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["b._optinfo['comment']", '"""updated!"""'], {}), "(b._optinfo['comment'], 'updated!')\n", (63480, 63515), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((63562, 63597), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["b['a']._data", 'a._data'], {}), "(b['a']._data, a._data)\n", (63574, 63597), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((63606, 63651), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["b['a'].fill_value", 'a.fill_value'], {}), "(b['a'].fill_value, a.fill_value)\n", (63618, 63651), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((63741, 63781), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]'], {'fill_value': '(-999)'}), '([1, 2, 3], fill_value=-999)\n', (63753, 63781), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((63823, 63873), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['series._fill_value', 'data._fill_value'], {}), '(series._fill_value, data._fill_value)\n', (63835, 63873), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((63932, 63984), 'numpy.ma.core.array', 'array', (["[(1, 'a'), (2, 'b'), (pi, 'pi')]"], {'dtype': 'mtype'}), "([(1, 'a'), (2, 'b'), (pi, 'pi')], dtype=mtype)\n", (63937, 63984), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((64086, 64122), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["x['f'].fill_value", '(999)'], {}), "(x['f'].fill_value, 999)\n", (64098, 64122), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((64285, 64319), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["x['f'].fill_value", '(9)'], {}), "(x['f'].fill_value, 9)\n", (64297, 64319), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((64389, 64407), 'numpy.ma.core.array', 'array', (['[1, 2, 3.1]'], {}), '([1, 2, 3.1])\n', (64394, 64407), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((64503, 64536), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.fill_value', '(999.0)'], {}), '(x.fill_value, 999.0)\n', (64515, 64536), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((65466, 65500), 'numpy.dtype', 'np.dtype', (['"""int, (2,3)float, float"""'], {}), "('int, (2,3)float, float')\n", (65474, 65500), True, 'import numpy as np\n'), ((65782, 65809), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (65794, 65809), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((66059, 66080), 'numpy.ma.core.masked_array', 'masked_array', (['control'], {}), '(control)\n', (66071, 66080), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((66089, 66129), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["M['f1'].fill_value.ndim", '(0)'], {}), "(M['f1'].fill_value.ndim, 0)\n", (66101, 66129), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((66923, 67016), 'numpy.ma.core.array', 'array', (['[(1, (2, 3)), (4, (5, 6))]'], {'dtype': "[('A', int), ('B', [('BA', int), ('BB', int)])]"}), "([(1, (2, 3)), (4, (5, 6))], dtype=[('A', int), ('B', [('BA', int), (\n 'BB', int)])])\n", (66928, 67016), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67278, 67299), 'numpy.ma.core.minimum_fill_value', 'minimum_fill_value', (['a'], {}), '(a)\n', (67296, 67299), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67566, 67587), 'numpy.ma.core.maximum_fill_value', 'maximum_fill_value', (['a'], {}), '(a)\n', (67584, 67587), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((68957, 68995), 'numpy.ma.core.empty', 'empty', (['a.shape'], {'dtype': '[adtype, ndtype]'}), '(a.shape, dtype=[adtype, ndtype])\n', (68962, 68995), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((69304, 69330), 'numpy.ma.core.empty', 'empty', (['(3)'], {'fill_value': '(999.0)'}), '(3, fill_value=999.0)\n', (69309, 69330), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((69338, 69371), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.fill_value', '(999.0)'], {}), '(a.fill_value, 999.0)\n', (69350, 69371), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((69384, 69422), 'numpy.ma.core.ones', 'ones', (['(3)'], {'fill_value': '(999.0)', 'dtype': 'float'}), '(3, fill_value=999.0, dtype=float)\n', (69388, 69422), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((69430, 69463), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.fill_value', '(999.0)'], {}), '(a.fill_value, 999.0)\n', (69442, 69463), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((69476, 69515), 'numpy.ma.core.zeros', 'zeros', (['(3)'], {'fill_value': '(0.0)', 'dtype': 'complex'}), '(3, fill_value=0.0, dtype=complex)\n', (69481, 69515), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((69523, 69554), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.fill_value', '(0.0)'], {}), '(a.fill_value, 0.0)\n', (69535, 69554), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((69567, 69609), 'numpy.ma.core.identity', 'identity', (['(3)'], {'fill_value': '(0.0)', 'dtype': 'complex'}), '(3, fill_value=0.0, dtype=complex)\n', (69575, 69609), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((69617, 69648), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.fill_value', '(0.0)'], {}), '(a.fill_value, 0.0)\n', (69629, 69648), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((69777, 69794), 'numpy.ma.core.empty', 'empty', ([], {'shape': '(3,)'}), '(shape=(3,))\n', (69782, 69794), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((69804, 69831), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.shape', '(3,)'], {}), '(a.shape, (3,))\n', (69816, 69831), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((69846, 69875), 'numpy.ma.core.ones', 'ones', ([], {'shape': '(3,)', 'dtype': 'float'}), '(shape=(3,), dtype=float)\n', (69850, 69875), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((69885, 69912), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.shape', '(3,)'], {}), '(a.shape, (3,))\n', (69897, 69912), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((69927, 69959), 'numpy.ma.core.zeros', 'zeros', ([], {'shape': '(3,)', 'dtype': 'complex'}), '(shape=(3,), dtype=complex)\n', (69932, 69959), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((69969, 69996), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.shape', '(3,)'], {}), '(a.shape, (3,))\n', (69981, 69996), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((70138, 70184), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'fill_value': '(1)', 'dtype': 'np.int64'}), '([1, 2, 3], fill_value=1, dtype=np.int64)\n', (70143, 70184), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((70271, 70297), 'numpy.ma.testutils.assert_', 'assert_', (['(y.fill_value == 1)'], {}), '(y.fill_value == 1)\n', (70278, 70297), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((70486, 70512), 'numpy.ma.testutils.assert_', 'assert_', (['(y.fill_value == 1)'], {}), '(y.fill_value == 1)\n', (70493, 70512), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((70767, 70793), 'numpy.ma.testutils.assert_', 'assert_', (['(y.fill_value == 1)'], {}), '(y.fill_value == 1)\n', (70774, 70793), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((71102, 71128), 'numpy.ma.testutils.assert_', 'assert_', (['(y.fill_value == 2)'], {}), '(y.fill_value == 2)\n', (71109, 71128), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((71263, 71289), 'numpy.ma.testutils.assert_', 'assert_', (['(y.fill_value == 2)'], {}), '(y.fill_value == 2)\n', (71270, 71289), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((71680, 71711), 'numpy.ma.testutils.assert_', 'assert_', (['(y.fill_value == 999999)'], {}), '(y.fill_value == 999999)\n', (71687, 71711), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((71895, 71933), 'numpy.ma.core.empty', 'empty', ([], {'shape': '(3,)', 'dtype': '"""(2)3S,(2)3U"""'}), "(shape=(3,), dtype='(2)3S,(2)3U')\n", (71900, 71933), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((72397, 72408), 'numpy.geterr', 'np.geterr', ([], {}), '()\n', (72406, 72408), True, 'import numpy as np\n'), ((72417, 72461), 'numpy.seterr', 'np.seterr', ([], {'divide': '"""ignore"""', 'invalid': '"""ignore"""'}), "(divide='ignore', invalid='ignore')\n", (72426, 72461), True, 'import numpy as np\n'), ((72495, 72523), 'numpy.seterr', 'np.seterr', ([], {}), '(**self.err_status)\n', (72504, 72523), True, 'import numpy as np\n'), ((74182, 74204), 'numpy.ma.core.masked_where', 'masked_where', (['(a < 5)', 'a'], {}), '(a < 5, a)\n', (74194, 74204), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((74597, 74649), 'numpy.ma.core.masked_array', 'masked_array', (['[-1, 0, 1, 2, 3]'], {'mask': '[0, 0, 0, 0, 1]'}), '([-1, 0, 1, 2, 3], mask=[0, 0, 0, 0, 1])\n', (74609, 74649), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((74665, 74675), 'numpy.sqrt', 'np.sqrt', (['a'], {}), '(a)\n', (74672, 74675), True, 'import numpy as np\n'), ((74796, 74823), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (74808, 74823), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((74832, 74869), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'control.mask'], {}), '(test.mask, control.mask)\n', (74844, 74869), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((75066, 75103), 'numpy.ma.core.masked_array', 'masked_array', (['[1.0, 2.0]'], {'mask': '[1, 0]'}), '([1.0, 2.0], mask=[1, 0])\n', (75078, 75103), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((75494, 75521), 'numpy.ma.testutils.assert_', 'assert_', (["(me * a == 'My mul')"], {}), "(me * a == 'My mul')\n", (75501, 75521), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((75530, 75558), 'numpy.ma.testutils.assert_', 'assert_', (["(a * me == 'My rmul')"], {}), "(a * me == 'My rmul')\n", (75537, 75558), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((76142, 76173), 'numpy.ma.testutils.assert_', 'assert_', (["(me_too * a == 'Me2mul')"], {}), "(me_too * a == 'Me2mul')\n", (76149, 76173), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((76182, 76214), 'numpy.ma.testutils.assert_', 'assert_', (["(a * me_too == 'Me2rmul')"], {}), "(a * me_too == 'Me2rmul')\n", (76189, 76214), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((76223, 76255), 'numpy.ma.testutils.assert_', 'assert_', (["(a / me_too == 'Me2rdiv')"], {}), "(a / me_too == 'Me2rdiv')\n", (76230, 76255), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((76399, 76438), 'numpy.ma.array', 'np.ma.array', (['[0.5, np.nan]'], {'mask': '[0, 1]'}), '([0.5, np.nan], mask=[0, 1])\n', (76410, 76438), True, 'import numpy as np\n'), ((77079, 77089), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (77085, 77089), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((77102, 77112), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (77108, 77112), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((77126, 77136), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (77132, 77136), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((77716, 77738), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y + 1)'], {}), '(x, y + 1)\n', (77728, 77738), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((77763, 77786), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y + 1)'], {}), '(xm, y + 1)\n', (77775, 77786), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((77882, 77917), 'numpy.ma.testutils.assert_', 'assert_', (['(id1 == x.data.ctypes._data)'], {}), '(id1 == x.data.ctypes._data)\n', (77889, 77917), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((77926, 77950), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y + 1.0)'], {}), '(x, y + 1.0)\n', (77938, 77950), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((78096, 78122), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 'np.int16'}), '(10, dtype=np.int16)\n', (78102, 78122), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((78185, 78207), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y + a)'], {}), '(x, y + a)\n', (78197, 78207), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((78216, 78239), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y + a)'], {}), '(xm, y + a)\n', (78228, 78239), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((78434, 78456), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y - 1)'], {}), '(x, y - 1)\n', (78446, 78456), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((78481, 78504), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y - 1)'], {}), '(xm, y - 1)\n', (78493, 78504), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((78659, 78682), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 'float'}), '(10, dtype=float)\n', (78665, 78682), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((78745, 78767), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y - a)'], {}), '(x, y - a)\n', (78757, 78767), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((78776, 78799), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y - a)'], {}), '(xm, y - a)\n', (78788, 78799), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((79003, 79025), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y * 2)'], {}), '(x, y * 2)\n', (79015, 79025), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((79052, 79075), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y * 2)'], {}), '(xm, y * 2)\n', (79064, 79075), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((79235, 79258), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 'float'}), '(10, dtype=float)\n', (79241, 79258), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((79321, 79343), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y * a)'], {}), '(x, y * a)\n', (79333, 79343), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((79352, 79375), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y * a)'], {}), '(xm, y * a)\n', (79364, 79375), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((79646, 79664), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', 'y'], {}), '(x, y)\n', (79658, 79664), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((79690, 79709), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', 'y'], {}), '(xm, y)\n', (79702, 79709), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((79857, 79881), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y / 2.0)'], {}), '(x, y / 2.0)\n', (79869, 79881), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((79896, 79906), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (79902, 79906), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((80098, 80121), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 'float'}), '(10, dtype=float)\n', (80104, 80121), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((80184, 80206), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y / a)'], {}), '(x, y / a)\n', (80196, 80206), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((80215, 80238), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y / a)'], {}), '(xm, y / a)\n', (80227, 80238), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((80601, 80625), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': 'm1'}), '(x, mask=m1)\n', (80613, 80625), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((80639, 80663), 'numpy.ma.core.masked_array', 'masked_array', (['y'], {'mask': 'm2'}), '(y, mask=m2)\n', (80651, 80663), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((80693, 80752), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z._mask', '[1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1]'], {}), '(z._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1])\n', (80705, 80752), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((80761, 80856), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z._data', '[1.0, 1.0, 1.0, -1.0, -pi / 2.0, 4.0, 5.0, 1.0, 1.0, 1.0, 2.0, 3.0]'], {}), '(z._data, [1.0, 1.0, 1.0, -1.0, -pi / 2.0, 4.0, 5.0, 1.0, 1.0, \n 1.0, 2.0, 3.0])\n', (80773, 80856), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((80910, 80970), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm._mask', '[1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1]'], {}), '(xm._mask, [1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 1])\n', (80922, 80970), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((80979, 81074), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z._data', '[1.0, 1.0, 1.0, -1.0, -pi / 2.0, 4.0, 5.0, 1.0, 1.0, 1.0, 2.0, 3.0]'], {}), '(z._data, [1.0, 1.0, 1.0, -1.0, -pi / 2.0, 4.0, 5.0, 1.0, 1.0, \n 1.0, 2.0, 3.0])\n', (80991, 81074), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((81179, 81211), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (81184, 81211), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((81268, 81300), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[2, 3, 3]'], {}), '(xx.data, [2, 3, 3])\n', (81280, 81300), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((81309, 81341), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[0, 0, 1]'], {}), '(xx.mask, [0, 0, 1])\n', (81321, 81341), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((81395, 81426), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[2, 3, 3]'], {}), '(x.data, [2, 3, 3])\n', (81407, 81426), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((81435, 81466), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[0, 0, 1]'], {}), '(x.mask, [0, 0, 1])\n', (81447, 81466), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((81507, 81539), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (81512, 81539), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((81598, 81630), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[1, 4, 3]'], {}), '(xx.data, [1, 4, 3])\n', (81610, 81630), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((81639, 81671), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[1, 0, 1]'], {}), '(xx.mask, [1, 0, 1])\n', (81651, 81671), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((81713, 81745), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (81718, 81745), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((81759, 81791), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]'}), '([1, 2, 3], mask=[1, 0, 0])\n', (81764, 81791), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((81800, 81831), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[1, 4, 3]'], {}), '(x.data, [1, 4, 3])\n', (81812, 81831), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((81840, 81871), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[1, 0, 1]'], {}), '(x.mask, [1, 0, 1])\n', (81852, 81871), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82004, 82036), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (82009, 82036), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((82064, 82096), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[0, 1, 3]'], {}), '(xx.data, [0, 1, 3])\n', (82076, 82096), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82105, 82137), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[0, 0, 1]'], {}), '(xx.mask, [0, 0, 1])\n', (82117, 82137), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82180, 82212), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (82185, 82212), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((82236, 82267), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[0, 1, 3]'], {}), '(x.data, [0, 1, 3])\n', (82248, 82267), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82276, 82307), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[0, 0, 1]'], {}), '(x.mask, [0, 0, 1])\n', (82288, 82307), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82348, 82380), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (82353, 82380), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((82439, 82471), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[1, 0, 3]'], {}), '(xx.data, [1, 0, 3])\n', (82451, 82471), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82480, 82512), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[1, 0, 1]'], {}), '(xx.mask, [1, 0, 1])\n', (82492, 82512), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82554, 82586), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (82559, 82586), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((82600, 82632), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]'}), '([1, 2, 3], mask=[1, 0, 0])\n', (82605, 82632), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((82641, 82672), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[1, 0, 3]'], {}), '(x.data, [1, 0, 3])\n', (82653, 82672), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82681, 82712), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[1, 0, 1]'], {}), '(x.mask, [1, 0, 1])\n', (82693, 82712), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82848, 82880), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (82853, 82880), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((82908, 82940), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[2, 4, 3]'], {}), '(xx.data, [2, 4, 3])\n', (82920, 82940), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((82949, 82981), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[0, 0, 1]'], {}), '(xx.mask, [0, 0, 1])\n', (82961, 82981), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83024, 83056), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (83029, 83056), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((83080, 83111), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[2, 4, 3]'], {}), '(x.data, [2, 4, 3])\n', (83092, 83111), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83120, 83151), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[0, 0, 1]'], {}), '(x.mask, [0, 0, 1])\n', (83132, 83151), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83192, 83224), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (83197, 83224), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((83286, 83319), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[1, 40, 3]'], {}), '(xx.data, [1, 40, 3])\n', (83298, 83319), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83328, 83360), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[1, 0, 1]'], {}), '(xx.mask, [1, 0, 1])\n', (83340, 83360), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83402, 83434), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (83407, 83434), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((83448, 83483), 'numpy.ma.core.array', 'array', (['[10, 20, 30]'], {'mask': '[1, 0, 0]'}), '([10, 20, 30], mask=[1, 0, 0])\n', (83453, 83483), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((83492, 83524), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[1, 40, 3]'], {}), '(x.data, [1, 40, 3])\n', (83504, 83524), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83533, 83564), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[1, 0, 1]'], {}), '(x.mask, [1, 0, 1])\n', (83545, 83564), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83694, 83726), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (83699, 83726), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((83755, 83799), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[1 / 2.0, 2 / 2.0, 3]'], {}), '(xx.data, [1 / 2.0, 2 / 2.0, 3])\n', (83767, 83799), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83806, 83838), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[0, 0, 1]'], {}), '(xx.mask, [0, 0, 1])\n', (83818, 83838), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83881, 83919), 'numpy.ma.core.array', 'array', (['[1.0, 2.0, 3.0]'], {'mask': '[0, 0, 1]'}), '([1.0, 2.0, 3.0], mask=[0, 0, 1])\n', (83886, 83919), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((83941, 83984), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[1 / 2.0, 2 / 2.0, 3]'], {}), '(x.data, [1 / 2.0, 2 / 2.0, 3])\n', (83953, 83984), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((83991, 84022), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[0, 0, 1]'], {}), '(x.mask, [0, 0, 1])\n', (84003, 84022), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84063, 84101), 'numpy.ma.core.array', 'array', (['[1.0, 2.0, 3.0]'], {'mask': '[0, 0, 1]'}), '([1.0, 2.0, 3.0], mask=[0, 0, 1])\n', (84068, 84101), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((84163, 84208), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[1.0, 2.0 / 20.0, 3.0]'], {}), '(xx.data, [1.0, 2.0 / 20.0, 3.0])\n', (84175, 84208), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84213, 84245), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[1, 0, 1]'], {}), '(xx.mask, [1, 0, 1])\n', (84225, 84245), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84287, 84325), 'numpy.ma.core.array', 'array', (['[1.0, 2.0, 3.0]'], {'mask': '[0, 0, 1]'}), '([1.0, 2.0, 3.0], mask=[0, 0, 1])\n', (84292, 84325), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((84336, 84377), 'numpy.ma.core.array', 'array', (['[10.0, 20.0, 30.0]'], {'mask': '[1, 0, 0]'}), '([10.0, 20.0, 30.0], mask=[1, 0, 0])\n', (84341, 84377), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((84383, 84425), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[1.0, 2 / 20.0, 3.0]'], {}), '(x.data, [1.0, 2 / 20.0, 3.0])\n', (84395, 84425), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84431, 84462), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[1, 0, 1]'], {}), '(x.mask, [1, 0, 1])\n', (84443, 84462), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84589, 84627), 'numpy.ma.core.array', 'array', (['[1.0, 2.0, 3.0]'], {'mask': '[0, 0, 1]'}), '([1.0, 2.0, 3.0], mask=[0, 0, 1])\n', (84594, 84627), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((84655, 84700), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', '[1.0, 2.0 ** 2.5, 3.0]'], {}), '(xx.data, [1.0, 2.0 ** 2.5, 3.0])\n', (84667, 84700), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84706, 84738), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', '[0, 0, 1]'], {}), '(xx.mask, [0, 0, 1])\n', (84718, 84738), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84795, 84837), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', '[1.0, 2.0 ** 2.5, 3]'], {}), '(x.data, [1.0, 2.0 ** 2.5, 3])\n', (84807, 84837), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84844, 84875), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[0, 0, 1]'], {}), '(x.mask, [0, 0, 1])\n', (84856, 84875), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((84933, 84956), 'numpy.ma.core.array', 'array', (['[[1, 1], [3, 3]]'], {}), '([[1, 1], [3, 3]])\n', (84938, 84956), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((84969, 84995), 'numpy.ma.core.array', 'array', (['[1, 1]'], {'mask': '[0, 0]'}), '([1, 1], mask=[0, 0])\n', (84974, 84995), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85019, 85052), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[2, 2], [4, 4]]'], {}), '(a, [[2, 2], [4, 4]])\n', (85031, 85052), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((85150, 85173), 'numpy.ma.core.array', 'array', (['[[1, 1], [3, 3]]'], {}), '([[1, 1], [3, 3]])\n', (85155, 85173), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85186, 85212), 'numpy.ma.core.array', 'array', (['[1, 1]'], {'mask': '[0, 1]'}), '([1, 1], mask=[0, 1])\n', (85191, 85212), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85236, 85269), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[2, 2], [4, 4]]'], {}), '(a, [[2, 2], [4, 4]])\n', (85248, 85269), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((85278, 85316), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[[0, 1], [0, 1]]'], {}), '(a.mask, [[0, 1], [0, 1]])\n', (85290, 85316), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((85374, 85397), 'numpy.ma.core.array', 'array', (['[[1, 1], [3, 3]]'], {}), '([[1, 1], [3, 3]])\n', (85379, 85397), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85410, 85436), 'numpy.ma.core.array', 'array', (['[1, 1]'], {'mask': '[0, 0]'}), '([1, 1], mask=[0, 0])\n', (85415, 85436), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85460, 85493), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[0, 0], [2, 2]]'], {}), '(a, [[0, 0], [2, 2]])\n', (85472, 85493), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((85591, 85614), 'numpy.ma.core.array', 'array', (['[[1, 1], [3, 3]]'], {}), '([[1, 1], [3, 3]])\n', (85596, 85614), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85627, 85653), 'numpy.ma.core.array', 'array', (['[1, 1]'], {'mask': '[0, 1]'}), '([1, 1], mask=[0, 1])\n', (85632, 85653), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85677, 85710), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[0, 0], [2, 2]]'], {}), '(a, [[0, 0], [2, 2]])\n', (85689, 85710), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((85719, 85757), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[[0, 1], [0, 1]]'], {}), '(a.mask, [[0, 1], [0, 1]])\n', (85731, 85757), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((85815, 85838), 'numpy.ma.core.array', 'array', (['[[1, 1], [3, 3]]'], {}), '([[1, 1], [3, 3]])\n', (85820, 85838), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85851, 85877), 'numpy.ma.core.array', 'array', (['[1, 1]'], {'mask': '[0, 0]'}), '([1, 1], mask=[0, 0])\n', (85856, 85877), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85901, 85934), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[1, 1], [3, 3]]'], {}), '(a, [[1, 1], [3, 3]])\n', (85913, 85934), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((86032, 86055), 'numpy.ma.core.array', 'array', (['[[1, 1], [3, 3]]'], {}), '([[1, 1], [3, 3]])\n', (86037, 86055), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((86068, 86094), 'numpy.ma.core.array', 'array', (['[1, 1]'], {'mask': '[0, 1]'}), '([1, 1], mask=[0, 1])\n', (86073, 86094), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((86118, 86151), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[1, 1], [3, 3]]'], {}), '(a, [[1, 1], [3, 3]])\n', (86130, 86151), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((86160, 86198), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[[0, 1], [0, 1]]'], {}), '(a.mask, [[0, 1], [0, 1]])\n', (86172, 86198), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((95177, 95447), 'numpy.array', 'np.array', (['[8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, \n 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, \n 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, \n 9.828, 6.272, 3.758, 6.693, 0.993]'], {}), '([8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878,\n 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, \n 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, \n 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])\n', (95185, 95447), True, 'import numpy as np\n'), ((95620, 95742), 'numpy.array', 'np.array', (['[0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1,\n 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]'], {}), '([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0])\n', (95628, 95742), True, 'import numpy as np\n'), ((95857, 95878), 'numpy.ma.core.array', 'array', ([], {'data': 'x', 'mask': 'm'}), '(data=x, mask=m)\n', (95862, 95878), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((96000, 96122), 'numpy.array', 'np.array', (['[1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1,\n 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]'], {}), '([1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1,\n 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1])\n', (96008, 96122), True, 'import numpy as np\n'), ((96243, 96265), 'numpy.ma.core.array', 'array', ([], {'data': 'x', 'mask': 'm2'}), '(data=x, mask=m2)\n', (96248, 96265), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((96528, 96544), 'numpy.ma.core.array', 'array', (['[1, 3, 2]'], {}), '([1, 3, 2])\n', (96533, 96544), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((97004, 97027), 'numpy.ma.core.array', 'array', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (97009, 97027), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((97321, 97339), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (97335, 97339), True, 'import numpy as np\n'), ((97628, 97643), 'numpy.ma.core.masked_array', 'masked_array', (['a'], {}), '(a)\n', (97640, 97643), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((98186, 98254), 'numpy.array', 'np.array', (['[[0.13, 0.26, 0.9], [0.28, 0.33, 0.63], [0.31, 0.87, 0.7]]'], {}), '([[0.13, 0.26, 0.9], [0.28, 0.33, 0.63], [0.31, 0.87, 0.7]])\n', (98194, 98254), True, 'import numpy as np\n'), ((98313, 98409), 'numpy.array', 'np.array', (['[[True, False, False], [False, False, False], [True, True, False]]'], {'dtype': 'np.bool_'}), '([[True, False, False], [False, False, False], [True, True, False]],\n dtype=np.bool_)\n', (98321, 98409), True, 'import numpy as np\n'), ((98463, 98486), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': 'm'}), '(x, mask=m)\n', (98475, 98486), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((99210, 99278), 'numpy.array', 'np.array', (['[[0.13, 0.26, 0.9], [0.28, 0.33, 0.63], [0.31, 0.87, 0.7]]'], {}), '([[0.13, 0.26, 0.9], [0.28, 0.33, 0.63], [0.31, 0.87, 0.7]])\n', (99218, 99278), True, 'import numpy as np\n'), ((99337, 99349), 'numpy.matrix', 'np.matrix', (['x'], {}), '(x)\n', (99346, 99349), True, 'import numpy as np\n'), ((99362, 99458), 'numpy.array', 'np.array', (['[[True, False, False], [False, False, False], [True, True, False]]'], {'dtype': 'np.bool_'}), '([[True, False, False], [False, False, False], [True, True, False]],\n dtype=np.bool_)\n', (99370, 99458), True, 'import numpy as np\n'), ((99512, 99535), 'numpy.ma.core.masked_array', 'masked_array', (['X'], {'mask': 'm'}), '(X, mask=m)\n', (99524, 99535), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((100393, 100414), 'numpy.ma.core.empty', 'empty', (['()'], {'dtype': 'bool'}), '((), dtype=bool)\n', (100398, 100414), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((100430, 100457), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '(True)'}), '([1, 2, 3], mask=True)\n', (100435, 100457), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((100669, 100690), 'numpy.ma.core.empty', 'empty', (['()'], {'dtype': 'bool'}), '((), dtype=bool)\n', (100674, 100690), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((101863, 102133), 'numpy.array', 'np.array', (['[8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, \n 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, \n 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, \n 9.828, 6.272, 3.758, 6.693, 0.993]'], {}), '([8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878,\n 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, \n 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, \n 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])\n', (101871, 102133), True, 'import numpy as np\n'), ((102242, 102364), 'numpy.array', 'np.array', (['[0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1,\n 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]'], {}), '([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0])\n', (102250, 102364), True, 'import numpy as np\n'), ((102418, 102434), 'numpy.ma.core.array', 'array', (['x'], {'mask': 'm'}), '(x, mask=m)\n', (102423, 102434), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((102475, 102510), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['clipped.mask', 'mx.mask'], {}), '(clipped.mask, mx.mask)\n', (102487, 102510), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((102684, 102740), 'numpy.ma.core.masked_array', 'masked_array', (['[1.0, 2.0, 3.0, 4.0, 5.0]'], {'fill_value': '(9999)'}), '([1.0, 2.0, 3.0, 4.0, 5.0], fill_value=9999)\n', (102696, 102740), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((102902, 102935), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._data', '[2.0, 3.0]'], {}), '(b._data, [2.0, 3.0])\n', (102914, 102935), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((102942, 102971), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._mask', '[0, 1]'], {}), '(b._mask, [0, 1])\n', (102954, 102971), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((102980, 103012), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.fill_value', '(9999)'], {}), '(b.fill_value, 9999)\n', (102992, 103012), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103021, 103050), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b', 'a[condition]'], {}), '(b, a[condition])\n', (103033, 103050), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103123, 103161), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._data', '[1.0, 2.0, 3.0]'], {}), '(b._data, [1.0, 2.0, 3.0])\n', (103135, 103161), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103167, 103199), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._mask', '[0, 0, 1]'], {}), '(b._mask, [0, 0, 1])\n', (103179, 103199), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103208, 103240), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.fill_value', '(9999)'], {}), '(b.fill_value, 9999)\n', (103220, 103240), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103249, 103278), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b', 'a[condition]'], {}), '(b, a[condition])\n', (103261, 103278), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103292, 103363), 'numpy.ma.core.masked_array', 'masked_array', (['[[10, 20, 30], [40, 50, 60]]'], {'mask': '[[0, 0, 1], [1, 0, 0]]'}), '([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0]])\n', (103304, 103363), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((103437, 103476), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._data', '[30, 40, 50, 60]'], {}), '(b._data, [30, 40, 50, 60])\n', (103449, 103476), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103485, 103520), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._mask', '[1, 1, 0, 0]'], {}), '(b._mask, [1, 1, 0, 0])\n', (103497, 103520), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103534, 103553), 'numpy.array', 'np.array', (['[3, 1, 2]'], {}), '([3, 1, 2])\n', (103542, 103553), True, 'import numpy as np\n'), ((103601, 103644), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._data', '[[10, 30], [40, 60]]'], {}), '(b._data, [[10, 30], [40, 60]])\n', (103613, 103644), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103653, 103692), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b._mask', '[[0, 1], [1, 0]]'], {}), '(b._mask, [[0, 1], [1, 0]])\n', (103665, 103692), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103764, 103802), 'numpy.ma.core.array', 'array', (['[1, 2, 3, 4]'], {'mask': '[0, 0, 0, 0]'}), '([1, 2, 3, 4], mask=[0, 0, 0, 0])\n', (103769, 103802), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((103838, 103856), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b', 'a'], {}), '(b, a)\n', (103850, 103856), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((103914, 103940), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b', '[2, 3, 4]'], {}), '(b, [2, 3, 4])\n', (103926, 103940), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((104039, 104057), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b', 'a'], {}), '(b, a)\n', (104051, 104057), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((104168, 104196), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b', '[[2, 3, 4]]'], {}), '(b, [[2, 3, 4]])\n', (104180, 104196), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((104323, 104409), 'numpy.ma.core.masked_array', 'masked_array', (["[(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')]"], {'dtype': 'datatype'}), "([(1, 1.1, '1.1'), (2, 2.2, '2.2'), (3, 3.3, '3.3')], dtype=\n datatype)\n", (104335, 104409), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((104505, 104518), 'numpy.ma.core.empty_like', 'empty_like', (['a'], {}), '(a)\n', (104515, 104518), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((104527, 104557), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.shape', 'a.shape'], {}), '(b.shape, a.shape)\n', (104539, 104557), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((104566, 104606), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.fill_value', 'a.fill_value'], {}), '(b.fill_value, a.fill_value)\n', (104578, 104606), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((104658, 104688), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.shape', 'a.shape'], {}), '(b.shape, a.shape)\n', (104670, 104688), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((104697, 104737), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.fill_value', 'a.fill_value'], {}), '(b.fill_value, a.fill_value)\n', (104709, 104737), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((104792, 104842), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]'], {'mask': '[False, True, False]'}), '([1, 2, 3], mask=[False, True, False])\n', (104804, 104842), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((104855, 104868), 'numpy.ma.core.empty_like', 'empty_like', (['a'], {}), '(a)\n', (104865, 104868), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((105070, 105079), 'numpy.ma.core.arange', 'arange', (['(5)'], {}), '(5)\n', (105076, 105079), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((105120, 105132), 'numpy.ma.core.make_mask', 'make_mask', (['n'], {}), '(n)\n', (105129, 105132), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((105145, 105161), 'numpy.ma.core.array', 'array', (['d'], {'mask': 'm'}), '(d, mask=m)\n', (105150, 105161), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((105363, 105398), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '[0, 10, 2, -1, 40]'], {}), '(x, [0, 10, 2, -1, 40])\n', (105375, 105398), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((105594, 105646), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[0, 0, 0, 0, 0, 1, 0, 0, 0, 0]'], {}), '(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])\n', (105606, 105646), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((105714, 105767), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['x', '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'], {}), '(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n', (105732, 105767), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((105778, 105830), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[1, 0, 0, 0, 1, 1, 0, 0, 0, 0]'], {}), '(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0])\n', (105790, 105830), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((105903, 105926), 'numpy.ma.core.put', 'put', (['x', 'i', '[6, 4, 2, 0]'], {}), '(x, i, [6, 4, 2, 0])\n', (105906, 105926), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((106002, 106054), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[0, 0, 0, 0, 0, 1, 0, 0, 0, 0]'], {}), '(x.mask, [0, 0, 0, 0, 0, 1, 0, 0, 0, 0])\n', (106014, 106054), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((106123, 106176), 'numpy.ma.testutils.assert_array_equal', 'assert_array_equal', (['x', '[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]'], {}), '(x, [0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n', (106141, 106176), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((106187, 106239), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', '[1, 0, 0, 0, 1, 1, 0, 0, 0, 0]'], {}), '(x.mask, [1, 0, 0, 0, 1, 1, 0, 0, 0, 0])\n', (106199, 106239), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((106312, 106321), 'numpy.ma.core.zeros', 'zeros', (['(10)'], {}), '(10)\n', (106317, 106321), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((106334, 106372), 'numpy.ma.core.array', 'array', (['[3.0, -1.0]'], {'mask': '[False, True]'}), '([3.0, -1.0], mask=[False, True])\n', (106339, 106372), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((106449, 106470), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x[0]', '(0)'], {}), '(x[0], 0)\n', (106461, 106470), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((106523, 106544), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x[1]', '(3)'], {}), '(x[1], 3)\n', (106535, 106544), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((106637, 106658), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x[3]', '(0)'], {}), '(x[3], 0)\n', (106649, 106658), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((106737, 106746), 'numpy.ma.core.arange', 'arange', (['(5)'], {}), '(5)\n', (106743, 106746), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((106787, 106799), 'numpy.ma.core.make_mask', 'make_mask', (['n'], {}), '(n)\n', (106796, 106799), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((106813, 106860), 'numpy.ma.core.array', 'array', (['(d + 1)'], {'mask': 'm', 'hard_mask': '(True)', 'copy': '(True)'}), '(d + 1, mask=m, hard_mask=True, copy=True)\n', (106818, 106860), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((106918, 106957), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xh._data', '[3, 4, 2, 4, 5]'], {}), '(xh._data, [3, 4, 2, 4, 5])\n', (106930, 106957), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((107026, 107059), 'numpy.ma.core.array', 'array', (['x'], {'mask': '[0, 0, 0, 1, 1, 1]'}), '(x, mask=[0, 0, 0, 1, 1, 1])\n', (107031, 107059), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((107162, 107183), 'numpy.ma.core.putmask', 'putmask', (['xx', 'mask', '(99)'], {}), '(xx, mask, 99)\n', (107169, 107183), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((107192, 107230), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx', '[1, 2, 99, 4, 5, 99]'], {}), '(xx, [1, 2, 99, 4, 5, 99])\n', (107204, 107230), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((107300, 107322), 'numpy.ma.core.putmask', 'putmask', (['mxx', 'mask', '(99)'], {}), '(mxx, mask, 99)\n', (107307, 107322), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((107331, 107376), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mxx._data', '[1, 2, 99, 4, 5, 99]'], {}), '(mxx._data, [1, 2, 99, 4, 5, 99])\n', (107343, 107376), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((107385, 107428), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mxx._mask', '[0, 0, 0, 1, 1, 0]'], {}), '(mxx._mask, [0, 0, 0, 1, 1, 0])\n', (107397, 107428), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((107483, 107539), 'numpy.ma.core.array', 'array', (['[10, 20, 30, 40, 50, 60]'], {'mask': '[1, 1, 1, 0, 0, 0]'}), '([10, 20, 30, 40, 50, 60], mask=[1, 1, 1, 0, 0, 0])\n', (107488, 107539), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((107570, 107595), 'numpy.ma.core.putmask', 'putmask', (['xx', 'mask', 'values'], {}), '(xx, mask, values)\n', (107577, 107595), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((107604, 107648), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx._data', '[1, 2, 30, 4, 5, 60]'], {}), '(xx._data, [1, 2, 30, 4, 5, 60])\n', (107616, 107648), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((107657, 107699), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx._mask', '[0, 0, 1, 0, 0, 0]'], {}), '(xx._mask, [0, 0, 1, 0, 0, 0])\n', (107669, 107699), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((107768, 107794), 'numpy.ma.core.putmask', 'putmask', (['mxx', 'mask', 'values'], {}), '(mxx, mask, values)\n', (107775, 107794), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((107803, 107848), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mxx._data', '[1, 2, 30, 4, 5, 60]'], {}), '(mxx._data, [1, 2, 30, 4, 5, 60])\n', (107815, 107848), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((107857, 107900), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mxx._mask', '[0, 0, 1, 1, 1, 0]'], {}), '(mxx._mask, [0, 0, 1, 1, 1, 0])\n', (107869, 107900), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((108006, 108032), 'numpy.ma.core.putmask', 'putmask', (['mxx', 'mask', 'values'], {}), '(mxx, mask, values)\n', (108013, 108032), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((108041, 108080), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mxx', '[1, 2, 30, 4, 5, 60]'], {}), '(mxx, [1, 2, 30, 4, 5, 60])\n', (108053, 108080), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((108142, 108190), 'numpy.ma.core.array', 'array', (['[[1, 2, 3, 4, 5]]'], {'mask': '[[0, 1, 0, 0, 0]]'}), '([[1, 2, 3, 4, 5]], mask=[[0, 1, 0, 0, 0]])\n', (108147, 108190), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((108226, 108272), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['aravel._mask.shape', 'aravel.shape'], {}), '(aravel._mask.shape, aravel.shape)\n', (108238, 108272), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((108285, 108311), 'numpy.ma.core.array', 'array', (['[0, 0]'], {'mask': '[1, 1]'}), '([0, 0], mask=[1, 1])\n', (108290, 108311), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((108347, 108388), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['aravel._mask.shape', 'a.shape'], {}), '(aravel._mask.shape, a.shape)\n', (108359, 108388), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((108494, 108528), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['aravel.shape', '(1, 5)'], {}), '(aravel.shape, (1, 5))\n', (108506, 108528), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((108537, 108578), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['aravel._mask.shape', 'a.shape'], {}), '(aravel._mask.shape, a.shape)\n', (108549, 108578), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((108637, 108689), 'numpy.ma.core.array', 'array', (['[1, 2, 3, 4]'], {'mask': '[0, 0, 0, 0]', 'shrink': '(False)'}), '([1, 2, 3, 4], mask=[0, 0, 0, 0], shrink=False)\n', (108642, 108689), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((108873, 108909), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['ar._mask', '[0, 0, 0, 0]'], {}), '(ar._mask, [0, 0, 0, 0])\n', (108885, 108909), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((108918, 108954), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['ar._data', '[1, 2, 3, 4]'], {}), '(ar._data, [1, 2, 3, 4])\n', (108930, 108954), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((108963, 108995), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['ar.fill_value', '(-99)'], {}), '(ar.fill_value, -99)\n', (108975, 108995), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109201, 109210), 'numpy.ma.core.arange', 'arange', (['(4)'], {}), '(4)\n', (109207, 109210), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((109269, 109298), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y.shape', '(2, 2)'], {}), '(y.shape, (2, 2))\n', (109281, 109298), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109308, 109343), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y._mask.shape', '(2, 2)'], {}), '(y._mask.shape, (2, 2))\n', (109320, 109343), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109353, 109380), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.shape', '(4,)'], {}), '(x.shape, (4,))\n', (109365, 109380), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109389, 109422), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._mask.shape', '(4,)'], {}), '(x._mask.shape, (4,))\n', (109401, 109422), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109481, 109535), 'numpy.ma.core.array', 'array', (['[1, 4, 2, 3]'], {'mask': '[0, 1, 0, 0]', 'dtype': 'np.uint8'}), '([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)\n', (109486, 109535), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((109555, 109562), 'numpy.ma.core.sort', 'sort', (['x'], {}), '(x)\n', (109559, 109562), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((109571, 109612), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['sortedx._data', '[1, 2, 3, 4]'], {}), '(sortedx._data, [1, 2, 3, 4])\n', (109583, 109612), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109621, 109662), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['sortedx._mask', '[0, 0, 0, 1]'], {}), '(sortedx._mask, [0, 0, 0, 1])\n', (109633, 109662), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109682, 109704), 'numpy.ma.core.sort', 'sort', (['x'], {'endwith': '(False)'}), '(x, endwith=False)\n', (109686, 109704), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((109713, 109754), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['sortedx._data', '[4, 1, 2, 3]'], {}), '(sortedx._data, [4, 1, 2, 3])\n', (109725, 109754), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109763, 109804), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['sortedx._mask', '[1, 0, 0, 0]'], {}), '(sortedx._mask, [1, 0, 0, 0])\n', (109775, 109804), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109831, 109866), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._data', '[1, 2, 3, 4]'], {}), '(x._data, [1, 2, 3, 4])\n', (109843, 109866), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109875, 109910), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._mask', '[0, 0, 0, 1]'], {}), '(x._mask, [0, 0, 0, 1])\n', (109887, 109910), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((109924, 109978), 'numpy.ma.core.array', 'array', (['[1, 4, 2, 3]'], {'mask': '[0, 1, 0, 0]', 'dtype': 'np.uint8'}), '([1, 4, 2, 3], mask=[0, 1, 0, 0], dtype=np.uint8)\n', (109929, 109978), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((110017, 110052), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._data', '[4, 1, 2, 3]'], {}), '(x._data, [4, 1, 2, 3])\n', (110029, 110052), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((110061, 110096), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._mask', '[1, 0, 0, 0]'], {}), '(x._mask, [1, 0, 0, 0])\n', (110073, 110096), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((110141, 110148), 'numpy.ma.core.sort', 'sort', (['x'], {}), '(x)\n', (110145, 110148), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((110223, 110275), 'numpy.ma.core.array', 'array', (['[0, 1, -1, -2, 2]'], {'mask': 'nomask', 'dtype': 'np.int8'}), '([0, 1, -1, -2, 2], mask=nomask, dtype=np.int8)\n', (110228, 110275), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((110294, 110316), 'numpy.ma.core.sort', 'sort', (['x'], {'endwith': '(False)'}), '(x, endwith=False)\n', (110298, 110316), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((110325, 110371), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['sortedx._data', '[-2, -1, 0, 1, 2]'], {}), '(sortedx._data, [-2, -1, 0, 1, 2])\n', (110337, 110371), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((110384, 110445), 'numpy.ma.core.array', 'array', (['[0, 1, -1, -2, 2]'], {'mask': '[0, 1, 0, 0, 1]', 'dtype': 'np.int8'}), '([0, 1, -1, -2, 2], mask=[0, 1, 0, 0, 1], dtype=np.int8)\n', (110389, 110445), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((110464, 110486), 'numpy.ma.core.sort', 'sort', (['x'], {'endwith': '(False)'}), '(x, endwith=False)\n', (110468, 110486), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((110495, 110541), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['sortedx._data', '[1, 2, -2, -1, 0]'], {}), '(sortedx._data, [1, 2, -2, -1, 0])\n', (110507, 110541), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((110550, 110594), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['sortedx._mask', '[1, 1, 0, 0, 0]'], {}), '(sortedx._mask, [1, 1, 0, 0, 0])\n', (110562, 110594), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((110698, 110734), 'numpy.ma.core.masked_array', 'masked_array', (['[[8, 4, 1], [2, 0, 9]]'], {}), '([[8, 4, 1], [2, 0, 9]])\n', (110710, 110734), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((110761, 110800), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[2, 0, 1], [8, 4, 9]]'], {}), '(a, [[2, 0, 1], [8, 4, 9]])\n', (110773, 110800), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((110813, 110849), 'numpy.ma.core.masked_array', 'masked_array', (['[[8, 4, 1], [2, 0, 9]]'], {}), '([[8, 4, 1], [2, 0, 9]])\n', (110825, 110849), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((110876, 110915), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[1, 4, 8], [0, 2, 9]]'], {}), '(a, [[1, 4, 8], [0, 2, 9]])\n', (110888, 110915), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((110954, 111019), 'numpy.ma.core.masked_array', 'masked_array', (['[[8, 4, 1], [2, 0, 9]]'], {'mask': '[[1, 0, 0], [0, 0, 1]]'}), '([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]])\n', (110966, 111019), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((111046, 111085), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[2, 0, 1], [8, 4, 9]]'], {}), '(a, [[2, 0, 1], [8, 4, 9]])\n', (111058, 111085), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((111094, 111139), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a._mask', '[[0, 0, 0], [1, 0, 1]]'], {}), '(a._mask, [[0, 0, 0], [1, 0, 1]])\n', (111106, 111139), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((111152, 111217), 'numpy.ma.core.masked_array', 'masked_array', (['[[8, 4, 1], [2, 0, 9]]'], {'mask': '[[1, 0, 0], [0, 0, 1]]'}), '([[8, 4, 1], [2, 0, 9]], mask=[[1, 0, 0], [0, 0, 1]])\n', (111164, 111217), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((111244, 111283), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a', '[[1, 4, 8], [0, 2, 9]]'], {}), '(a, [[1, 4, 8], [0, 2, 9]])\n', (111256, 111283), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((111292, 111337), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a._mask', '[[0, 0, 1], [0, 0, 1]]'], {}), '(a._mask, [[0, 0, 1], [0, 0, 1]])\n', (111304, 111337), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((111363, 111525), 'numpy.ma.core.masked_array', 'masked_array', (['[[[7, 8, 9], [4, 5, 6], [1, 2, 3]], [[1, 2, 3], [7, 8, 9], [4, 5, 6]], [[7,\n 8, 9], [1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3], [7, 8, 9]]]'], {}), '([[[7, 8, 9], [4, 5, 6], [1, 2, 3]], [[1, 2, 3], [7, 8, 9], [4,\n 5, 6]], [[7, 8, 9], [1, 2, 3], [4, 5, 6]], [[4, 5, 6], [1, 2, 3], [7, 8,\n 9]]])\n', (111375, 111525), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((111721, 111741), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['am', 'an'], {}), '(am, an)\n', (111733, 111741), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((111836, 111856), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['am', 'an'], {}), '(am, an)\n', (111848, 111856), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((111951, 111971), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['am', 'an'], {}), '(am, an)\n', (111963, 111971), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((112058, 112230), 'numpy.ma.core.array', 'array', ([], {'data': '[(3, 3), (3, 2), (2, 2), (2, 1), (1, 0), (1, 1), (1, 2)]', 'mask': '[(0, 0), (0, 1), (0, 0), (0, 0), (1, 0), (0, 0), (0, 0)]', 'dtype': "[('A', int), ('B', int)]"}), "(data=[(3, 3), (3, 2), (2, 2), (2, 1), (1, 0), (1, 1), (1, 2)], mask=[\n (0, 0), (0, 1), (0, 0), (0, 0), (1, 0), (0, 0), (0, 0)], dtype=[('A',\n int), ('B', int)])\n", (112063, 112230), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((112275, 112282), 'numpy.ma.core.sort', 'sort', (['a'], {}), '(a)\n', (112279, 112282), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((112295, 112467), 'numpy.ma.core.array', 'array', ([], {'data': '[(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 2), (1, 0)]', 'mask': '[(0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (1, 0)]', 'dtype': "[('A', int), ('B', int)]"}), "(data=[(1, 1), (1, 2), (2, 1), (2, 2), (3, 3), (3, 2), (1, 0)], mask=[\n (0, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (1, 0)], dtype=[('A',\n int), ('B', int)])\n", (112300, 112467), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((112504, 112525), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'b'], {}), '(test, b)\n', (112516, 112525), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((112534, 112565), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'b.mask'], {}), '(test.mask, b.mask)\n', (112546, 112565), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((112582, 112604), 'numpy.ma.core.sort', 'sort', (['a'], {'endwith': '(False)'}), '(a, endwith=False)\n', (112586, 112604), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((112617, 112789), 'numpy.ma.core.array', 'array', ([], {'data': '[(1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (3, 2), (3, 3)]', 'mask': '[(1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (0, 0)]', 'dtype': "[('A', int), ('B', int)]"}), "(data=[(1, 0), (1, 1), (1, 2), (2, 1), (2, 2), (3, 2), (3, 3)], mask=[\n (1, 0), (0, 0), (0, 0), (0, 0), (0, 0), (0, 1), (0, 0)], dtype=[('A',\n int), ('B', int)])\n", (112622, 112789), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((112830, 112851), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'b'], {}), '(test, b)\n', (112842, 112851), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((112860, 112891), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'b.mask'], {}), '(test.mask, b.mask)\n', (112872, 112891), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((112956, 113000), 'numpy.ma.core.array', 'array', (['[1, 5, 2, 4, 3]'], {'mask': '[1, 0, 0, 1, 0]'}), '([1, 5, 2, 4, 3], mask=[1, 0, 0, 1, 0])\n', (112961, 113000), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((113117, 113142), 'numpy.ma.core.masked_array', 'masked_array', (['[[1, 2, 3]]'], {}), '([[1, 2, 3]])\n', (113129, 113142), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((113206, 113249), 'numpy.ma.core.masked_array', 'masked_array', (['[[1, 2, 3]]'], {'mask': '[[1, 1, 1]]'}), '([[1, 2, 3]], mask=[[1, 1, 1]])\n', (113218, 113249), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((113367, 113397), 'numpy.ma.core.masked_array', 'masked_array', (['[[1]]'], {'mask': '(True)'}), '([[1]], mask=True)\n', (113379, 113397), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((113532, 113802), 'numpy.array', 'np.array', (['[8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, \n 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, \n 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, \n 9.828, 6.272, 3.758, 6.693, 0.993]'], {}), '([8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878,\n 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, \n 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, \n 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])\n', (113540, 113802), True, 'import numpy as np\n'), ((113911, 114033), 'numpy.array', 'np.array', (['[0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1,\n 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]'], {}), '([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0])\n', (113919, 114033), True, 'import numpy as np\n'), ((114268, 114306), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mXswapped[-1]', 'mX[:, -1]'], {}), '(mXswapped[-1], mX[:, -1])\n', (114280, 114306), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((114356, 114400), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mXXswapped.shape', '(2, 2, 3, 3)'], {}), '(mXXswapped.shape, (2, 2, 3, 3))\n', (114368, 114400), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((114460, 114504), 'numpy.ma.core.masked_array', 'masked_array', (['[10, 20, 30, 40]', '[0, 1, 0, 1]'], {}), '([10, 20, 30, 40], [0, 1, 0, 1])\n', (114472, 114504), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((114917, 114981), 'numpy.ma.core.array', 'array', (['[[10, 20, 30], [40, 50, 60]]'], {'mask': '[[0, 0, 1], [1, 0, 0]]'}), '([[10, 20, 30], [40, 50, 60]], mask=[[0, 0, 1], [1, 0, 0]])\n', (114922, 114981), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((115312, 115341), 'numpy.array', 'np.array', (['(40, 18, 37, 9, 22)'], {}), '((40, 18, 37, 9, 22))\n', (115320, 115341), True, 'import numpy as np\n'), ((115498, 115528), 'numpy.ma.core.take', 'take', (['a', 'mindices'], {'mode': '"""clip"""'}), "(a, mindices, mode='clip')\n", (115502, 115528), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((115544, 115618), 'numpy.ma.core.array', 'array', (['[[40, 18, 37], [18, 37, 9], [37, 9, 22], [9, 22, 22], [22, 22, 22]]'], {}), '([[40, 18, 37], [18, 37, 9], [37, 9, 22], [9, 22, 22], [22, 22, 22]])\n', (115549, 115618), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((115715, 115739), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'ctrl'], {}), '(test, ctrl)\n', (115727, 115739), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((115780, 115797), 'numpy.ma.core.take', 'take', (['a', 'mindices'], {}), '(a, mindices)\n', (115784, 115797), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((115813, 115887), 'numpy.ma.core.array', 'array', (['[[40, 18, 37], [18, 37, 9], [37, 9, 22], [9, 22, 40], [22, 40, 40]]'], {}), '([[40, 18, 37], [18, 37, 9], [37, 9, 22], [9, 22, 40], [22, 40, 40]])\n', (115818, 115887), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((116038, 116062), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'ctrl'], {}), '(test, ctrl)\n', (116050, 116062), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((116071, 116105), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'ctrl.mask'], {}), '(test.mask, ctrl.mask)\n', (116083, 116105), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((116158, 116206), 'numpy.ma.core.array', 'array', (['(40, 18, 37, 9, 22)'], {'mask': '(0, 1, 0, 0, 0)'}), '((40, 18, 37, 9, 22), mask=(0, 1, 0, 0, 0))\n', (116163, 116206), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((116222, 116239), 'numpy.ma.core.take', 'take', (['a', 'mindices'], {}), '(a, mindices)\n', (116226, 116239), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((116289, 116313), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'ctrl'], {}), '(test, ctrl)\n', (116301, 116313), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((116322, 116356), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'ctrl.mask'], {}), '(test.mask, ctrl.mask)\n', (116334, 116356), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((116747, 116786), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xlist[0]', '[0, None, 2, 3]'], {}), '(xlist[0], [0, None, 2, 3])\n', (116759, 116786), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((116795, 116831), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xlist[1]', '[4, 5, 6, 7]'], {}), '(xlist[1], [4, 5, 6, 7])\n', (116807, 116831), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((116840, 116880), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xlist[2]', '[8, 9, None, 11]'], {}), '(xlist[2], [8, 9, None, 11])\n', (116852, 116880), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((116889, 116914), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xlist', 'ctrl'], {}), '(xlist, ctrl)\n', (116901, 116914), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((117425, 117503), 'numpy.ma.core.array', 'array', (['[(1, 2), (3, 4)]'], {'mask': '[(0, 1), (0, 0)]', 'dtype': "[('a', int), ('b', int)]"}), "([(1, 2), (3, 4)], mask=[(0, 1), (0, 0)], dtype=[('a', int), ('b', int)])\n", (117430, 117503), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((117557, 117596), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[[1, None], [3, 4]]'], {}), '(test, [[1, None], [3, 4]])\n', (117569, 117596), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((117671, 117700), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[1, None]'], {}), '(test, [1, None])\n', (117683, 117700), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((117827, 117882), 'numpy.ma.core.array', 'array', (['[(0, 1), (2, 3)]'], {'dtype': "[('a', int), ('b', int)]"}), "([(0, 1), (2, 3)], dtype=[('a', int), ('b', int)])\n", (117832, 117882), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((118411, 118421), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (118417, 118421), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((118461, 118502), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["record['_data']", 'data._data'], {}), "(record['_data'], data._data)\n", (118473, 118502), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((118511, 118552), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["record['_mask']", 'data._mask'], {}), "(record['_mask'], data._mask)\n", (118523, 118552), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((118630, 118671), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["record['_data']", 'data._data'], {}), "(record['_data'], data._data)\n", (118642, 118671), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((118680, 118721), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["record['_mask']", 'data._mask'], {}), "(record['_mask'], data._mask)\n", (118692, 118721), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((119105, 119146), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["record['_data']", 'data._data'], {}), "(record['_data'], data._data)\n", (119117, 119146), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((119155, 119196), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["record['_mask']", 'data._mask'], {}), "(record['_mask'], data._mask)\n", (119167, 119196), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((119215, 119249), 'numpy.dtype', 'np.dtype', (['"""int, (2,3)float, float"""'], {}), "('int, (2,3)float, float')\n", (119223, 119249), True, 'import numpy as np\n'), ((119583, 119632), 'numpy.ma.testutils.assert_equal_records', 'assert_equal_records', (["record['_data']", 'data._data'], {}), "(record['_data'], data._data)\n", (119603, 119632), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((119641, 119690), 'numpy.ma.testutils.assert_equal_records', 'assert_equal_records', (["record['_mask']", 'data._mask'], {}), "(record['_mask'], data._mask)\n", (119661, 119690), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((119799, 119815), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (119804, 119815), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((119860, 119881), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'a'], {}), '(test, a)\n', (119872, 119881), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((119890, 119921), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'a.mask'], {}), '(test.mask, a.mask)\n', (119902, 119921), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((119935, 119967), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]'}), '([1, 2, 3], mask=[0, 0, 1])\n', (119940, 119967), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((120012, 120033), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'a'], {}), '(test, a)\n', (120024, 120033), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((120042, 120073), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'a.mask'], {}), '(test.mask, a.mask)\n', (120054, 120073), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((120087, 120194), 'numpy.ma.core.array', 'array', (['[(1, 1.0), (2, 2.0), (3, 3.0)]'], {'mask': '[(1, 0), (0, 0), (0, 1)]', 'dtype': "[('A', int), ('B', float)]"}), "([(1, 1.0), (2, 2.0), (3, 3.0)], mask=[(1, 0), (0, 0), (0, 1)], dtype=\n [('A', int), ('B', float)])\n", (120092, 120194), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((120249, 120270), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'a'], {}), '(test, a)\n', (120261, 120270), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((120279, 120310), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.data', 'a.data'], {}), '(test.data, a.data)\n', (120291, 120310), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((120405, 120458), 'numpy.ma.core.masked_array', 'masked_array', (['[[1, 2, 3, 4, 5]]'], {'mask': '[0, 0, 1, 0, 0]'}), '([[1, 2, 3, 4, 5]], mask=[0, 0, 1, 0, 0])\n', (120417, 120458), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((120477, 120538), 'numpy.ma.core.masked_array', 'masked_array', (['[[1], [2], [3], [4], [5]]'], {'mask': '[0, 0, 1, 0, 0]'}), '([[1], [2], [3], [4], [5]], mask=[0, 0, 1, 0, 0])\n', (120489, 120538), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((120578, 120609), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['marray.T', 'control'], {}), '(marray.T, control)\n', (120590, 120609), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((120846, 121116), 'numpy.array', 'np.array', (['[8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878, 8.979, \n 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, 7.712, \n 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, 7.357, \n 9.828, 6.272, 3.758, 6.693, 0.993]'], {}), '([8.375, 7.545, 8.828, 8.5, 1.757, 5.928, 8.43, 7.78, 9.865, 5.878,\n 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, \n 7.712, 3.382, 4.489, 6.479, 7.189, 9.645, 5.395, 4.961, 9.894, 2.893, \n 7.357, 9.828, 6.272, 3.758, 6.693, 0.993])\n', (120854, 121116), True, 'import numpy as np\n'), ((121289, 121411), 'numpy.array', 'np.array', (['[0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1,\n 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]'], {}), '([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0])\n', (121297, 121411), True, 'import numpy as np\n'), ((121526, 121547), 'numpy.ma.core.array', 'array', ([], {'data': 'x', 'mask': 'm'}), '(data=x, mask=m)\n', (121531, 121547), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((121669, 121791), 'numpy.array', 'np.array', (['[1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1,\n 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]'], {}), '([1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1,\n 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1])\n', (121677, 121791), True, 'import numpy as np\n'), ((121912, 121934), 'numpy.ma.core.array', 'array', ([], {'data': 'x', 'mask': 'm2'}), '(data=x, mask=m2)\n', (121917, 121934), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((123619, 123640), 'numpy.zeros', 'np.zeros', (['n', 'np.float'], {}), '(n, np.float)\n', (123627, 123640), True, 'import numpy as np\n'), ((123656, 123677), 'numpy.zeros', 'np.zeros', (['m', 'np.float'], {}), '(m, np.float)\n', (123664, 123677), True, 'import numpy as np\n'), ((123949, 124000), 'numpy.ma.core.masked_array', 'masked_array', (["['a', 'b']"], {'mask': '[1, 0]', 'dtype': 'object'}), "(['a', 'b'], mask=[1, 0], dtype=object)\n", (123961, 124000), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((124029, 124053), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y[1]', '"""bx"""'], {}), "(y[1], 'bx')\n", (124041, 124053), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((124062, 124080), 'numpy.ma.testutils.assert_', 'assert_', (['y.mask[0]'], {}), '(y.mask[0])\n', (124069, 124080), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((124160, 124216), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]', 'dtype': 'np.object'}), '([1, 2, 3], mask=[1, 0, 0], dtype=np.object)\n', (124172, 124216), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((124262, 124312), 'numpy.ma.core.masked_array', 'masked_array', (['[[1, 2, 3], [4, 5, 6]]'], {'dtype': 'object'}), '([[1, 2, 3], [4, 5, 6]], dtype=object)\n', (124274, 124312), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((124441, 124497), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]', 'dtype': 'np.object'}), '([1, 2, 3], mask=[1, 0, 0], dtype=np.object)\n', (124453, 124497), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((124548, 124598), 'numpy.ma.core.masked_array', 'masked_array', (['[[1, 2, 3], [4, 5, 6]]'], {'dtype': 'object'}), '([[1, 2, 3], [4, 5, 6]], dtype=object)\n', (124560, 124598), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((124739, 124779), 'numpy.ma.core.masked_array', 'masked_array', (['[1, 2, 3]'], {'dtype': 'np.object'}), '([1, 2, 3], dtype=np.object)\n', (124751, 124779), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((125525, 125550), 'numpy.ma.testutils.assert_', 'assert_', (['(r.mask is nomask)'], {}), '(r.mask is nomask)\n', (125532, 125550), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((125662, 125683), 'numpy.ma.testutils.assert_', 'assert_', (['r.mask[1, 3]'], {}), '(r.mask[1, 3])\n', (125669, 125683), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((125696, 125709), 'numpy.ma.core.empty_like', 'empty_like', (['r'], {}), '(r)\n', (125706, 125709), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((125745, 125771), 'numpy.ma.testutils.assert_almost_equal', 'assert_almost_equal', (['r', 'r1'], {}), '(r, r1)\n', (125764, 125771), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((125949, 125962), 'numpy.ma.core.empty_like', 'empty_like', (['r'], {}), '(r)\n', (125959, 125962), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((126000, 126026), 'numpy.ma.testutils.assert_almost_equal', 'assert_almost_equal', (['r', 'r1'], {}), '(r, r1)\n', (126019, 126026), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((126105, 126158), 'numpy.ma.core.masked_array', 'masked_array', (['[[1, 2], [3, 4]]'], {'mask': '[[0, 1], [0, 0]]'}), '([[1, 2], [3, 4]], mask=[[0, 1], [0, 0]])\n', (126117, 126158), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((126165, 126218), 'numpy.ma.core.masked_array', 'masked_array', (['[[1, 2], [3, 4]]'], {'mask': '[[0, 1], [0, 0]]'}), '([[1, 2], [3, 4]], mask=[[0, 1], [0, 0]])\n', (126177, 126218), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((126225, 126255), 'numpy.ma.core.masked_array', 'masked_array', (['[[0, 1], [3, 3]]'], {}), '([[0, 1], [3, 3]])\n', (126237, 126255), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((126346, 126391), 'numpy.ma.testutils.assert_almost_equal', 'assert_almost_equal', (['z.mask', '[[0, 1], [0, 0]]'], {}), '(z.mask, [[0, 1], [0, 0]])\n', (126365, 126391), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((127664, 127689), 'numpy.array', 'np.array', (['(-1)'], {'dtype': 'float'}), '(-1, dtype=float)\n', (127672, 127689), True, 'import numpy as np\n'), ((127705, 127727), 'numpy.ma.core.array', 'array', (['(-1)'], {'dtype': 'float'}), '(-1, dtype=float)\n', (127710, 127727), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((129161, 129219), 'numpy.ma.core.array', 'array', (['[[1, 1, 0], [1, 1, 0]]'], {'mask': '[[0, 0, 1], [0, 0, 1]]'}), '([[1, 1, 0], [1, 1, 0]], mask=[[0, 0, 1], [0, 0, 1]])\n', (129166, 129219), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((129313, 129347), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[0, 0, 1]'], {}), '(test.mask, [0, 0, 1])\n', (129325, 129347), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((129441, 129475), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[0, 0, 1]'], {}), '(test.mask, [0, 0, 1])\n', (129453, 129475), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((129569, 129603), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[1, 1, 1]'], {}), '(test.mask, [1, 1, 1])\n', (129581, 129603), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((129727, 129737), 'numpy.diag', 'np.diag', (['x'], {}), '(x)\n', (129734, 129737), True, 'import numpy as np\n'), ((129746, 129774), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['out', '[0, 4, 8]'], {}), '(out, [0, 4, 8])\n', (129758, 129774), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((129789, 129796), 'numpy.ma.core.diag', 'diag', (['x'], {}), '(x)\n', (129793, 129796), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((129805, 129833), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['out', '[0, 4, 8]'], {}), '(out, [0, 4, 8])\n', (129817, 129833), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((129842, 129875), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['out.mask', '[0, 1, 0]'], {}), '(out.mask, [0, 1, 0])\n', (129854, 129875), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((129890, 129899), 'numpy.ma.core.diag', 'diag', (['out'], {}), '(out)\n', (129894, 129899), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((129918, 130003), 'numpy.ma.core.array', 'array', (['[[0, 0, 0], [0, 4, 0], [0, 0, 8]]'], {'mask': '[[0, 0, 0], [0, 1, 0], [0, 0, 0]]'}), '([[0, 0, 0], [0, 4, 0], [0, 0, 8]], mask=[[0, 0, 0], [0, 1, 0], [0, 0, 0]]\n )\n', (129923, 130003), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((130031, 130057), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['out', 'control'], {}), '(out, control)\n', (130043, 130057), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((130167, 130196), 'numpy.ma.core.array', 'array', (['[[1, 2, 3], [4, 5, 6]]'], {}), '([[1, 2, 3], [4, 5, 6]])\n', (130172, 130196), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((130871, 131150), 'numpy.array', 'np.array', (['[8.375j, 7.545j, 8.828j, 8.5j, 1.757j, 5.928, 8.43, 7.78, 9.865, 5.878, \n 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, 9.63, \n 7.712, 3.382, 4.489, 6.479j, 7.189j, 9.645, 5.395, 4.961, 9.894, 2.893,\n 7.357, 9.828, 6.272, 3.758, 6.693, 0.993j]'], {}), '([8.375j, 7.545j, 8.828j, 8.5j, 1.757j, 5.928, 8.43, 7.78, 9.865, \n 5.878, 8.979, 4.732, 3.012, 6.022, 5.095, 3.116, 5.238, 3.957, 6.04, \n 9.63, 7.712, 3.382, 4.489, 6.479j, 7.189j, 9.645, 5.395, 4.961, 9.894, \n 2.893, 7.357, 9.828, 6.272, 3.758, 6.693, 0.993j])\n', (130879, 131150), True, 'import numpy as np\n'), ((131322, 131444), 'numpy.array', 'np.array', (['[0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1,\n 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0]'], {}), '([0, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1,\n 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, 0])\n', (131330, 131444), True, 'import numpy as np\n'), ((131559, 131580), 'numpy.ma.core.array', 'array', ([], {'data': 'x', 'mask': 'm'}), '(data=x, mask=m)\n', (131564, 131580), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((131702, 131824), 'numpy.array', 'np.array', (['[1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1,\n 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1]'], {}), '([1, 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 0, 0, 1, 1, 0, 1, 0, 0, 0, 1,\n 1, 1, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1])\n', (131710, 131824), True, 'import numpy as np\n'), ((131945, 131967), 'numpy.ma.core.array', 'array', ([], {'data': 'x', 'mask': 'm2'}), '(data=x, mask=m2)\n', (131950, 131967), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((133217, 133296), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0]'], {}), '([1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0])\n', (133225, 133296), True, 'import numpy as np\n'), ((133296, 133371), 'numpy.array', 'np.array', (['[5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0]'], {}), '([5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0])\n', (133304, 133371), True, 'import numpy as np\n'), ((133473, 133497), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': 'm1'}), '(x, mask=m1)\n', (133485, 133497), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((133511, 133535), 'numpy.ma.core.masked_array', 'masked_array', (['y'], {'mask': 'm2'}), '(y, mask=m2)\n', (133523, 133535), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((133668, 133690), 'numpy.ma.core.masked_where', 'masked_where', (['(False)', 'x'], {}), '(False, x)\n', (133680, 133690), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((133699, 133722), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y', '[1, 2]'], {}), '(y, [1, 2])\n', (133711, 133722), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((133731, 133752), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y[1]', '(2)'], {}), '(y[1], 2)\n', (133743, 133752), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((133828, 133846), 'numpy.ma.core.masked_equal', 'masked_equal', (['x', '(3)'], {}), '(x, 3)\n', (133840, 133846), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((133855, 133874), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx', 'x'], {}), '(mx, x)\n', (133867, 133874), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((133883, 133916), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx._mask', '[0, 0, 1]'], {}), '(mx._mask, [0, 0, 1])\n', (133895, 133916), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((133930, 133952), 'numpy.ma.core.masked_not_equal', 'masked_not_equal', (['x', '(3)'], {}), '(x, 3)\n', (133946, 133952), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((133961, 133980), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx', 'x'], {}), '(mx, x)\n', (133973, 133980), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((133989, 134022), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx._mask', '[1, 1, 0]'], {}), '(mx._mask, [1, 1, 0])\n', (134001, 134022), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((134103, 134121), 'numpy.ma.core.masked_equal', 'masked_equal', (['x', '(3)'], {}), '(x, 3)\n', (134115, 134121), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134130, 134163), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx._mask', '[0, 0, 1]'], {}), '(mx._mask, [0, 0, 1])\n', (134142, 134163), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((134172, 134202), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mx.fill_value', '(3)'], {}), '(mx.fill_value, 3)\n', (134184, 134202), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((134294, 134326), 'numpy.ma.core.array', 'array', (['[1.0, 2.0, 3.0, 4.0, 5.0]'], {}), '([1.0, 2.0, 3.0, 4.0, 5.0])\n', (134299, 134326), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((135134, 135165), 'numpy.ma.core.ones', 'ones', (['(10, 10, 10)'], {'dtype': 'float'}), '((10, 10, 10), dtype=float)\n', (135138, 135165), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((135182, 135210), 'numpy.ma.core.zeros', 'zeros', (['atest.shape', 'MaskType'], {}), '(atest.shape, MaskType)\n', (135187, 135210), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((135227, 135253), 'numpy.ma.core.masked_where', 'masked_where', (['btest', 'atest'], {}), '(btest, atest)\n', (135239, 135253), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((135262, 135288), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['atest', 'ctest'], {}), '(atest, ctest)\n', (135274, 135288), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((135352, 135362), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (135358, 135362), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((135545, 135563), 'numpy.ma.core.masked_equal', 'masked_equal', (['a', '(1)'], {}), '(a, 1)\n', (135557, 135563), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((135572, 135627), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '[0, 1, 0, 0, 0, 0, 0, 0, 0, 0]'], {}), '(test.mask, [0, 1, 0, 0, 0, 0, 0, 0, 0, 0])\n', (135584, 135627), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((135791, 135839), 'numpy.zeros', 'np.zeros', (['(10)'], {'dtype': "[('A', '<f2'), ('B', '<f4')]"}), "(10, dtype=[('A', '<f2'), ('B', '<f4')])\n", (135799, 135839), True, 'import numpy as np\n'), ((135853, 135886), 'numpy.ma.masked_where', 'np.ma.masked_where', (["(a['A'] < 5)", 'a'], {}), "(a['A'] < 5, a)\n", (135871, 135886), True, 'import numpy as np\n'), ((135895, 135944), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['am.mask.dtype.names', 'am.dtype.names'], {}), '(am.mask.dtype.names, am.dtype.names)\n', (135907, 135944), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((136991, 137064), 'numpy.ma.core.array', 'array', (['[1.23456, 2.34567, 3.45678, 4.56789, 5.6789]'], {'mask': '[0, 1, 0, 0, 0]'}), '([1.23456, 2.34567, 3.45678, 4.56789, 5.6789], mask=[0, 1, 0, 0, 0])\n', (136996, 137064), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((137280, 137293), 'numpy.ma.core.empty_like', 'empty_like', (['a'], {}), '(a)\n', (137290, 137293), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((137325, 137367), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b', '[1.0, 2.0, 3.0, 5.0, 6.0]'], {}), '(b, [1.0, 2.0, 3.0, 5.0, 6.0])\n', (137337, 137367), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((137376, 137408), 'numpy.ma.core.array', 'array', (['[1.0, 2.0, 3.0, 4.0, 5.0]'], {}), '([1.0, 2.0, 3.0, 4.0, 5.0])\n', (137381, 137408), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((137416, 137438), 'numpy.ma.core.array', 'array', (['[1, 1, 1, 0, 0]'], {}), '([1, 1, 1, 0, 0])\n', (137421, 137438), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((137473, 137488), 'numpy.ma.core.where', 'where', (['c', 'x', '(-x)'], {}), '(c, x, -x)\n', (137478, 137488), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((137497, 137539), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[1.0, 2.0, 0.0, -4.0, -5]'], {}), '(z, [1.0, 2.0, 0.0, -4.0, -5])\n', (137509, 137539), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((137570, 137585), 'numpy.ma.core.where', 'where', (['c', 'x', '(-x)'], {}), '(c, x, -x)\n', (137575, 137585), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((137594, 137636), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[1.0, 2.0, 0.0, -4.0, -5]'], {}), '(z, [1.0, 2.0, 0.0, -4.0, -5])\n', (137606, 137636), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((137641, 137664), 'numpy.ma.testutils.assert_', 'assert_', (['(z[0] is masked)'], {}), '(z[0] is masked)\n', (137648, 137664), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((137673, 137700), 'numpy.ma.testutils.assert_', 'assert_', (['(z[1] is not masked)'], {}), '(z[1] is not masked)\n', (137680, 137700), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((137709, 137732), 'numpy.ma.testutils.assert_', 'assert_', (['(z[2] is masked)'], {}), '(z[2] is masked)\n', (137716, 137732), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((137987, 138016), 'numpy.empty', 'np.empty', (['(3, 4)'], {'dtype': 'float'}), '((3, 4), dtype=float)\n', (137995, 138016), True, 'import numpy as np\n'), ((138061, 138097), 'numpy.round', 'np.round', (['xm'], {'decimals': '(2)', 'out': 'output'}), '(xm, decimals=2, out=output)\n', (138069, 138097), True, 'import numpy as np\n'), ((138273, 138299), 'numpy.ma.core.empty', 'empty', (['(3, 4)'], {'dtype': 'float'}), '((3, 4), dtype=float)\n', (138278, 138299), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((138524, 138548), 'numpy.ma.core.array', 'array', (['(1.1)'], {'mask': '[False]'}), '(1.1, mask=[False])\n', (138529, 138548), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((138597, 138620), 'numpy.ma.core.array', 'array', (['(1.1)'], {'mask': '[True]'}), '(1.1, mask=[True])\n', (138602, 138620), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((138671, 138695), 'numpy.ma.core.array', 'array', (['(1.1)'], {'mask': '[False]'}), '(1.1, mask=[False])\n', (138676, 138695), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((138713, 138737), 'numpy.empty', 'np.empty', (['(1)'], {'dtype': 'float'}), '(1, dtype=float)\n', (138721, 138737), True, 'import numpy as np\n'), ((138801, 138824), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['output', '(1)'], {}), '(output, 1)\n', (138813, 138824), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((138838, 138862), 'numpy.ma.core.array', 'array', (['(1.1)'], {'mask': '[False]'}), '(1.1, mask=[False])\n', (138843, 138862), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((138880, 138907), 'numpy.ma.core.array', 'array', (['(-9999.0)'], {'mask': '[True]'}), '(-9999.0, mask=[True])\n', (138885, 138907), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((138943, 138970), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['output[()]', '(1)'], {}), '(output[()], 1)\n', (138955, 138970), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((138984, 139007), 'numpy.ma.core.array', 'array', (['(1.1)'], {'mask': '[True]'}), '(1.1, mask=[True])\n', (138989, 139007), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((139025, 139053), 'numpy.ma.core.array', 'array', (['(-9999.0)'], {'mask': '[False]'}), '(-9999.0, mask=[False])\n', (139030, 139053), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((139089, 139118), 'numpy.ma.testutils.assert_', 'assert_', (['(output[()] is masked)'], {}), '(output[()] is masked)\n', (139096, 139118), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139161, 139172), 'numpy.ma.core.identity', 'identity', (['(5)'], {}), '(5)\n', (139169, 139172), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((139421, 139455), 'numpy.ma.core.array', 'array', (['[-1.1, -1.1, 1.1, 1.1, 0.0]'], {}), '([-1.1, -1.1, 1.1, 1.1, 0.0])\n', (139426, 139455), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((139467, 139522), 'numpy.ma.core.array', 'array', (['[0.5, 2.0, 0.5, 2.0, -1.0]'], {'mask': '[0, 0, 0, 0, 1]'}), '([0.5, 2.0, 0.5, 2.0, -1.0], mask=[0, 0, 0, 0, 1])\n', (139472, 139522), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((139532, 139543), 'numpy.ma.core.power', 'power', (['x', 'b'], {}), '(x, b)\n', (139537, 139543), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((139552, 139611), 'numpy.ma.testutils.assert_almost_equal', 'assert_almost_equal', (['y', '[0, 1.21, 1.04880884817, 1.21, 0.0]'], {}), '(y, [0, 1.21, 1.04880884817, 1.21, 0.0])\n', (139571, 139611), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139619, 139657), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y._mask', '[1, 0, 0, 0, 1]'], {}), '(y._mask, [1, 0, 0, 0, 1])\n', (139631, 139657), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139694, 139705), 'numpy.ma.core.power', 'power', (['x', 'b'], {}), '(x, b)\n', (139699, 139705), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((139714, 139752), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['y._mask', '[1, 0, 0, 0, 1]'], {}), '(y._mask, [1, 0, 0, 0, 1])\n', (139726, 139752), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139780, 139810), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z._mask', 'y._mask'], {}), '(z._mask, y._mask)\n', (139792, 139810), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139819, 139844), 'numpy.ma.testutils.assert_almost_equal', 'assert_almost_equal', (['z', 'y'], {}), '(z, y)\n', (139838, 139844), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139853, 139890), 'numpy.ma.testutils.assert_almost_equal', 'assert_almost_equal', (['z._data', 'y._data'], {}), '(z._data, y._data)\n', (139872, 139890), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139915, 139945), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x._mask', 'y._mask'], {}), '(x._mask, y._mask)\n', (139927, 139945), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139954, 139979), 'numpy.ma.testutils.assert_almost_equal', 'assert_almost_equal', (['x', 'y'], {}), '(x, y)\n', (139973, 139979), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((139988, 140025), 'numpy.ma.testutils.assert_almost_equal', 'assert_almost_equal', (['x._data', 'y._data'], {}), '(x._data, y._data)\n', (140007, 140025), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((140118, 140162), 'numpy.array', 'np.array', (['[[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]'], {}), '([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])\n', (140126, 140162), True, 'import numpy as np\n'), ((140171, 140209), 'numpy.ma.core.array', 'array', (['a2'], {'mask': '[[1, 0, 0], [0, 0, 1]]'}), '(a2, mask=[[1, 0, 0], [0, 0, 1]])\n', (140176, 140209), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((140223, 140242), 'numpy.array', 'np.array', (['[2, 4, 3]'], {}), '([2, 4, 3])\n', (140231, 140242), True, 'import numpy as np\n'), ((140256, 140274), 'numpy.array', 'np.array', (['[b1, b1]'], {}), '([b1, b1])\n', (140264, 140274), True, 'import numpy as np\n'), ((140289, 140327), 'numpy.ma.core.array', 'array', (['b2'], {'mask': '[[0, 1, 0], [0, 1, 0]]'}), '(b2, mask=[[0, 1, 0], [0, 1, 0]])\n', (140294, 140327), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((140344, 140436), 'numpy.ma.core.array', 'array', (['[[1 ** 2, 2 ** 4, 3 ** 3], [4 ** 2, 5 ** 4, 6 ** 3]]'], {'mask': '[[1, 1, 0], [0, 1, 1]]'}), '([[1 ** 2, 2 ** 4, 3 ** 3], [4 ** 2, 5 ** 4, 6 ** 3]], mask=[[1, 1, 0],\n [0, 1, 1]])\n', (140349, 140436), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((140534, 140558), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'ctrl'], {}), '(test, ctrl)\n', (140546, 140558), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((140567, 140601), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'ctrl.mask'], {}), '(test.mask, ctrl.mask)\n', (140579, 140601), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((140689, 140713), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'ctrl'], {}), '(test, ctrl)\n', (140701, 140713), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((140722, 140755), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'a2m.mask'], {}), '(test.mask, a2m.mask)\n', (140734, 140755), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((140843, 140867), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'ctrl'], {}), '(test, ctrl)\n', (140855, 140867), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((140876, 140909), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'b2m.mask'], {}), '(test.mask, b2m.mask)\n', (140888, 140909), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((140926, 141018), 'numpy.ma.core.array', 'array', (['[[2 ** 2, 4 ** 4, 3 ** 3], [2 ** 2, 4 ** 4, 3 ** 3]]'], {'mask': '[[0, 1, 0], [0, 1, 0]]'}), '([[2 ** 2, 4 ** 4, 3 ** 3], [2 ** 2, 4 ** 4, 3 ** 3]], mask=[[0, 1, 0],\n [0, 1, 0]])\n', (140931, 141018), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((141069, 141093), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'ctrl'], {}), '(test, ctrl)\n', (141081, 141093), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((141102, 141136), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'ctrl.mask'], {}), '(test.mask, ctrl.mask)\n', (141114, 141136), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((141170, 141194), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'ctrl'], {}), '(test, ctrl)\n', (141182, 141194), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((141203, 141237), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'ctrl.mask'], {}), '(test.mask, ctrl.mask)\n', (141215, 141237), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((141311, 141390), 'numpy.array', 'np.array', (['[1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0]'], {}), '([1.0, 1.0, 1.0, -2.0, pi / 2.0, 4.0, 5.0, -10.0, 10.0, 1.0, 2.0, 3.0])\n', (141319, 141390), True, 'import numpy as np\n'), ((141390, 141465), 'numpy.array', 'np.array', (['[5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0]'], {}), '([5.0, 0.0, 3.0, 2.0, -1.0, -4.0, 0.0, -10.0, 10.0, 1.0, 0.0, 3.0])\n', (141398, 141465), True, 'import numpy as np\n'), ((141567, 141591), 'numpy.ma.core.masked_array', 'masked_array', (['x'], {'mask': 'm1'}), '(x, mask=m1)\n', (141579, 141591), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((141605, 141629), 'numpy.ma.core.masked_array', 'masked_array', (['y'], {'mask': 'm2'}), '(y, mask=m2)\n', (141617, 141629), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((141676, 141697), 'numpy.ma.core.where', 'where', (['(xm > 2)', 'xm', '(-9)'], {}), '(xm > 2, xm, -9)\n', (141681, 141697), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((141706, 141797), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['d', '[-9.0, -9.0, -9.0, -9.0, -9.0, 4.0, -9.0, -9.0, 10.0, -9.0, -9.0, 3.0]'], {}), '(d, [-9.0, -9.0, -9.0, -9.0, -9.0, 4.0, -9.0, -9.0, 10.0, -9.0,\n -9.0, 3.0])\n', (141718, 141797), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((141815, 141846), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['d._mask', 'xm._mask'], {}), '(d._mask, xm._mask)\n', (141827, 141846), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((141859, 141880), 'numpy.ma.core.where', 'where', (['(xm > 2)', '(-9)', 'ym'], {}), '(xm > 2, -9, ym)\n', (141864, 141880), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((141889, 141978), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['d', '[5.0, 0.0, 3.0, 2.0, -1.0, -9.0, -9.0, -10.0, -9.0, 1.0, 0.0, -9.0]'], {}), '(d, [5.0, 0.0, 3.0, 2.0, -1.0, -9.0, -9.0, -10.0, -9.0, 1.0, \n 0.0, -9.0])\n', (141901, 141978), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((141995, 142054), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['d._mask', '[1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0]'], {}), '(d._mask, [1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0])\n', (142007, 142054), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((142067, 142092), 'numpy.ma.core.where', 'where', (['(xm > 2)', 'xm', 'masked'], {}), '(xm > 2, xm, masked)\n', (142072, 142092), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((142101, 142192), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['d', '[-9.0, -9.0, -9.0, -9.0, -9.0, 4.0, -9.0, -9.0, 10.0, -9.0, -9.0, 3.0]'], {}), '(d, [-9.0, -9.0, -9.0, -9.0, -9.0, 4.0, -9.0, -9.0, 10.0, -9.0,\n -9.0, 3.0])\n', (142113, 142192), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((142283, 142309), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['d._mask', 'tmp'], {}), '(d._mask, tmp)\n', (142295, 142309), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((142352, 142379), 'numpy.ma.core.where', 'where', (['(ixm > 2)', 'ixm', 'masked'], {}), '(ixm > 2, ixm, masked)\n', (142357, 142379), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((142388, 142451), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['d', '[-9, -9, -9, -9, -9, 4, -9, -9, 10, -9, -9, 3]'], {}), '(d, [-9, -9, -9, -9, -9, 4, -9, -9, 10, -9, -9, 3])\n', (142400, 142451), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((142460, 142492), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['d.dtype', 'ixm.dtype'], {}), '(d.dtype, ixm.dtype)\n', (142472, 142492), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((142539, 142553), 'numpy.array', 'np.array', (['None'], {}), '(None)\n', (142547, 142553), True, 'import numpy as np\n'), ((142566, 142584), 'numpy.ma.core.masked_array', 'masked_array', (['None'], {}), '(None)\n', (142578, 142584), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((142762, 142772), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (142768, 142772), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((142856, 142875), 'numpy.ma.core.where', 'where', (['c', 'x', 'masked'], {}), '(c, x, masked)\n', (142861, 142875), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((142884, 142911), 'numpy.ma.testutils.assert_', 'assert_', (['(z.dtype is x.dtype)'], {}), '(z.dtype is x.dtype)\n', (142891, 142911), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((142920, 142943), 'numpy.ma.testutils.assert_', 'assert_', (['(z[3] is masked)'], {}), '(z[3] is masked)\n', (142927, 142943), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((142952, 142975), 'numpy.ma.testutils.assert_', 'assert_', (['(z[4] is masked)'], {}), '(z[4] is masked)\n', (142959, 142975), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((142984, 143007), 'numpy.ma.testutils.assert_', 'assert_', (['(z[7] is masked)'], {}), '(z[7] is masked)\n', (142991, 143007), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143016, 143043), 'numpy.ma.testutils.assert_', 'assert_', (['(z[8] is not masked)'], {}), '(z[8] is not masked)\n', (143023, 143043), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143052, 143079), 'numpy.ma.testutils.assert_', 'assert_', (['(z[9] is not masked)'], {}), '(z[9] is not masked)\n', (143059, 143079), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143088, 143106), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', 'z'], {}), '(x, z)\n', (143100, 143106), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143148, 143167), 'numpy.ma.core.where', 'where', (['c', 'masked', 'x'], {}), '(c, masked, x)\n', (143153, 143167), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((143176, 143203), 'numpy.ma.testutils.assert_', 'assert_', (['(z.dtype is x.dtype)'], {}), '(z.dtype is x.dtype)\n', (143183, 143203), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143212, 143235), 'numpy.ma.testutils.assert_', 'assert_', (['(z[3] is masked)'], {}), '(z[3] is masked)\n', (143219, 143235), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143244, 143271), 'numpy.ma.testutils.assert_', 'assert_', (['(z[4] is not masked)'], {}), '(z[4] is not masked)\n', (143251, 143271), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143280, 143307), 'numpy.ma.testutils.assert_', 'assert_', (['(z[7] is not masked)'], {}), '(z[7] is not masked)\n', (143287, 143307), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143316, 143339), 'numpy.ma.testutils.assert_', 'assert_', (['(z[8] is masked)'], {}), '(z[8] is masked)\n', (143323, 143339), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143348, 143371), 'numpy.ma.testutils.assert_', 'assert_', (['(z[9] is masked)'], {}), '(z[9] is masked)\n', (143355, 143371), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143433, 143465), 'numpy.ma.core.array', 'array', (['[1.0, 2.0, 3.0, 4.0, 5.0]'], {}), '([1.0, 2.0, 3.0, 4.0, 5.0])\n', (143438, 143465), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((143473, 143495), 'numpy.ma.core.array', 'array', (['[1, 1, 1, 0, 0]'], {}), '([1, 1, 1, 0, 0])\n', (143478, 143495), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((143530, 143545), 'numpy.ma.core.where', 'where', (['c', 'x', '(-x)'], {}), '(c, x, -x)\n', (143535, 143545), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((143554, 143596), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[1.0, 2.0, 0.0, -4.0, -5]'], {}), '(z, [1.0, 2.0, 0.0, -4.0, -5])\n', (143566, 143596), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143627, 143642), 'numpy.ma.core.where', 'where', (['c', 'x', '(-x)'], {}), '(c, x, -x)\n', (143632, 143642), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((143651, 143693), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[1.0, 2.0, 0.0, -4.0, -5]'], {}), '(z, [1.0, 2.0, 0.0, -4.0, -5])\n', (143663, 143693), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143698, 143721), 'numpy.ma.testutils.assert_', 'assert_', (['(z[0] is masked)'], {}), '(z[0] is masked)\n', (143705, 143721), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143730, 143757), 'numpy.ma.testutils.assert_', 'assert_', (['(z[1] is not masked)'], {}), '(z[1] is not masked)\n', (143737, 143757), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143766, 143789), 'numpy.ma.testutils.assert_', 'assert_', (['(z[2] is masked)'], {}), '(z[2] is masked)\n', (143773, 143789), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((143803, 143815), 'numpy.ma.core.arange', 'arange', (['(1)', '(6)'], {}), '(1, 6)\n', (143809, 143815), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((143903, 143947), 'numpy.ma.core.array', 'array', (['[1, 1, 1, 0, 0]'], {'mask': '[1, 0, 0, 0, 0]'}), '([1, 1, 1, 0, 0], mask=[1, 0, 0, 0, 0])\n', (143908, 143947), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((143985, 143999), 'numpy.ma.core.where', 'where', (['c', 'x', 'y'], {}), '(c, x, y)\n', (143990, 143999), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144013, 144028), 'numpy.ma.core.where', 'where', (['cm', 'x', 'y'], {}), '(cm, x, y)\n', (144018, 144028), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144037, 144056), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', 'zm'], {}), '(z, zm)\n', (144049, 144056), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((144104, 144139), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['zm', '[1, 2, 3, 40, 50]'], {}), '(zm, [1, 2, 3, 40, 50])\n', (144116, 144139), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((144152, 144171), 'numpy.ma.core.where', 'where', (['c', 'masked', '(1)'], {}), '(c, masked, 1)\n', (144157, 144171), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144180, 144215), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[99, 99, 99, 1, 1]'], {}), '(z, [99, 99, 99, 1, 1])\n', (144192, 144215), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((144228, 144247), 'numpy.ma.core.where', 'where', (['c', '(1)', 'masked'], {}), '(c, 1, masked)\n', (144233, 144247), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144256, 144291), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['z', '[99, 1, 1, 99, 99]'], {}), '(z, [99, 1, 1, 99, 99])\n', (144268, 144291), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((144384, 144412), 'numpy.arange', 'np.arange', (['(4)'], {'dtype': 'np.int32'}), '(4, dtype=np.int32)\n', (144393, 144412), True, 'import numpy as np\n'), ((144522, 144569), 'numpy.find_common_type', 'np.find_common_type', (['[np.int32, np.float32]', '[]'], {}), '([np.int32, np.float32], [])\n', (144541, 144569), True, 'import numpy as np\n'), ((144578, 144605), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (144590, 144605), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((144779, 144808), 'numpy.ma.core.choose', 'choose', (['[2, 3, 1, 0]', 'choices'], {}), '([2, 3, 1, 0], choices)\n', (144785, 144808), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144879, 144921), 'numpy.ma.core.choose', 'choose', (['[2, 4, 1, 0]', 'choices'], {'mode': '"""clip"""'}), "([2, 4, 1, 0], choices, mode='clip')\n", (144885, 144921), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144992, 145034), 'numpy.ma.core.choose', 'choose', (['[2, 4, 1, 0]', 'choices'], {'mode': '"""wrap"""'}), "([2, 4, 1, 0], choices, mode='wrap')\n", (144998, 145034), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145147, 145185), 'numpy.ma.core.array', 'array', (['[2, 4, 1, 0]'], {'mask': '[1, 0, 0, 1]'}), '([2, 4, 1, 0], mask=[1, 0, 0, 1])\n', (145152, 145185), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145203, 145241), 'numpy.ma.core.choose', 'choose', (['indices_', 'choices'], {'mode': '"""wrap"""'}), "(indices_, choices, mode='wrap')\n", (145209, 145241), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145303, 145342), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['chosen.mask', '[1, 0, 0, 1]'], {}), '(chosen.mask, [1, 0, 0, 1])\n', (145315, 145342), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((145402, 145479), 'numpy.ma.core.array', 'array', (['choices'], {'mask': '[[0, 0, 0, 1], [1, 1, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]'}), '(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]])\n', (145407, 145479), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145568, 145606), 'numpy.ma.core.choose', 'choose', (['indices_', 'choices'], {'mode': '"""wrap"""'}), "(indices_, choices, mode='wrap')\n", (145574, 145606), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145668, 145707), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['chosen.mask', '[1, 0, 0, 1]'], {}), '(chosen.mask, [1, 0, 0, 1])\n', (145680, 145707), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((145918, 145937), 'numpy.ma.core.empty', 'empty', (['(4)'], {'dtype': 'int'}), '(4, dtype=int)\n', (145923, 145937), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145955, 145995), 'numpy.ma.core.choose', 'choose', (['[2, 3, 1, 0]', 'choices'], {'out': 'store'}), '([2, 3, 1, 0], choices, out=store)\n', (145961, 145995), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146152, 146171), 'numpy.ma.core.empty', 'empty', (['(4)'], {'dtype': 'int'}), '(4, dtype=int)\n', (146157, 146171), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146191, 146229), 'numpy.ma.core.array', 'array', (['[2, 3, 1, 0]'], {'mask': '[1, 0, 0, 1]'}), '([2, 3, 1, 0], mask=[1, 0, 0, 1])\n', (146196, 146229), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146247, 146296), 'numpy.ma.core.choose', 'choose', (['indices_', 'choices'], {'mode': '"""wrap"""', 'out': 'store'}), "(indices_, choices, mode='wrap', out=store)\n", (146253, 146296), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146358, 146396), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['store.mask', '[1, 0, 0, 1]'], {}), '(store.mask, [1, 0, 0, 1])\n', (146370, 146396), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((146476, 146553), 'numpy.ma.core.array', 'array', (['choices'], {'mask': '[[0, 0, 0, 1], [1, 1, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]]'}), '(choices, mask=[[0, 0, 0, 1], [1, 1, 0, 1], [1, 0, 0, 0], [0, 0, 0, 0]])\n', (146481, 146553), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146692, 146741), 'numpy.ma.core.choose', 'choose', (['indices_', 'choices'], {'mode': '"""wrap"""', 'out': 'store'}), "(indices_, choices, mode='wrap', out=store)\n", (146698, 146741), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146844, 146854), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (146850, 146854), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146941, 146970), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.shape', '(5, 2)'], {}), '(b.shape, (5, 2))\n', (146953, 146970), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((147097, 147126), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.shape', '(5, 2)'], {}), '(b.shape, (5, 2))\n', (147109, 147126), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((147237, 147266), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.shape', '(5, 2)'], {}), '(b.shape, (5, 2))\n', (147249, 147266), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((147375, 147404), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['b.shape', '(5, 2)'], {}), '(b.shape, (5, 2))\n', (147387, 147404), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((147456, 147477), 'numpy.reshape', 'np.reshape', (['a', '(2, 5)'], {}), '(a, (2, 5))\n', (147466, 147477), True, 'import numpy as np\n'), ((147538, 147567), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['c.shape', '(2, 5)'], {}), '(c.shape, (2, 5))\n', (147550, 147567), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((147802, 147824), 'numpy.ma.core.make_mask_descr', 'make_mask_descr', (['ntype'], {}), '(ntype)\n', (147817, 147824), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((147833, 147885), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', "[('a', np.bool), ('b', np.bool)]"], {}), "(test, [('a', np.bool), ('b', np.bool)])\n", (147845, 147885), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((147959, 147981), 'numpy.ma.core.make_mask_descr', 'make_mask_descr', (['ntype'], {}), '(ntype)\n', (147974, 147981), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((147990, 148022), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '(np.bool, 2)'], {}), '(test, (np.bool, 2))\n', (148002, 148022), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((148091, 148113), 'numpy.ma.core.make_mask_descr', 'make_mask_descr', (['ntype'], {}), '(ntype)\n', (148106, 148113), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((148271, 148293), 'numpy.ma.core.make_mask_descr', 'make_mask_descr', (['ntype'], {}), '(ntype)\n', (148286, 148293), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((148312, 148372), 'numpy.dtype', 'np.dtype', (["[('a', 'b1'), ('b', [('ba', 'b1'), ('bb', 'b1')])]"], {}), "([('a', 'b1'), ('b', [('ba', 'b1'), ('bb', 'b1')])])\n", (148320, 148372), True, 'import numpy as np\n'), ((148381, 148408), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (148393, 148408), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((148486, 148508), 'numpy.ma.core.make_mask_descr', 'make_mask_descr', (['ntype'], {}), '(ntype)\n', (148501, 148508), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((148640, 148662), 'numpy.ma.core.make_mask_descr', 'make_mask_descr', (['ntype'], {}), '(ntype)\n', (148655, 148662), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((148847, 148862), 'numpy.ma.core.make_mask', 'make_mask', (['mask'], {}), '(mask)\n', (148856, 148862), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((148871, 148905), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'MaskType'], {}), '(test.dtype, MaskType)\n', (148883, 148905), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((148914, 148940), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[0, 1]'], {}), '(test, [0, 1])\n', (148926, 148940), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((148991, 149022), 'numpy.array', 'np.array', (['[0, 1]'], {'dtype': 'np.bool'}), '([0, 1], dtype=np.bool)\n', (148999, 149022), True, 'import numpy as np\n'), ((149038, 149053), 'numpy.ma.core.make_mask', 'make_mask', (['mask'], {}), '(mask)\n', (149047, 149053), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((149062, 149096), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'MaskType'], {}), '(test.dtype, MaskType)\n', (149074, 149096), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((149105, 149131), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[0, 1]'], {}), '(test, [0, 1])\n', (149117, 149131), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((149260, 149300), 'numpy.array', 'np.array', (['[(0, 0), (0, 1)]'], {'dtype': 'mdtype'}), '([(0, 0), (0, 1)], dtype=mdtype)\n', (149268, 149300), True, 'import numpy as np\n'), ((149316, 149331), 'numpy.ma.core.make_mask', 'make_mask', (['mask'], {}), '(mask)\n', (149325, 149331), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((149340, 149374), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'MaskType'], {}), '(test.dtype, MaskType)\n', (149352, 149374), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((149383, 149409), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '[1, 1]'], {}), '(test, [1, 1])\n', (149395, 149409), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((149542, 149582), 'numpy.array', 'np.array', (['[(0, 0), (0, 1)]'], {'dtype': 'mdtype'}), '([(0, 0), (0, 1)], dtype=mdtype)\n', (149550, 149582), True, 'import numpy as np\n'), ((149598, 149631), 'numpy.ma.core.make_mask', 'make_mask', (['mask'], {'dtype': 'mask.dtype'}), '(mask, dtype=mask.dtype)\n', (149607, 149631), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((149640, 149672), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'mdtype'], {}), '(test.dtype, mdtype)\n', (149652, 149672), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((149681, 149705), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'mask'], {}), '(test, mask)\n', (149693, 149705), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((149890, 149930), 'numpy.array', 'np.array', (['[(0, 0), (0, 1)]'], {'dtype': 'mdtype'}), '([(0, 0), (0, 1)], dtype=mdtype)\n', (149898, 149930), True, 'import numpy as np\n'), ((149946, 149979), 'numpy.ma.core.make_mask', 'make_mask', (['mask'], {'dtype': 'mask.dtype'}), '(mask, dtype=mask.dtype)\n', (149955, 149979), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((149988, 150020), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype', 'bdtype'], {}), '(test.dtype, bdtype)\n', (150000, 150020), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((150295, 150334), 'itertools.product', 'itertools.product', (['bools', 'bools', 'dtypes'], {}), '(bools, bools, dtypes)\n', (150312, 150334), False, 'import itertools\n'), ((150582, 150637), 'numpy.array', 'np.array', (['[(0, 0), (0, 1), (1, 0), (0, 0)]'], {'dtype': 'mtype'}), '([(0, 0), (0, 1), (1, 0), (0, 0)], dtype=mtype)\n', (150590, 150637), True, 'import numpy as np\n'), ((150690, 150711), 'numpy.ma.core.mask_or', 'mask_or', (['mask', 'nomask'], {}), '(mask, nomask)\n', (150697, 150711), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((150720, 150744), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'mask'], {}), '(test, mask)\n', (150732, 150744), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((150760, 150781), 'numpy.ma.core.mask_or', 'mask_or', (['nomask', 'mask'], {}), '(nomask, mask)\n', (150767, 150781), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((150790, 150814), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'mask'], {}), '(test, mask)\n', (150802, 150814), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((150861, 150881), 'numpy.ma.core.mask_or', 'mask_or', (['mask', '(False)'], {}), '(mask, False)\n', (150868, 150881), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((150890, 150914), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'mask'], {}), '(test, mask)\n', (150902, 150914), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((150980, 151035), 'numpy.array', 'np.array', (['[(0, 1), (0, 1), (0, 1), (0, 1)]'], {'dtype': 'mtype'}), '([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=mtype)\n', (150988, 151035), True, 'import numpy as np\n'), ((151051, 151071), 'numpy.ma.core.mask_or', 'mask_or', (['mask', 'other'], {}), '(mask, other)\n', (151058, 151071), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((151090, 151145), 'numpy.array', 'np.array', (['[(0, 1), (0, 1), (1, 1), (0, 1)]'], {'dtype': 'mtype'}), '([(0, 1), (0, 1), (1, 1), (0, 1)], dtype=mtype)\n', (151098, 151145), True, 'import numpy as np\n'), ((151154, 151181), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (151166, 151181), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((151303, 151362), 'numpy.array', 'np.array', (['[(0, 1), (0, 1), (0, 1), (0, 1)]'], {'dtype': 'othertype'}), '([(0, 1), (0, 1), (0, 1), (0, 1)], dtype=othertype)\n', (151311, 151362), True, 'import numpy as np\n'), ((151582, 151631), 'numpy.array', 'np.array', (['[(0, (1, 0)), (0, (1, 0))]'], {'dtype': 'dtype'}), '([(0, (1, 0)), (0, (1, 0))], dtype=dtype)\n', (151590, 151631), True, 'import numpy as np\n'), ((151648, 151697), 'numpy.array', 'np.array', (['[(1, (0, 1)), (0, (0, 0))]'], {'dtype': 'dtype'}), '([(1, (0, 1)), (0, (0, 0))], dtype=dtype)\n', (151656, 151697), True, 'import numpy as np\n'), ((151714, 151763), 'numpy.array', 'np.array', (['[(1, (1, 1)), (0, (1, 0))]'], {'dtype': 'dtype'}), '([(1, (1, 1)), (0, (1, 0))], dtype=dtype)\n', (151722, 151763), True, 'import numpy as np\n'), ((151918, 151952), 'numpy.array', 'np.array', (['[0, 0, 1]'], {'dtype': 'np.bool'}), '([0, 0, 1], dtype=np.bool)\n', (151926, 151952), True, 'import numpy as np\n'), ((152040, 152100), 'numpy.array', 'np.array', (['[(0, 0), (0, 1)]'], {'dtype': "[('a', bool), ('b', bool)]"}), "([(0, 0), (0, 1)], dtype=[('a', bool), ('b', bool)])\n", (152048, 152100), True, 'import numpy as np\n'), ((152116, 152134), 'numpy.ma.core.flatten_mask', 'flatten_mask', (['mask'], {}), '(mask)\n', (152128, 152134), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((152153, 152187), 'numpy.array', 'np.array', (['[0, 0, 0, 1]'], {'dtype': 'bool'}), '([0, 0, 0, 1], dtype=bool)\n', (152161, 152187), True, 'import numpy as np\n'), ((152196, 152223), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (152208, 152223), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((152350, 152378), 'numpy.array', 'np.array', (['data'], {'dtype': 'mdtype'}), '(data, dtype=mdtype)\n', (152358, 152378), True, 'import numpy as np\n'), ((152394, 152412), 'numpy.ma.core.flatten_mask', 'flatten_mask', (['mask'], {}), '(mask)\n', (152406, 152412), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((152431, 152471), 'numpy.array', 'np.array', (['[0, 0, 0, 0, 0, 1]'], {'dtype': 'bool'}), '([0, 0, 0, 0, 0, 1], dtype=bool)\n', (152439, 152471), True, 'import numpy as np\n'), ((152480, 152507), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (152492, 152507), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((152589, 152611), 'numpy.array', 'np.array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (152597, 152611), True, 'import numpy as np\n'), ((152624, 152644), 'numpy.ma.core.array', 'array', (['a'], {'mask': '(False)'}), '(a, mask=False)\n', (152629, 152644), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((152660, 152667), 'numpy.ma.core.anom', 'anom', (['a'], {}), '(a)\n', (152664, 152667), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((152720, 152738), 'numpy.ma.core.reshape', 'reshape', (['a', '(2, 2)'], {}), '(a, (2, 2))\n', (152727, 152738), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((152920, 152932), 'numpy.arange', 'np.arange', (['(8)'], {}), '(8)\n', (152929, 152932), True, 'import numpy as np\n'), ((152973, 153008), 'numpy.array', 'np.array', (['[True, False, True, True]'], {}), '([True, False, True, True])\n', (152981, 153008), True, 'import numpy as np\n'), ((153057, 153090), 'numpy.ma.compress', 'np.ma.compress', (['cond', 'arr'], {'axis': '(0)'}), '(cond, arr, axis=0)\n', (153071, 153090), True, 'import numpy as np\n'), ((153099, 153126), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (153111, 153126), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((153142, 153158), 'numpy.ma.array', 'np.ma.array', (['arr'], {}), '(arr)\n', (153153, 153158), True, 'import numpy as np\n'), ((153174, 153208), 'numpy.ma.compress', 'np.ma.compress', (['cond', 'marr'], {'axis': '(0)'}), '(cond, marr, axis=0)\n', (153188, 153208), True, 'import numpy as np\n'), ((153217, 153244), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (153229, 153244), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((153354, 153373), 'numpy.ma.array', 'np.ma.array', (['[1, 2]'], {}), '([1, 2])\n', (153365, 153373), True, 'import numpy as np\n'), ((153389, 153408), 'numpy.ma.compressed', 'np.ma.compressed', (['a'], {}), '(a)\n', (153405, 153408), True, 'import numpy as np\n'), ((153606, 153625), 'numpy.ma.compressed', 'np.ma.compressed', (['a'], {}), '(a)\n', (153622, 153625), True, 'import numpy as np\n'), ((153713, 153741), 'numpy.ma.compressed', 'np.ma.compressed', (['[[1], [2]]'], {}), '([[1], [2]])\n', (153729, 153741), True, 'import numpy as np\n'), ((153749, 153775), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.ndim', '(1)'], {}), '(test.ndim, 1)\n', (153761, 153775), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((153791, 153820), 'numpy.ma.compressed', 'np.ma.compressed', (['[[[[[1]]]]]'], {}), '([[[[[1]]]]])\n', (153807, 153820), True, 'import numpy as np\n'), ((153829, 153855), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.ndim', '(1)'], {}), '(test.ndim, 1)\n', (153841, 153855), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((154018, 154044), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.ndim', '(1)'], {}), '(test.ndim, 1)\n', (154030, 154044), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((154235, 154257), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', '(42)'], {}), '(test, 42)\n', (154247, 154257), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((155793, 155824), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_a.dtype', 'int'], {}), '(base_a.dtype, int)\n', (155805, 155824), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((155833, 155876), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_a._data', '[3, 2, 3, 4, 5]'], {}), '(base_a._data, [3, 2, 3, 4, 5])\n', (155845, 155876), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((155886, 155919), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_b.dtype', 'float'], {}), '(base_b.dtype, float)\n', (155898, 155919), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((155928, 155980), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_b._data', '[pi, 2.2, 3.3, 4.4, 5.5]'], {}), '(base_b._data, [pi, 2.2, 3.3, 4.4, 5.5])\n', (155940, 155980), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((155990, 156023), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_c.dtype', '"""|S8"""'], {}), "(base_c.dtype, '|S8')\n", (156002, 156023), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((156319, 156350), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_a.dtype', 'int'], {}), '(base_a.dtype, int)\n', (156331, 156350), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((156359, 156402), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_a._data', '[3, 3, 3, 4, 5]'], {}), '(base_a._data, [3, 3, 3, 4, 5])\n', (156371, 156402), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((156412, 156445), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_b.dtype', 'float'], {}), '(base_b.dtype, float)\n', (156424, 156445), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((156454, 156504), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_b._data', '[pi, pi, pi, 4.4, 5.5]'], {}), '(base_b._data, [pi, pi, pi, 4.4, 5.5])\n', (156466, 156504), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((156514, 156547), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base_c.dtype', '"""|S8"""'], {}), "(base_c.dtype, '|S8')\n", (156526, 156547), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((157063, 157085), 'numpy.ma.core.empty', 'empty', (['(3)'], {'dtype': 'ndtype'}), '(3, dtype=ndtype)\n', (157068, 157085), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((157582, 157600), 'numpy.array', 'np.array', (['iterator'], {}), '(iterator)\n', (157590, 157600), True, 'import numpy as np\n'), ((157613, 157664), 'numpy.ma.core.array', 'array', (['iterator'], {'dtype': "[('a', float), ('b', float)]"}), "(iterator, dtype=[('a', float), ('b', float)])\n", (157618, 157664), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((157714, 157750), 'numpy.array', 'np.array', (['([1] + 19 * [0])'], {'dtype': 'bool'}), '([1] + 19 * [0], dtype=bool)\n', (157722, 157750), True, 'import numpy as np\n'), ((157874, 157910), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'controlmask'], {}), '(test.mask, controlmask)\n', (157886, 157910), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((157989, 158013), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'data'], {}), '(test, data)\n', (158001, 158013), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((158128, 158152), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'data'], {}), '(test, data)\n', (158140, 158152), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((158720, 158764), 'numpy.ma.testutils.assert_equal_records', 'assert_equal_records', (['a[0]._data', 'a._data[0]'], {}), '(a[0]._data, a._data[0])\n', (158740, 158764), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((158773, 158817), 'numpy.ma.testutils.assert_equal_records', 'assert_equal_records', (['a[0]._mask', 'a._mask[0]'], {}), '(a[0]._mask, a._mask[0])\n', (158793, 158817), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((158911, 158957), 'numpy.ma.testutils.assert_equal_records', 'assert_equal_records', (['a[-2]._data', 'a._data[-2]'], {}), '(a[-2]._data, a._data[-2])\n', (158931, 158957), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((158966, 159012), 'numpy.ma.testutils.assert_equal_records', 'assert_equal_records', (['a[-2]._mask', 'a._mask[-2]'], {}), '(a[-2]._mask, a._mask[-2])\n', (158986, 159012), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((159172, 159208), 'numpy.dtype', 'np.dtype', (["[('a', float), ('b', int)]"], {}), "([('a', float), ('b', int)])\n", (159180, 159208), True, 'import numpy as np\n'), ((159222, 159275), 'numpy.ma.MaskedArray', 'np.ma.MaskedArray', (['[(1.0, 1), (2.0, 2)]'], {'dtype': 'ndtype'}), '([(1.0, 1), (2.0, 2)], dtype=ndtype)\n', (159239, 159275), True, 'import numpy as np\n'), ((159468, 159504), 'numpy.dtype', 'np.dtype', (["[('a', bool), ('b', bool)]"], {}), "([('a', bool), ('b', bool)])\n", (159476, 159504), True, 'import numpy as np\n'), ((159543, 159596), 'numpy.array', 'np.array', (['[(False, True), (True, True)]'], {'dtype': 'mdtype'}), '([(False, True), (True, True)], dtype=mdtype)\n', (159551, 159596), True, 'import numpy as np\n'), ((159609, 159645), 'numpy.ma.masked_all', 'np.ma.masked_all', (['(2,)'], {'dtype': 'ndtype'}), '((2,), dtype=ndtype)\n', (159625, 159645), True, 'import numpy as np\n'), ((159676, 159705), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', 'control'], {}), '(a.mask, control)\n', (159688, 159705), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((159718, 159754), 'numpy.ma.masked_all', 'np.ma.masked_all', (['(2,)'], {'dtype': 'ndtype'}), '((2,), dtype=ndtype)\n', (159734, 159754), True, 'import numpy as np\n'), ((159785, 159814), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', 'control'], {}), '(a.mask, control)\n', (159797, 159814), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((159853, 159905), 'numpy.array', 'np.array', (['[(True, True), (True, True)]'], {'dtype': 'mdtype'}), '([(True, True), (True, True)], dtype=mdtype)\n', (159861, 159905), True, 'import numpy as np\n'), ((159918, 159954), 'numpy.ma.masked_all', 'np.ma.masked_all', (['(2,)'], {'dtype': 'ndtype'}), '((2,), dtype=ndtype)\n', (159934, 159954), True, 'import numpy as np\n'), ((160009, 160038), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', 'control'], {}), '(a.mask, control)\n', (160021, 160038), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((160051, 160087), 'numpy.ma.masked_all', 'np.ma.masked_all', (['(2,)'], {'dtype': 'ndtype'}), '((2,), dtype=ndtype)\n', (160067, 160087), True, 'import numpy as np\n'), ((160142, 160171), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', 'control'], {}), '(a.mask, control)\n', (160154, 160171), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((160502, 160520), 'numpy.array', 'np.array', (['iterator'], {}), '(iterator)\n', (160510, 160520), True, 'import numpy as np\n'), ((160533, 160584), 'numpy.ma.core.array', 'array', (['iterator'], {'dtype': "[('a', float), ('b', float)]"}), "(iterator, dtype=[('a', float), ('b', float)])\n", (160538, 160584), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((160634, 160670), 'numpy.array', 'np.array', (['([1] + 19 * [0])'], {'dtype': 'bool'}), '([1] + 19 * [0], dtype=bool)\n', (160642, 160670), True, 'import numpy as np\n'), ((160881, 160914), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test._data', 'a._data'], {}), '(test._data, a._data)\n', (160893, 160914), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((160923, 160956), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test._mask', 'a._mask'], {}), '(test._mask, a._mask)\n', (160935, 160956), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((161135, 161162), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'a._data'], {}), '(test, a._data)\n', (161147, 161162), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((161470, 161506), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', 'controlmask'], {}), '(test.mask, controlmask)\n', (161482, 161506), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((161655, 161702), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask.dtype.names', "('A', 'B')"], {}), "(test.mask.dtype.names, ('A', 'B'))\n", (161667, 161702), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((161711, 161742), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["test['A']", "a['a']"], {}), "(test['A'], a['a'])\n", (161723, 161742), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((161751, 161782), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["test['B']", "a['b']"], {}), "(test['B'], a['b'])\n", (161763, 161782), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((161902, 161949), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask.dtype.names', "('A', 'B')"], {}), "(test.mask.dtype.names, ('A', 'B'))\n", (161914, 161949), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((161958, 161992), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["test['A']", "a['a'][0]"], {}), "(test['A'], a['a'][0])\n", (161970, 161992), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((162001, 162035), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["test['B']", "a['b'][0]"], {}), "(test['B'], a['b'][0])\n", (162013, 162035), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((162156, 162198), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.dtype.names', "('A', 'B')"], {}), "(test.dtype.names, ('A', 'B'))\n", (162168, 162198), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((162207, 162242), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["test['A']", "a['a'][-1]"], {}), "(test['A'], a['a'][-1])\n", (162219, 162242), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((162251, 162286), 'numpy.ma.testutils.assert_equal', 'assert_equal', (["test['B']", "a['b'][-1]"], {}), "(test['B'], a['b'][-1])\n", (162263, 162286), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((162489, 162513), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'data'], {}), '(test, data)\n', (162501, 162513), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((162709, 162736), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'data[0]'], {}), '(test, data[0])\n', (162721, 162736), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((162745, 162776), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test.mask', '(1, 0)'], {}), '(test.mask, (1, 0))\n', (162757, 162776), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((162915, 162943), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'data[-1]'], {}), '(test, data[-1])\n', (162927, 162943), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((163085, 163109), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'data'], {}), '(test, data)\n', (163097, 163109), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((163555, 163577), 'numpy.ma.array', 'np.ma.array', (['d'], {'mask': 'm'}), '(d, mask=m)\n', (163566, 163577), True, 'import numpy as np\n'), ((164876, 164898), 'numpy.ma.array', 'np.ma.array', (['d'], {'mask': 'm'}), '(d, mask=m)\n', (164887, 164898), True, 'import numpy as np\n'), ((165196, 165218), 'numpy.ma.array', 'np.ma.array', (['d'], {'mask': 'm'}), '(d, mask=m)\n', (165207, 165218), True, 'import numpy as np\n'), ((165639, 165687), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'count', 'a'], {'axis': '(1, 1)'}), '(ValueError, count, a, axis=(1, 1))\n', (165652, 165687), False, 'from numpy.testing import TestCase, run_module_suite, assert_raises\n'), ((165695, 165738), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'count', 'a'], {'axis': '(3)'}), '(ValueError, count, a, axis=3)\n', (165708, 165738), False, 'from numpy.testing import TestCase, run_module_suite, assert_raises\n'), ((165786, 165813), 'numpy.ma.array', 'np.ma.array', (['d'], {'mask': 'nomask'}), '(d, mask=nomask)\n', (165797, 165813), True, 'import numpy as np\n'), ((166234, 166282), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'count', 'a'], {'axis': '(1, 1)'}), '(ValueError, count, a, axis=(1, 1))\n', (166247, 166282), False, 'from numpy.testing import TestCase, run_module_suite, assert_raises\n'), ((166290, 166333), 'numpy.testing.assert_raises', 'assert_raises', (['ValueError', 'count', 'a'], {'axis': '(3)'}), '(ValueError, count, a, axis=3)\n', (166303, 166333), False, 'from numpy.testing import TestCase, run_module_suite, assert_raises\n'), ((166631, 166645), 'numpy.argwhere', 'np.argwhere', (['a'], {}), '(a)\n', (166642, 166645), True, 'import numpy as np\n'), ((3560, 3577), 'numpy.ma.core.isMaskedArray', 'isMaskedArray', (['xm'], {}), '(xm)\n', (3573, 3577), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((3735, 3747), 'numpy.shape', 'np.shape', (['xm'], {}), '(xm)\n', (3743, 3747), True, 'import numpy as np\n'), ((3896, 3925), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 's'], {}), '(lambda x, y: x * y, s)\n', (3902, 3925), False, 'from functools import reduce\n'), ((3947, 3956), 'numpy.ma.core.count', 'count', (['xm'], {}), '(xm)\n', (3952, 3956), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((4061, 4078), 'numpy.ma.core.filled', 'filled', (['xm', '(1e+20)'], {}), '(xm, 1e+20)\n', (4067, 4078), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((4581, 4606), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm.shape', 's'], {}), '(xm.shape, s)\n', (4593, 4606), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((4760, 4780), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', 'xf'], {}), '(xm, xf)\n', (4772, 4780), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((4841, 4860), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', 'xm'], {}), '(x, xm)\n', (4853, 4860), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((5039, 5061), 'numpy.concatenate', 'np.concatenate', (['(x, y)'], {}), '((x, y))\n', (5053, 5061), True, 'import numpy as np\n'), ((5063, 5084), 'numpy.ma.core.concatenate', 'concatenate', (['(xm, ym)'], {}), '((xm, ym))\n', (5074, 5084), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((5107, 5129), 'numpy.concatenate', 'np.concatenate', (['(x, y)'], {}), '((x, y))\n', (5121, 5129), True, 'import numpy as np\n'), ((5131, 5150), 'numpy.ma.core.concatenate', 'concatenate', (['(x, y)'], {}), '((x, y))\n', (5142, 5150), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((5173, 5195), 'numpy.concatenate', 'np.concatenate', (['(x, y)'], {}), '((x, y))\n', (5187, 5195), True, 'import numpy as np\n'), ((5197, 5217), 'numpy.ma.core.concatenate', 'concatenate', (['(xm, y)'], {}), '((xm, y))\n', (5208, 5217), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((5240, 5265), 'numpy.concatenate', 'np.concatenate', (['(x, y, x)'], {}), '((x, y, x))\n', (5254, 5265), True, 'import numpy as np\n'), ((5267, 5290), 'numpy.ma.core.concatenate', 'concatenate', (['(x, ym, x)'], {}), '((x, ym, x))\n', (5278, 5290), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((5562, 5579), 'numpy.reshape', 'np.reshape', (['m1', 's'], {}), '(m1, s)\n', (5572, 5579), True, 'import numpy as np\n'), ((5611, 5628), 'numpy.reshape', 'np.reshape', (['m2', 's'], {}), '(m2, s)\n', (5621, 5628), True, 'import numpy as np\n'), ((5691, 5716), 'numpy.concatenate', 'np.concatenate', (['(x, y)', '(1)'], {}), '((x, y), 1)\n', (5705, 5716), True, 'import numpy as np\n'), ((5745, 5782), 'numpy.concatenate', 'np.concatenate', (['(xm.mask, ym.mask)', '(1)'], {}), '((xm.mask, ym.mask), 1)\n', (5759, 5782), True, 'import numpy as np\n'), ((5836, 5843), 'numpy.ma.core.ones', 'ones', (['(2)'], {}), '(2)\n', (5840, 5843), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7766, 7801), 'numpy.may_share_memory', 'np.may_share_memory', (['x.mask', 'y.mask'], {}), '(x.mask, y.mask)\n', (7785, 7801), True, 'import numpy as np\n'), ((8058, 8070), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (8067, 8070), True, 'import numpy as np\n'), ((8865, 8874), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (8871, 8874), True, 'import numpy as np\n'), ((9083, 9092), 'numpy.eye', 'np.eye', (['(3)'], {}), '(3)\n', (9089, 9092), True, 'import numpy as np\n'), ((9307, 9336), 'numpy.errstate', 'np.errstate', ([], {'invalid': '"""ignore"""'}), "(invalid='ignore')\n", (9318, 9336), True, 'import numpy as np\n'), ((9357, 9405), 'numpy.ma.core.masked_array', 'masked_array', (['[np.nan, 0.0, 1.0]'], {'mask': '[0, 0, 1]'}), '([np.nan, 0.0, 1.0], mask=[0, 0, 1])\n', (9369, 9405), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((9429, 9446), 'numpy.ma.core.fix_invalid', 'fix_invalid', (['data'], {}), '(data)\n', (9440, 9446), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((9459, 9518), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['data_fixed._data', '[data.fill_value, 0.0, 1.0]'], {}), '(data_fixed._data, [data.fill_value, 0.0, 1.0])\n', (9471, 9518), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((9529, 9576), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['data_fixed._mask', '[1.0, 0.0, 1.0]'], {}), '(data_fixed._mask, [1.0, 0.0, 1.0])\n', (9541, 9576), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((9792, 9807), 'numpy.ma.core.filled', 'filled', (['x[1]', '(0)'], {}), '(x[1], 0)\n', (9798, 9807), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((10488, 10499), 'numpy.sort', 'np.sort', (['x1'], {}), '(x1)\n', (10495, 10499), True, 'import numpy as np\n'), ((10501, 10524), 'numpy.ma.core.sort', 'sort', (['x2'], {'endwith': '(False)'}), '(x2, endwith=False)\n', (10505, 10524), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11451, 11463), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (11460, 11463), True, 'import numpy as np\n'), ((13981, 14002), 'numpy.ma.core.allequal', 'allequal', (['x1', 'y1.data'], {}), '(x1, y1.data)\n', (13989, 14002), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14657, 14677), 'numpy.ma.core.allequal', 'allequal', (['y2.mask', '(0)'], {}), '(y2.mask, 0)\n', (14665, 14677), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14877, 14898), 'numpy.ma.core.concatenate', 'concatenate', (['[x4, x4]'], {}), '([x4, x4])\n', (14888, 14898), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14925, 14936), 'numpy.ma.core.getmask', 'getmask', (['y4'], {}), '(y4)\n', (14932, 14936), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((18721, 18736), 'pickle.dumps', 'pickle.dumps', (['b'], {}), '(b)\n', (18733, 18736), False, 'import pickle\n'), ((19361, 19374), 'numpy.ma.core.array', 'array', (['[1, 1]'], {}), '([1, 1])\n', (19366, 19374), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((19390, 19415), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (19413, 19415), False, 'import warnings\n'), ((19429, 19473), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""', 'UserWarning'], {}), "('ignore', UserWarning)\n", (19450, 19473), False, 'import warnings\n'), ((22022, 22066), 'numpy.array', 'np.array', (["[(1, '1', 1.0)]"], {'dtype': 'flexi.dtype'}), "([(1, '1', 1.0)], dtype=flexi.dtype)\n", (22030, 22066), True, 'import numpy as np\n'), ((23650, 23693), 'numpy.array', 'np.array', (['[(0, 1, 2), (4, 5, 6)]'], {'order': '"""F"""'}), "([(0, 1, 2), (4, 5, 6)], order='F')\n", (23658, 23693), True, 'import numpy as np\n'), ((27014, 27046), 'numpy.array', 'np.array', (['[(1, 2)]'], {'dtype': 'ndtype'}), '([(1, 2)], dtype=ndtype)\n', (27022, 27046), True, 'import numpy as np\n'), ((27123, 27174), 'numpy.ma.core.masked_array', 'masked_array', (['[(1, 2)]'], {'mask': '[(1, 0)]', 'dtype': 'ndtype'}), '([(1, 2)], mask=[(1, 0)], dtype=ndtype)\n', (27135, 27174), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((28189, 28247), 'numpy.ma.core.masked_array', 'masked_array', ([], {'data': '[0, 1]', 'mask': '[True, False]', 'dtype': '""">i2"""'}), "(data=[0, 1], mask=[True, False], dtype='>i2')\n", (28201, 28247), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((29062, 29106), 'numpy.ma.core.masked_print_option.set_display', 'masked_print_option.set_display', (['ini_display'], {}), '(ini_display)\n', (29093, 29106), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((31160, 31190), 'numpy.all', 'np.all', (['(mx[1].data == mx2.data)'], {}), '(mx[1].data == mx2.data)\n', (31166, 31190), True, 'import numpy as np\n'), ((31208, 31226), 'numpy.all', 'np.all', (['mx[1].mask'], {}), '(mx[1].mask)\n', (31214, 31226), True, 'import numpy as np\n'), ((32734, 32755), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(-x)', '(-xm)'], {}), '(-x, -xm)\n', (32746, 32755), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((32768, 32796), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x + y)', '(xm + ym)'], {}), '(x + y, xm + ym)\n', (32780, 32796), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((32809, 32837), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x - y)', '(xm - ym)'], {}), '(x - y, xm - ym)\n', (32821, 32837), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((32850, 32878), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x * y)', '(xm * ym)'], {}), '(x * y, xm * ym)\n', (32862, 32878), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((32891, 32919), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x / y)', '(xm / ym)'], {}), '(x / y, xm / ym)\n', (32903, 32919), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((32932, 32963), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a10 + y)', '(a10 + ym)'], {}), '(a10 + y, a10 + ym)\n', (32944, 32963), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((32976, 33007), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a10 - y)', '(a10 - ym)'], {}), '(a10 - y, a10 - ym)\n', (32988, 33007), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33020, 33051), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a10 * y)', '(a10 * ym)'], {}), '(a10 * y, a10 * ym)\n', (33032, 33051), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33064, 33095), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(a10 / y)', '(a10 / ym)'], {}), '(a10 / y, a10 / ym)\n', (33076, 33095), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33108, 33139), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x + a10)', '(xm + a10)'], {}), '(x + a10, xm + a10)\n', (33120, 33139), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33152, 33183), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x - a10)', '(xm - a10)'], {}), '(x - a10, xm - a10)\n', (33164, 33183), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33196, 33227), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x * a10)', '(xm * a10)'], {}), '(x * a10, xm * a10)\n', (33208, 33227), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33240, 33271), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x / a10)', '(xm / a10)'], {}), '(x / a10, xm / a10)\n', (33252, 33271), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33284, 33313), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x ** 2)', '(xm ** 2)'], {}), '(x ** 2, xm ** 2)\n', (33296, 33313), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((33382, 33412), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['(x ** y)', '(xm ** ym)'], {}), '(x ** y, xm ** ym)\n', (33394, 33412), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((34523, 34538), 'numpy.finfo', 'np.finfo', (['float'], {}), '(float)\n', (34531, 34538), True, 'import numpy as np\n'), ((34606, 34625), 'numpy.ma.core.getmaskarray', 'getmaskarray', (['(a / 2)'], {}), '(a / 2)\n', (34618, 34625), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((34659, 34678), 'numpy.ma.core.getmaskarray', 'getmaskarray', (['(2 / a)'], {}), '(2 / a)\n', (34671, 34678), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36285, 36298), 'numpy.ma.core.array', 'array', (['(0, 0)'], {}), '((0, 0))\n', (36290, 36298), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36541, 36550), 'numpy.cos', 'np.cos', (['x'], {}), '(x)\n', (36547, 36550), True, 'import numpy as np\n'), ((36552, 36559), 'numpy.ma.core.cos', 'cos', (['xm'], {}), '(xm)\n', (36555, 36559), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36582, 36592), 'numpy.cosh', 'np.cosh', (['x'], {}), '(x)\n', (36589, 36592), True, 'import numpy as np\n'), ((36594, 36602), 'numpy.ma.core.cosh', 'cosh', (['xm'], {}), '(xm)\n', (36598, 36602), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36625, 36634), 'numpy.sin', 'np.sin', (['x'], {}), '(x)\n', (36631, 36634), True, 'import numpy as np\n'), ((36636, 36643), 'numpy.ma.core.sin', 'sin', (['xm'], {}), '(xm)\n', (36639, 36643), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36666, 36676), 'numpy.sinh', 'np.sinh', (['x'], {}), '(x)\n', (36673, 36676), True, 'import numpy as np\n'), ((36678, 36686), 'numpy.ma.core.sinh', 'sinh', (['xm'], {}), '(xm)\n', (36682, 36686), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36709, 36718), 'numpy.tan', 'np.tan', (['x'], {}), '(x)\n', (36715, 36718), True, 'import numpy as np\n'), ((36720, 36727), 'numpy.ma.core.tan', 'tan', (['xm'], {}), '(xm)\n', (36723, 36727), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36750, 36760), 'numpy.tanh', 'np.tanh', (['x'], {}), '(x)\n', (36757, 36760), True, 'import numpy as np\n'), ((36762, 36770), 'numpy.ma.core.tanh', 'tanh', (['xm'], {}), '(xm)\n', (36766, 36770), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36810, 36818), 'numpy.ma.core.sqrt', 'sqrt', (['xm'], {}), '(xm)\n', (36814, 36818), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36857, 36864), 'numpy.ma.core.log', 'log', (['xm'], {}), '(xm)\n', (36860, 36864), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36905, 36914), 'numpy.ma.core.log10', 'log10', (['xm'], {}), '(xm)\n', (36910, 36914), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36937, 36946), 'numpy.exp', 'np.exp', (['x'], {}), '(x)\n', (36943, 36946), True, 'import numpy as np\n'), ((36948, 36955), 'numpy.ma.core.exp', 'exp', (['xm'], {}), '(xm)\n', (36951, 36955), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36978, 36990), 'numpy.arcsin', 'np.arcsin', (['z'], {}), '(z)\n', (36987, 36990), True, 'import numpy as np\n'), ((36992, 37002), 'numpy.ma.core.arcsin', 'arcsin', (['zm'], {}), '(zm)\n', (36998, 37002), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37025, 37037), 'numpy.arccos', 'np.arccos', (['z'], {}), '(z)\n', (37034, 37037), True, 'import numpy as np\n'), ((37039, 37049), 'numpy.ma.core.arccos', 'arccos', (['zm'], {}), '(zm)\n', (37045, 37049), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37072, 37084), 'numpy.arctan', 'np.arctan', (['z'], {}), '(z)\n', (37081, 37084), True, 'import numpy as np\n'), ((37086, 37096), 'numpy.ma.core.arctan', 'arctan', (['zm'], {}), '(zm)\n', (37092, 37096), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37119, 37135), 'numpy.arctan2', 'np.arctan2', (['x', 'y'], {}), '(x, y)\n', (37129, 37135), True, 'import numpy as np\n'), ((37137, 37152), 'numpy.ma.core.arctan2', 'arctan2', (['xm', 'ym'], {}), '(xm, ym)\n', (37144, 37152), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37175, 37189), 'numpy.absolute', 'np.absolute', (['x'], {}), '(x)\n', (37186, 37189), True, 'import numpy as np\n'), ((37191, 37203), 'numpy.ma.core.absolute', 'absolute', (['xm'], {}), '(xm)\n', (37199, 37203), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37226, 37248), 'numpy.angle', 'np.angle', (['(x + 1.0j * y)'], {}), '(x + 1.0j * y)\n', (37234, 37248), True, 'import numpy as np\n'), ((37246, 37267), 'numpy.ma.core.angle', 'angle', (['(xm + 1.0j * ym)'], {}), '(xm + 1.0j * ym)\n', (37251, 37267), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37286, 37318), 'numpy.angle', 'np.angle', (['(x + 1.0j * y)'], {'deg': '(True)'}), '(x + 1.0j * y, deg=True)\n', (37294, 37318), True, 'import numpy as np\n'), ((37316, 37347), 'numpy.ma.core.angle', 'angle', (['(xm + 1.0j * ym)'], {'deg': '(True)'}), '(xm + 1.0j * ym, deg=True)\n', (37321, 37347), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37366, 37380), 'numpy.equal', 'np.equal', (['x', 'y'], {}), '(x, y)\n', (37374, 37380), True, 'import numpy as np\n'), ((37382, 37395), 'numpy.ma.core.equal', 'equal', (['xm', 'ym'], {}), '(xm, ym)\n', (37387, 37395), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37418, 37436), 'numpy.not_equal', 'np.not_equal', (['x', 'y'], {}), '(x, y)\n', (37430, 37436), True, 'import numpy as np\n'), ((37438, 37455), 'numpy.ma.core.not_equal', 'not_equal', (['xm', 'ym'], {}), '(xm, ym)\n', (37447, 37455), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37478, 37491), 'numpy.less', 'np.less', (['x', 'y'], {}), '(x, y)\n', (37485, 37491), True, 'import numpy as np\n'), ((37493, 37505), 'numpy.ma.core.less', 'less', (['xm', 'ym'], {}), '(xm, ym)\n', (37497, 37505), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37528, 37544), 'numpy.greater', 'np.greater', (['x', 'y'], {}), '(x, y)\n', (37538, 37544), True, 'import numpy as np\n'), ((37546, 37561), 'numpy.ma.core.greater', 'greater', (['xm', 'ym'], {}), '(xm, ym)\n', (37553, 37561), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37584, 37603), 'numpy.less_equal', 'np.less_equal', (['x', 'y'], {}), '(x, y)\n', (37597, 37603), True, 'import numpy as np\n'), ((37605, 37623), 'numpy.ma.core.less_equal', 'less_equal', (['xm', 'ym'], {}), '(xm, ym)\n', (37615, 37623), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37646, 37668), 'numpy.greater_equal', 'np.greater_equal', (['x', 'y'], {}), '(x, y)\n', (37662, 37668), True, 'import numpy as np\n'), ((37670, 37691), 'numpy.ma.core.greater_equal', 'greater_equal', (['xm', 'ym'], {}), '(xm, ym)\n', (37683, 37691), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37714, 37729), 'numpy.conjugate', 'np.conjugate', (['x'], {}), '(x)\n', (37726, 37729), True, 'import numpy as np\n'), ((37731, 37744), 'numpy.ma.core.conjugate', 'conjugate', (['xm'], {}), '(xm)\n', (37740, 37744), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37824, 37832), 'numpy.ma.core.count', 'count', (['(1)'], {}), '(1)\n', (37829, 37832), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((37858, 37876), 'numpy.ma.core.array', 'array', (['(1)'], {'mask': '[1]'}), '(1, mask=[1])\n', (37863, 37876), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38821, 38828), 'numpy.ma.core.max', 'max', (['xr'], {}), '(xr)\n', (38824, 38828), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38830, 38842), 'numpy.ma.core.maximum', 'maximum', (['xmr'], {}), '(xmr)\n', (38837, 38842), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38865, 38872), 'numpy.ma.core.min', 'min', (['xr'], {}), '(xr)\n', (38868, 38872), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38874, 38886), 'numpy.ma.core.minimum', 'minimum', (['xmr'], {}), '(xmr)\n', (38881, 38886), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38910, 38939), 'numpy.ma.core.minimum', 'minimum', (['[1, 2, 3]', '[4, 0, 9]'], {}), '([1, 2, 3], [4, 0, 9])\n', (38917, 38939), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38973, 39002), 'numpy.ma.core.maximum', 'maximum', (['[1, 2, 3]', '[4, 0, 9]'], {}), '([1, 2, 3], [4, 0, 9])\n', (38980, 39002), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39049, 39058), 'numpy.ma.core.arange', 'arange', (['(5)'], {}), '(5)\n', (39055, 39058), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39128, 39141), 'numpy.ma.core.minimum', 'minimum', (['x', 'y'], {}), '(x, y)\n', (39135, 39141), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39189, 39202), 'numpy.ma.core.maximum', 'maximum', (['x', 'y'], {}), '(x, y)\n', (39196, 39202), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39383, 39393), 'numpy.ma.core.maximum', 'maximum', (['x'], {}), '(x)\n', (39390, 39393), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39590, 39606), 'numpy.minimum', 'np.minimum', (['a', 'a'], {}), '(a, a)\n', (39600, 39606), True, 'import numpy as np\n'), ((39738, 39760), 'numpy.minimum.outer', 'np.minimum.outer', (['a', 'a'], {}), '(a, a)\n', (39754, 39760), True, 'import numpy as np\n'), ((39886, 39902), 'numpy.maximum', 'np.maximum', (['a', 'a'], {}), '(a, a)\n', (39896, 39902), True, 'import numpy as np\n'), ((40034, 40056), 'numpy.maximum.outer', 'np.maximum.outer', (['a', 'a'], {}), '(a, a)\n', (40050, 40056), True, 'import numpy as np\n'), ((40442, 40470), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(10)', '(12)'], {}), '(0, 10, 12)\n', (40459, 40470), True, 'import numpy as np\n'), ((40723, 40748), 'numpy.empty', 'np.empty', (['(4,)'], {'dtype': 'int'}), '((4,), dtype=int)\n', (40731, 40748), True, 'import numpy as np\n'), ((40890, 40917), 'numpy.empty', 'np.empty', (['(4,)'], {'dtype': 'float'}), '((4,), dtype=float)\n', (40898, 40917), True, 'import numpy as np\n'), ((42174, 42190), 'numpy.add.reduce', 'np.add.reduce', (['x'], {}), '(x)\n', (42187, 42190), True, 'import numpy as np\n'), ((42192, 42205), 'numpy.ma.core.add.reduce', 'add.reduce', (['x'], {}), '(x)\n', (42202, 42205), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42228, 42248), 'numpy.add.accumulate', 'np.add.accumulate', (['x'], {}), '(x)\n', (42245, 42248), True, 'import numpy as np\n'), ((42250, 42267), 'numpy.ma.core.add.accumulate', 'add.accumulate', (['x'], {}), '(x)\n', (42264, 42267), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42384, 42401), 'numpy.sum', 'np.sum', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (42390, 42401), True, 'import numpy as np\n'), ((42403, 42417), 'numpy.ma.core.sum', 'sum', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (42406, 42417), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42471, 42486), 'numpy.ma.core.sum', 'sum', (['xm'], {'axis': '(0)'}), '(xm, axis=0)\n', (42474, 42486), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42509, 42521), 'numpy.sum', 'np.sum', (['x', '(0)'], {}), '(x, 0)\n', (42515, 42521), True, 'import numpy as np\n'), ((42523, 42532), 'numpy.ma.core.sum', 'sum', (['x', '(0)'], {}), '(x, 0)\n', (42526, 42532), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42555, 42576), 'numpy.product', 'np.product', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (42565, 42576), True, 'import numpy as np\n'), ((42578, 42596), 'numpy.ma.core.product', 'product', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (42585, 42596), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42619, 42635), 'numpy.product', 'np.product', (['x', '(0)'], {}), '(x, 0)\n', (42629, 42635), True, 'import numpy as np\n'), ((42637, 42650), 'numpy.ma.core.product', 'product', (['x', '(0)'], {}), '(x, 0)\n', (42644, 42650), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42708, 42727), 'numpy.ma.core.product', 'product', (['xm'], {'axis': '(0)'}), '(xm, axis=0)\n', (42715, 42727), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((46806, 46815), 'numpy.ma.core.mod', 'mod', (['x', 'y'], {}), '(x, y)\n', (46809, 46815), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((46817, 46828), 'numpy.ma.core.mod', 'mod', (['xm', 'ym'], {}), '(xm, ym)\n', (46820, 46828), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((46884, 46898), 'numpy.mod', 'np.mod', (['ym', 'xm'], {}), '(ym, xm)\n', (46890, 46898), True, 'import numpy as np\n'), ((46932, 46957), 'numpy.ma.core.mask_or', 'mask_or', (['xm.mask', 'ym.mask'], {}), '(xm.mask, ym.mask)\n', (46939, 46957), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47013, 47027), 'numpy.mod', 'np.mod', (['xm', 'ym'], {}), '(xm, ym)\n', (47019, 47027), True, 'import numpy as np\n'), ((47366, 47392), 'numpy.transpose', 'np.transpose', (['y', '(2, 0, 1)'], {}), '(y, (2, 0, 1))\n', (47378, 47392), True, 'import numpy as np\n'), ((47394, 47417), 'numpy.ma.core.transpose', 'transpose', (['x', '(2, 0, 1)'], {}), '(x, (2, 0, 1))\n', (47403, 47417), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47440, 47464), 'numpy.take', 'np.take', (['y', '(2, 0, 1)', '(1)'], {}), '(y, (2, 0, 1), 1)\n', (47447, 47464), True, 'import numpy as np\n'), ((47466, 47487), 'numpy.ma.core.take', 'take', (['x', '(2, 0, 1)', '(1)'], {}), '(x, (2, 0, 1), 1)\n', (47470, 47487), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47569, 47580), 'numpy.ma.core.inner', 'inner', (['x', 'y'], {}), '(x, y)\n', (47574, 47580), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47662, 47673), 'numpy.ma.core.outer', 'outer', (['x', 'y'], {}), '(x, y)\n', (47667, 47673), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((48681, 48705), 'numpy.empty', 'np.empty', (['(4)'], {'dtype': 'float'}), '(4, dtype=float)\n', (48689, 48705), True, 'import numpy as np\n'), ((48857, 48882), 'numpy.ma.testutils.assert_', 'assert_', (['(result is output)'], {}), '(result is output)\n', (48864, 48882), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((48966, 48985), 'numpy.ma.core.empty', 'empty', (['(4)'], {'dtype': 'int'}), '(4, dtype=int)\n', (48971, 48985), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((49046, 49071), 'numpy.ma.testutils.assert_', 'assert_', (['(result is output)'], {}), '(result is output)\n', (49053, 49071), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((49084, 49112), 'numpy.ma.testutils.assert_', 'assert_', (['(output[0] is masked)'], {}), '(output[0] is masked)\n', (49091, 49112), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((49181, 49208), 'numpy.matrix', 'np.matrix', (['[[1, 2], [3, 4]]'], {}), '([[1, 2], [3, 4]])\n', (49190, 49208), True, 'import numpy as np\n'), ((54524, 54545), 'numpy.ma.core.filled', 'filled', (['(xh > 1)', '(False)'], {}), '(xh > 1, False)\n', (54530, 54545), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((54972, 54993), 'numpy.ma.core.filled', 'filled', (['(xh < 5)', '(False)'], {}), '(xh < 5, False)\n', (54978, 54993), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((55713, 55745), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]'}), '([1, 2, 3], mask=[1, 0, 0])\n', (55718, 55745), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((55843, 55875), 'numpy.ma.core.array', 'array', (['[0, 2, 3]'], {'mask': '[0, 0, 0]'}), '([0, 2, 3], mask=[0, 0, 0])\n', (55848, 55875), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((56174, 56183), 'numpy.ma.core.zeros', 'zeros', (['(10)'], {}), '(10)\n', (56179, 56183), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((56539, 56561), 'numpy.matrix', 'np.matrix', (['[[1, 2, 3]]'], {}), '([[1, 2, 3]])\n', (56548, 56561), True, 'import numpy as np\n'), ((56684, 56722), 'numpy.all', 'np.all', (['(test.flat[0:2] == test[0, 0:2])'], {}), '(test.flat[0:2] == test[0, 0:2])\n', (56690, 56722), True, 'import numpy as np\n'), ((56791, 56813), 'numpy.matrix', 'np.matrix', (['[[1, 2, 3]]'], {}), '([[1, 2, 3]])\n', (56800, 56813), True, 'import numpy as np\n'), ((56922, 56944), 'numpy.matrix', 'np.matrix', (['[[3, 2, 1]]'], {}), '([[3, 2, 1]])\n', (56931, 56944), True, 'import numpy as np\n'), ((57049, 57071), 'numpy.matrix', 'np.matrix', (['[[1, 2, 3]]'], {}), '([[1, 2, 3]])\n', (57058, 57071), True, 'import numpy as np\n'), ((58115, 58140), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xf', 'x[j, i]'], {}), '(xf, x[j, i])\n', (58127, 58140), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((58423, 58442), 'numpy.ma.core.array', 'array', (['[[1.0, 0.0]]'], {}), '([[1.0, 0.0]])\n', (58428, 58442), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((58473, 58496), 'numpy.ma.core.array', 'array', (['[[False, False]]'], {}), '([[False, False]])\n', (58478, 58496), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((58760, 58774), 'numpy.dtype', 'np.dtype', (['"""f4"""'], {}), "('f4')\n", (58768, 58774), True, 'import numpy as np\n'), ((58911, 58925), 'numpy.ma.array', 'np.ma.array', (['a'], {}), '(a)\n', (58922, 58925), True, 'import numpy as np\n'), ((58948, 58962), 'numpy.dtype', 'np.dtype', (['"""f8"""'], {}), "('f8')\n", (58956, 58962), True, 'import numpy as np\n'), ((59102, 59116), 'numpy.dtype', 'np.dtype', (['"""f4"""'], {}), "('f4')\n", (59110, 59116), True, 'import numpy as np\n'), ((59289, 59306), 'numpy.dtype', 'np.dtype', (['"""f4,i4"""'], {}), "('f4,i4')\n", (59297, 59306), True, 'import numpy as np\n'), ((59691, 59712), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0)'], {}), '(0)\n', (59709, 59712), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((59785, 59797), 'numpy.compat.asbytes', 'asbytes', (['"""0"""'], {}), "('0')\n", (59792, 59797), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((59872, 59903), 'numpy.ma.core.default_fill_value', 'default_fill_value', (["b'camelot!'"], {}), "(b'camelot!')\n", (59890, 59903), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((61952, 61966), 'numpy.compat.asbytes', 'asbytes', (['"""???"""'], {}), "('???')\n", (61959, 61966), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((62984, 63015), 'numpy.compat.asbytes_nested', 'asbytes_nested', (["['3', '4', '5']"], {}), "(['3', '4', '5'])\n", (62998, 63015), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((63176, 63197), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0)'], {}), '(0)\n', (63194, 63197), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((63310, 63333), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0.0)'], {}), '(0.0)\n', (63328, 63333), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((63437, 63458), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0)'], {}), '(0)\n', (63455, 63458), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((64163, 64177), 'numpy.compat.asbytes', 'asbytes', (['"""999"""'], {}), "('999')\n", (64170, 64177), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((64360, 64374), 'numpy.compat.asbytes', 'asbytes', (['"""???"""'], {}), "('???')\n", (64367, 64374), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((64572, 64587), 'numpy.array', 'np.array', (['(999.0)'], {}), '(999.0)\n', (64580, 64587), True, 'import numpy as np\n'), ((66612, 66639), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (66624, 66639), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((66786, 66813), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['test', 'control'], {}), '(test, control)\n', (66798, 66813), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((67090, 67116), 'numpy.ma.core.default_fill_value', 'default_fill_value', (["a['A']"], {}), "(a['A'])\n", (67108, 67116), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67156, 67188), 'numpy.ma.core.default_fill_value', 'default_fill_value', (["a['B']['BA']"], {}), "(a['B']['BA'])\n", (67174, 67188), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67228, 67260), 'numpy.ma.core.default_fill_value', 'default_fill_value', (["a['B']['BB']"], {}), "(a['B']['BB'])\n", (67246, 67260), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67330, 67356), 'numpy.ma.core.minimum_fill_value', 'minimum_fill_value', (["a['A']"], {}), "(a['A'])\n", (67348, 67356), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67391, 67423), 'numpy.ma.core.minimum_fill_value', 'minimum_fill_value', (["a['B']['BA']"], {}), "(a['B']['BA'])\n", (67409, 67423), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67458, 67490), 'numpy.ma.core.minimum_fill_value', 'minimum_fill_value', (["a['B']['BB']"], {}), "(a['B']['BB'])\n", (67476, 67490), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67522, 67548), 'numpy.ma.core.minimum_fill_value', 'minimum_fill_value', (["a['B']"], {}), "(a['B'])\n", (67540, 67548), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67618, 67644), 'numpy.ma.core.maximum_fill_value', 'maximum_fill_value', (["a['A']"], {}), "(a['A'])\n", (67636, 67644), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67679, 67711), 'numpy.ma.core.maximum_fill_value', 'maximum_fill_value', (["a['B']['BA']"], {}), "(a['B']['BA'])\n", (67697, 67711), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67746, 67778), 'numpy.ma.core.maximum_fill_value', 'maximum_fill_value', (["a['B']['BB']"], {}), "(a['B']['BB'])\n", (67764, 67778), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((67810, 67836), 'numpy.ma.core.maximum_fill_value', 'maximum_fill_value', (["a['B']"], {}), "(a['B'])\n", (67828, 67836), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((68209, 68221), 'numpy.array', 'np.array', (['(10)'], {}), '(10)\n', (68217, 68221), True, 'import numpy as np\n'), ((68544, 68556), 'numpy.array', 'np.array', (['(10)'], {}), '(10)\n', (68552, 68556), True, 'import numpy as np\n'), ((69115, 69129), 'numpy.isnan', 'np.isnan', (['f[0]'], {}), '(f[0])\n', (69123, 69129), True, 'import numpy as np\n'), ((69159, 69182), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(1.0)'], {}), '(1.0)\n', (69177, 69182), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((71976, 72003), 'numpy.ma.core.default_fill_value', 'default_fill_value', (["b'spam'"], {}), "(b'spam')\n", (71994, 72003), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((72046, 72072), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['"""eggs"""'], {}), "('eggs')\n", (72064, 72072), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((72240, 72294), 'numpy.ma.core.array', 'array', (['([1.0, 0, -1, pi / 2] * 2)'], {'mask': '([0, 1] + [0] * 6)'}), '([1.0, 0, -1, pi / 2] * 2, mask=[0, 1] + [0] * 6)\n', (72245, 72294), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((72314, 72368), 'numpy.ma.core.array', 'array', (['([1.0, 0, -1, pi / 2] * 2)'], {'mask': '([1, 0] + [0] * 6)'}), '([1.0, 0, -1, pi / 2] * 2, mask=[1, 0] + [0] * 6)\n', (72319, 72368), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((73699, 73745), 'numpy.ma.testutils.assert_mask_equal', 'assert_mask_equal', (['ur.mask', 'mr.mask'], {'err_msg': 'f'}), '(ur.mask, mr.mask, err_msg=f)\n', (73716, 73745), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((73908, 73927), 'numpy.ma.core.sometrue', 'sometrue', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (73916, 73927), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((73950, 73968), 'numpy.ma.core.sum', 'sum', (['a[:3]'], {'axis': '(0)'}), '(a[:3], axis=0)\n', (73953, 73968), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((73994, 74012), 'numpy.ma.core.product', 'product', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (74001, 74012), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((74038, 74051), 'numpy.ma.core.add.reduce', 'add.reduce', (['a'], {}), '(a)\n', (74048, 74051), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76452, 76477), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (76475, 76477), False, 'import warnings\n'), ((76491, 76523), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""error"""'], {}), "('error')\n", (76514, 76523), False, 'import warnings\n'), ((76580, 76586), 'numpy.ma.core.exp', 'exp', (['m'], {}), '(m)\n', (76583, 76586), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76599, 76608), 'numpy.ma.core.add', 'add', (['m', '(1)'], {}), '(m, 1)\n', (76602, 76608), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76683, 76690), 'numpy.ma.core.sqrt', 'sqrt', (['m'], {}), '(m)\n', (76687, 76690), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76703, 76709), 'numpy.ma.core.log', 'log', (['m'], {}), '(m)\n', (76706, 76709), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76722, 76728), 'numpy.ma.core.tan', 'tan', (['m'], {}), '(m)\n', (76725, 76728), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76741, 76750), 'numpy.ma.core.arcsin', 'arcsin', (['m'], {}), '(m)\n', (76747, 76750), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76763, 76772), 'numpy.ma.core.arccos', 'arccos', (['m'], {}), '(m)\n', (76769, 76772), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76785, 76795), 'numpy.ma.core.arccosh', 'arccosh', (['m'], {}), '(m)\n', (76792, 76795), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76843, 76855), 'numpy.ma.core.divide', 'divide', (['m', '(2)'], {}), '(m, 2)\n', (76849, 76855), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76941, 76957), 'numpy.ma.core.allclose', 'allclose', (['m', '(0.5)'], {}), '(m, 0.5)\n', (76949, 76957), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((78270, 78288), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (78277, 78288), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((78830, 78848), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (78837, 78848), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((79406, 79424), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (79413, 79424), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((79556, 79566), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (79562, 79566), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((79584, 79594), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (79590, 79594), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((79932, 79943), 'numpy.ma.core.ones', 'ones', (['(10,)'], {}), '((10,))\n', (79936, 79943), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((81557, 81589), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]'}), '([1, 2, 3], mask=[1, 0, 0])\n', (81562, 81589), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((82398, 82430), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[1, 0, 0]'}), '([1, 2, 3], mask=[1, 0, 0])\n', (82403, 82430), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((83242, 83277), 'numpy.ma.core.array', 'array', (['[10, 20, 30]'], {'mask': '[1, 0, 0]'}), '([10, 20, 30], mask=[1, 0, 0])\n', (83247, 83277), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((84116, 84157), 'numpy.ma.core.array', 'array', (['[10.0, 20.0, 30.0]'], {'mask': '[1, 0, 0]'}), '([10.0, 20.0, 30.0], mask=[1, 0, 0])\n', (84121, 84157), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((85098, 85136), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[[0, 0], [0, 0]]'], {}), '(a.mask, [[0, 0], [0, 0]])\n', (85110, 85136), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((85539, 85577), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[[0, 0], [0, 0]]'], {}), '(a.mask, [[0, 0], [0, 0]])\n', (85551, 85577), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((85980, 86018), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['a.mask', '[[0, 0], [0, 0]]'], {}), '(a.mask, [[0, 0], [0, 0]])\n', (85992, 86018), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((97406, 97420), 'numpy.ma.core.allclose', 'allclose', (['a', 'b'], {}), '(a, b)\n', (97414, 97420), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((97566, 97580), 'numpy.ma.core.allclose', 'allclose', (['a', 'b'], {}), '(a, b)\n', (97574, 97580), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((97691, 97724), 'numpy.ma.core.allclose', 'allclose', (['a', 'b'], {'masked_equal': '(True)'}), '(a, b, masked_equal=True)\n', (97699, 97724), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((97885, 97918), 'numpy.ma.core.allclose', 'allclose', (['a', '(0)'], {'masked_equal': '(True)'}), '(a, 0, masked_equal=True)\n', (97893, 97918), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((98082, 98096), 'numpy.ma.core.allclose', 'allclose', (['a', 'a'], {}), '(a, a)\n', (98090, 98096), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((99703, 99734), 'numpy.matrix', 'np.matrix', (['[False, False, True]'], {}), '([False, False, True])\n', (99712, 99734), True, 'import numpy as np\n'), ((99841, 99872), 'numpy.matrix', 'np.matrix', (['[False, False, True]'], {}), '([False, False, True])\n', (99850, 99872), True, 'import numpy as np\n'), ((100059, 100089), 'numpy.matrix', 'np.matrix', (['[True, True, False]'], {}), '([True, True, False])\n', (100068, 100089), True, 'import numpy as np\n'), ((100201, 100231), 'numpy.matrix', 'np.matrix', (['[True, True, False]'], {}), '([True, True, False])\n', (100210, 100231), True, 'import numpy as np\n'), ((103960, 103983), 'numpy.matrix', 'np.matrix', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (103969, 103983), True, 'import numpy as np\n'), ((104975, 105010), 'numpy.may_share_memory', 'np.may_share_memory', (['a.mask', 'b.mask'], {}), '(a.mask, b.mask)\n', (104994, 105010), True, 'import numpy as np\n'), ((105425, 105435), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (105431, 105435), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((105543, 105582), 'numpy.ma.core.asarray', 'asarray', (['[6, 1, 4, 3, 2, 5, 0, 7, 8, 9]'], {}), '([6, 1, 4, 3, 2, 5, 0, 7, 8, 9])\n', (105550, 105582), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((105664, 105704), 'numpy.ma.core.masked_array', 'masked_array', (['[0, 2, 4, 6]', '[1, 0, 1, 0]'], {}), '([0, 2, 4, 6], [1, 0, 1, 0])\n', (105676, 105704), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((105857, 105867), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (105863, 105867), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((105951, 105990), 'numpy.ma.core.asarray', 'asarray', (['[6, 1, 4, 3, 2, 5, 0, 7, 8, 9]'], {}), '([6, 1, 4, 3, 2, 5, 0, 7, 8, 9])\n', (105958, 105990), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((106073, 106113), 'numpy.ma.core.masked_array', 'masked_array', (['[0, 2, 4, 6]', '[1, 0, 1, 0]'], {}), '([0, 2, 4, 6], [1, 0, 1, 0])\n', (106085, 106113), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((106999, 107008), 'numpy.ma.core.arange', 'arange', (['(6)'], {}), '(6)\n', (107005, 107008), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((108407, 108433), 'numpy.matrix', 'np.matrix', (['[1, 2, 3, 4, 5]'], {}), '([1, 2, 3, 4, 5])\n', (108416, 108433), True, 'import numpy as np\n'), ((113022, 113035), 'numpy.argsort', 'np.argsort', (['a'], {}), '(a)\n', (113032, 113035), True, 'import numpy as np\n'), ((113037, 113047), 'numpy.ma.core.argsort', 'argsort', (['a'], {}), '(a)\n', (113044, 113047), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((114545, 114582), 'numpy.ma.core.masked_array', 'masked_array', (['[10, 10, 40]', '[0, 0, 1]'], {}), '([10, 10, 40], [0, 0, 1])\n', (114557, 114582), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((114706, 114758), 'numpy.ma.core.masked_array', 'masked_array', (['[[10, 20], [10, 20]]', '[[0, 1], [0, 1]]'], {}), '([[10, 20], [10, 20]], [[0, 1], [0, 1]])\n', (114718, 114758), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((115050, 115100), 'numpy.ma.core.array', 'array', (['[[10, 30], [40, 60]]'], {'mask': '[[0, 1], [1, 0]]'}), '([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]])\n', (115055, 115100), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((115123, 115146), 'numpy.ma.core.take', 'take', (['x', '[0, 2]'], {'axis': '(1)'}), '(x, [0, 2], axis=1)\n', (115127, 115146), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((115169, 115219), 'numpy.ma.core.array', 'array', (['[[10, 30], [40, 60]]'], {'mask': '[[0, 1], [1, 0]]'}), '([[10, 30], [40, 60]], mask=[[0, 1], [1, 0]])\n', (115174, 115219), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((116447, 116460), 'numpy.arange', 'np.arange', (['(12)'], {}), '(12)\n', (116456, 116460), True, 'import numpy as np\n'), ((120682, 120713), 'numpy.ma.core.MaskedArray.cumsum', 'MaskedArray.cumsum', (['marray.T', '(0)'], {}), '(marray.T, 0)\n', (120700, 120713), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((122986, 123015), 'numpy.empty', 'np.empty', (['(3, 4)'], {'dtype': 'float'}), '((3, 4), dtype=float)\n', (122994, 123015), True, 'import numpy as np\n'), ((123284, 123308), 'numpy.ma.core.empty', 'empty', (['(3, 4)'], {'dtype': 'int'}), '((3, 4), dtype=int)\n', (123289, 123308), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((125267, 125279), 'numpy.trace', 'np.trace', (['mX'], {}), '(mX)\n', (125275, 125279), True, 'import numpy as np\n'), ((127747, 127757), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (127753, 127757), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((128242, 128271), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mout.mask', '(True)'], {}), '(mout.mask, True)\n', (128254, 128271), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((128509, 128519), 'numpy.ma.core.arange', 'arange', (['(10)'], {}), '(10)\n', (128515, 128519), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((128956, 128985), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['mout.mask', '(True)'], {}), '(mout.mask, True)\n', (128968, 128985), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((134397, 134417), 'numpy.ma.core.masked_greater', 'masked_greater', (['x', '(2)'], {}), '(x, 2)\n', (134411, 134417), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134499, 134525), 'numpy.ma.core.masked_greater_equal', 'masked_greater_equal', (['x', '(2)'], {}), '(x, 2)\n', (134519, 134525), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134577, 134594), 'numpy.ma.core.masked_less', 'masked_less', (['x', '(2)'], {}), '(x, 2)\n', (134588, 134594), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134673, 134696), 'numpy.ma.core.masked_less_equal', 'masked_less_equal', (['x', '(2)'], {}), '(x, 2)\n', (134690, 134696), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134753, 134775), 'numpy.ma.core.masked_not_equal', 'masked_not_equal', (['x', '(2)'], {}), '(x, 2)\n', (134769, 134775), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134828, 134846), 'numpy.ma.core.masked_equal', 'masked_equal', (['x', '(2)'], {}), '(x, 2)\n', (134840, 134846), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134903, 134925), 'numpy.ma.core.masked_not_equal', 'masked_not_equal', (['x', '(2)'], {}), '(x, 2)\n', (134919, 134925), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134948, 134994), 'numpy.ma.core.masked_where', 'masked_where', (['[1, 1, 0, 0, 0]', '[1, 2, 3, 4, 5]'], {}), '([1, 1, 0, 0, 0], [1, 2, 3, 4, 5])\n', (134960, 134994), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((135395, 135413), 'numpy.ma.core.masked_equal', 'masked_equal', (['(1)', 'a'], {}), '(1, a)\n', (135407, 135413), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((139249, 139263), 'numpy.identity', 'np.identity', (['(5)'], {}), '(5)\n', (139260, 139263), True, 'import numpy as np\n'), ((139337, 139350), 'numpy.ma.core.power', 'power', (['x', '(2.0)'], {}), '(x, 2.0)\n', (139342, 139350), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((142627, 142650), 'numpy.ma.where', 'np.ma.where', (['(True)', 'a', 'a'], {}), '(True, a, a)\n', (142638, 142650), True, 'import numpy as np\n'), ((142676, 142699), 'numpy.ma.where', 'np.ma.where', (['(True)', 'b', 'b'], {}), '(True, b, b)\n', (142687, 142699), True, 'import numpy as np\n'), ((143851, 143863), 'numpy.ma.core.arange', 'arange', (['(1)', '(6)'], {}), '(1, 6)\n', (143857, 143863), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144425, 144455), 'numpy.arange', 'np.arange', (['(4)'], {'dtype': 'np.float32'}), '(4, dtype=np.float32)\n', (144434, 144455), True, 'import numpy as np\n'), ((144477, 144497), 'numpy.ma.core.where', 'where', (['(x > 1.5)', 'y', 'x'], {}), '(x > 1.5, y, x)\n', (144482, 144497), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144838, 144860), 'numpy.ma.core.array', 'array', (['[20, 31, 12, 3]'], {}), '([20, 31, 12, 3])\n', (144843, 144860), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144951, 144973), 'numpy.ma.core.array', 'array', (['[20, 31, 12, 3]'], {}), '([20, 31, 12, 3])\n', (144956, 144973), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145064, 145085), 'numpy.ma.core.array', 'array', (['[20, 1, 12, 3]'], {}), '([20, 1, 12, 3])\n', (145069, 145085), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145271, 145293), 'numpy.ma.core.array', 'array', (['[99, 1, 12, 99]'], {}), '([99, 1, 12, 99])\n', (145276, 145293), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((145636, 145658), 'numpy.ma.core.array', 'array', (['[20, 31, 12, 3]'], {}), '([20, 31, 12, 3])\n', (145641, 145658), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146024, 146046), 'numpy.ma.core.array', 'array', (['[20, 31, 12, 3]'], {}), '([20, 31, 12, 3])\n', (146029, 146046), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146325, 146348), 'numpy.ma.core.array', 'array', (['[99, 31, 12, 99]'], {}), '([99, 31, 12, 99])\n', (146330, 146348), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146770, 146801), 'numpy.ma.core.array', 'array', (['[999999, 31, 12, 999999]'], {}), '([999999, 31, 12, 999999])\n', (146775, 146801), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((148141, 148158), 'numpy.dtype', 'np.dtype', (['np.bool'], {}), '(np.bool)\n', (148149, 148158), True, 'import numpy as np\n'), ((148536, 148567), 'numpy.dtype', 'np.dtype', (["[('a', (np.bool, 2))]"], {}), "([('a', (np.bool, 2))])\n", (148544, 148567), True, 'import numpy as np\n'), ((148690, 148720), 'numpy.dtype', 'np.dtype', (["[(('A', 'a'), bool)]"], {}), "([(('A', 'a'), bool)])\n", (148698, 148720), True, 'import numpy as np\n'), ((150048, 150088), 'numpy.array', 'np.array', (['[(0, 0), (0, 1)]'], {'dtype': 'bdtype'}), '([(0, 0), (0, 1)], dtype=bdtype)\n', (150056, 150088), True, 'import numpy as np\n'), ((150354, 150403), 'numpy.ma.core.make_mask', 'make_mask', (['nomask'], {'copy': 'cpy', 'shrink': 'shr', 'dtype': 'dt'}), '(nomask, copy=cpy, shrink=shr, dtype=dt)\n', (150363, 150403), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((150416, 150466), 'numpy.ma.testutils.assert_', 'assert_', (['(res is nomask)', '(msgformat % (cpy, shr, dt))'], {}), '(res is nomask, msgformat % (cpy, shr, dt))\n', (150423, 150466), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((151395, 151415), 'numpy.ma.core.mask_or', 'mask_or', (['mask', 'other'], {}), '(mask, other)\n', (151402, 151415), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((151785, 151806), 'numpy.ma.core.mask_or', 'mask_or', (['amask', 'bmask'], {}), '(amask, bmask)\n', (151792, 151806), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((151974, 151992), 'numpy.ma.core.flatten_mask', 'flatten_mask', (['mask'], {}), '(mask)\n', (151986, 151992), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((154958, 154992), 'numpy.zeros', 'np.zeros', (['base.shape'], {'dtype': 'mdtype'}), '(base.shape, dtype=mdtype)\n', (154966, 154992), True, 'import numpy as np\n'), ((155062, 155095), 'numpy.ones', 'np.ones', (['base.shape'], {'dtype': 'mdtype'}), '(base.shape, dtype=mdtype)\n', (155069, 155095), True, 'import numpy as np\n'), ((155196, 155230), 'numpy.zeros', 'np.zeros', (['base.shape'], {'dtype': 'mdtype'}), '(base.shape, dtype=mdtype)\n', (155204, 155230), True, 'import numpy as np\n'), ((155298, 155331), 'numpy.ones', 'np.ones', (['base.shape'], {'dtype': 'mdtype'}), '(base.shape, dtype=mdtype)\n', (155305, 155331), True, 'import numpy as np\n'), ((155461, 155521), 'numpy.array', 'np.array', (['[(x, x, x) for x in [0, 0, 0, 1, 1]]'], {'dtype': 'mdtype'}), '([(x, x, x) for x in [0, 0, 0, 1, 1]], dtype=mdtype)\n', (155469, 155521), True, 'import numpy as np\n'), ((156080, 156134), 'numpy.compat.asbytes_nested', 'asbytes_nested', (["['pi', 'two', 'three', 'four', 'five']"], {}), "(['pi', 'two', 'three', 'four', 'five'])\n", (156094, 156134), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((156604, 156654), 'numpy.compat.asbytes_nested', 'asbytes_nested', (["['pi', 'pi', 'pi', 'four', 'five']"], {}), "(['pi', 'pi', 'pi', 'four', 'five'])\n", (156618, 156654), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((156825, 156868), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base[n].mask', '[1, 1, 0, 0, 1]'], {}), '(base[n].mask, [1, 1, 0, 0, 1])\n', (156837, 156868), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((156881, 156923), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['base[n]._data', 'base._data[n]'], {}), '(base[n]._data, base._data[n])\n', (156893, 156923), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((157107, 157125), 'numpy.ma.core.getmaskarray', 'getmaskarray', (['test'], {}), '(test)\n', (157119, 157125), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((157148, 157218), 'numpy.array', 'np.array', (['[(0, 0), (0, 0), (0, 0)]'], {'dtype': "[('a', '|b1'), ('b', '|b1')]"}), "([(0, 0), (0, 0), (0, 0)], dtype=[('a', '|b1'), ('b', '|b1')])\n", (157156, 157218), True, 'import numpy as np\n'), ((157296, 157314), 'numpy.ma.core.getmaskarray', 'getmaskarray', (['test'], {}), '(test)\n', (157308, 157314), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((157337, 157407), 'numpy.array', 'np.array', (['[(1, 1), (1, 1), (1, 1)]'], {'dtype': "[('a', '|b1'), ('b', '|b1')]"}), "([(1, 1), (1, 1), (1, 1)], dtype=[('a', '|b1'), ('b', '|b1')])\n", (157345, 157407), True, 'import numpy as np\n'), ((159331, 159351), 'numpy.array', 'np.array', (['[1.0, 3.0]'], {}), '([1.0, 3.0])\n', (159339, 159351), True, 'import numpy as np\n'), ((159408, 159428), 'numpy.array', 'np.array', (['[1.0, 4.0]'], {}), '([1.0, 4.0])\n', (159416, 159428), True, 'import numpy as np\n'), ((163677, 163702), 'numpy.ma.__getattribute__', 'np.ma.__getattribute__', (['f'], {}), '(f)\n', (163699, 163702), True, 'import numpy as np\n'), ((164028, 164053), 'numpy.ma.__getattribute__', 'np.ma.__getattribute__', (['f'], {}), '(f)\n', (164050, 164053), True, 'import numpy as np\n'), ((165241, 165249), 'numpy.ma.core.count', 'count', (['a'], {}), '(a)\n', (165246, 165249), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165276, 165292), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(1)'}), '(a, axis=1)\n', (165281, 165292), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165330, 165351), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(0, 1)'}), '(a, axis=(0, 1))\n', (165335, 165351), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165387, 165410), 'numpy.ma.core.count', 'count', (['a'], {'keepdims': '(True)'}), '(a, keepdims=True)\n', (165392, 165410), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165451, 165482), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(1)', 'keepdims': '(True)'}), '(a, axis=1, keepdims=True)\n', (165456, 165482), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165522, 165558), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(0, 1)', 'keepdims': '(True)'}), '(a, axis=(0, 1), keepdims=True)\n', (165527, 165558), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165597, 165614), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(-2)'}), '(a, axis=-2)\n', (165602, 165614), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165836, 165844), 'numpy.ma.core.count', 'count', (['a'], {}), '(a)\n', (165841, 165844), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165871, 165887), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(1)'}), '(a, axis=1)\n', (165876, 165887), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165925, 165946), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(0, 1)'}), '(a, axis=(0, 1))\n', (165930, 165946), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165982, 166005), 'numpy.ma.core.count', 'count', (['a'], {'keepdims': '(True)'}), '(a, keepdims=True)\n', (165987, 166005), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166046, 166077), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(1)', 'keepdims': '(True)'}), '(a, axis=1, keepdims=True)\n', (166051, 166077), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166117, 166153), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(0, 1)', 'keepdims': '(True)'}), '(a, axis=(0, 1), keepdims=True)\n', (166122, 166153), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166192, 166209), 'numpy.ma.core.count', 'count', (['a'], {'axis': '(-2)'}), '(a, axis=-2)\n', (166197, 166209), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166395, 166414), 'numpy.ma.core.count', 'count', (['np.ma.masked'], {}), '(np.ma.masked)\n', (166400, 166414), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166510, 166524), 'numpy.ma.array', 'np.ma.array', (['(1)'], {}), '(1)\n', (166521, 166524), True, 'import numpy as np\n'), ((168100, 168128), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(1 + 1.0j)'], {}), '(1 + 1.0j)\n', (168118, 168128), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((3518, 3534), 'numpy.ma.core.isMaskedArray', 'isMaskedArray', (['x'], {}), '(x)\n', (3531, 3534), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((3968, 3998), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'm1'], {}), '(lambda x, y: x + y, m1)\n', (3974, 3998), False, 'from functools import reduce\n'), ((4511, 4528), 'numpy.ma.core.isMaskedArray', 'isMaskedArray', (['xm'], {}), '(xm)\n', (4524, 4528), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((4555, 4564), 'numpy.ma.core.shape', 'shape', (['xm'], {}), '(xm)\n', (4560, 4564), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((4641, 4670), 'functools.reduce', 'reduce', (['(lambda x, y: x * y)', 's'], {}), '(lambda x, y: x * y, s)\n', (4647, 4670), False, 'from functools import reduce\n'), ((4696, 4705), 'numpy.ma.core.count', 'count', (['xm'], {}), '(xm)\n', (4701, 4705), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((4806, 4823), 'numpy.ma.core.filled', 'filled', (['xm', '(1e+20)'], {}), '(xm, 1e+20)\n', (4812, 4823), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((7877, 7912), 'numpy.may_share_memory', 'np.may_share_memory', (['x.mask', 'y.mask'], {}), '(x.mask, y.mask)\n', (7896, 7912), True, 'import numpy as np\n'), ((11118, 11129), 'numpy.ma.core.getmask', 'getmask', (['x2'], {}), '(x2)\n', (11125, 11129), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11131, 11150), 'numpy.ma.core.array', 'array', (['[0, 1, 0, 0]'], {}), '([0, 1, 0, 0])\n', (11136, 11150), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11235, 11246), 'numpy.ma.core.getmask', 'getmask', (['x3'], {}), '(x3)\n', (11242, 11246), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11248, 11267), 'numpy.ma.core.array', 'array', (['[0, 1, 1, 0]'], {}), '([0, 1, 1, 0])\n', (11253, 11267), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11352, 11363), 'numpy.ma.core.getmask', 'getmask', (['x4'], {}), '(x4)\n', (11359, 11363), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11365, 11384), 'numpy.ma.core.array', 'array', (['[0, 1, 1, 0]'], {}), '([0, 1, 1, 0])\n', (11370, 11384), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11416, 11435), 'numpy.ma.core.array', 'array', (['[1, 2, 3, 4]'], {}), '([1, 2, 3, 4])\n', (11421, 11435), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((11560, 11592), 'numpy.ma.core.array', 'array', (['[0, 0, 0, 1, 0]', 'MaskType'], {}), '([0, 0, 0, 1, 0], MaskType)\n', (11565, 11592), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((12949, 12960), 'numpy.ma.core.getmask', 'getmask', (['x2'], {}), '(x2)\n', (12956, 12960), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((12962, 12994), 'numpy.array', 'np.array', (['[[0, 1, 0], [0, 1, 0]]'], {}), '([[0, 1, 0], [0, 1, 0]])\n', (12970, 12994), True, 'import numpy as np\n'), ((13092, 13108), 'numpy.ma.core.array', 'array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (13097, 13108), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13136, 13150), 'numpy.ma.core.getmask', 'getmask', (['x3[1]'], {}), '(x3[1])\n', (13143, 13150), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13152, 13168), 'numpy.ma.core.array', 'array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (13157, 13168), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13250, 13264), 'numpy.ma.core.getmask', 'getmask', (['x4[1]'], {}), '(x4[1])\n', (13257, 13264), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13266, 13282), 'numpy.ma.core.array', 'array', (['[1, 1, 0]'], {}), '([1, 1, 0])\n', (13271, 13282), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13317, 13333), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {}), '([1, 2, 3])\n', (13322, 13333), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((13359, 13371), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (13368, 13371), True, 'import numpy as np\n'), ((13469, 13501), 'numpy.ma.core.array', 'array', (['[0, 0, 0, 1, 0]', 'MaskType'], {}), '([0, 0, 0, 1, 0], MaskType)\n', (13474, 13501), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((19171, 19179), 'numpy.ma.core.array', 'array', (['(1)'], {}), '(1)\n', (19176, 19179), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((19214, 19222), 'numpy.ma.core.array', 'array', (['(1)'], {}), '(1)\n', (19219, 19222), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((19253, 19267), 'numpy.ma.core.array', 'array', (['[[[1]]]'], {}), '([[[1]]])\n', (19258, 19267), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((19302, 19314), 'numpy.ma.core.array', 'array', (['[[1]]'], {}), '([[1]])\n', (19307, 19314), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((22329, 22352), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(1.0)'], {}), '(1.0)\n', (22347, 22352), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((23718, 23761), 'numpy.array', 'np.array', (['[(0, 0, 1), (1, 0, 0)]'], {'order': '"""F"""'}), "([(0, 0, 1), (1, 0, 0)], order='F')\n", (23726, 23761), True, 'import numpy as np\n'), ((33438, 33450), 'numpy.add', 'np.add', (['x', 'y'], {}), '(x, y)\n', (33444, 33450), True, 'import numpy as np\n'), ((33452, 33463), 'numpy.ma.core.add', 'add', (['xm', 'ym'], {}), '(xm, ym)\n', (33455, 33463), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((33490, 33507), 'numpy.subtract', 'np.subtract', (['x', 'y'], {}), '(x, y)\n', (33501, 33507), True, 'import numpy as np\n'), ((33509, 33525), 'numpy.ma.core.subtract', 'subtract', (['xm', 'ym'], {}), '(xm, ym)\n', (33517, 33525), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((33552, 33569), 'numpy.multiply', 'np.multiply', (['x', 'y'], {}), '(x, y)\n', (33563, 33569), True, 'import numpy as np\n'), ((33571, 33587), 'numpy.ma.core.multiply', 'multiply', (['xm', 'ym'], {}), '(xm, ym)\n', (33579, 33587), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((33614, 33629), 'numpy.divide', 'np.divide', (['x', 'y'], {}), '(x, y)\n', (33623, 33629), True, 'import numpy as np\n'), ((33631, 33645), 'numpy.ma.core.divide', 'divide', (['xm', 'ym'], {}), '(xm, ym)\n', (33637, 33645), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((35034, 35049), 'numpy.ma.core.maximum', 'maximum', (['xm', 'xm'], {}), '(xm, xm)\n', (35041, 35049), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((35080, 35095), 'numpy.ma.core.minimum', 'minimum', (['xm', 'xm'], {}), '(xm, xm)\n', (35087, 35095), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36801, 36807), 'numpy.ma.core.abs', 'abs', (['x'], {}), '(x)\n', (36804, 36807), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36848, 36854), 'numpy.ma.core.abs', 'abs', (['x'], {}), '(x)\n', (36851, 36854), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((36896, 36902), 'numpy.ma.core.abs', 'abs', (['x'], {}), '(x)\n', (36899, 36902), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((38293, 38305), 'numpy.ma.core.getmask', 'getmask', (['res'], {}), '(res)\n', (38300, 38305), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39149, 39159), 'numpy.ma.core.less', 'less', (['x', 'y'], {}), '(x, y)\n', (39153, 39159), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39210, 39223), 'numpy.ma.core.greater', 'greater', (['x', 'y'], {}), '(x, y)\n', (39217, 39223), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39248, 39258), 'numpy.ma.core.minimum', 'minimum', (['x'], {}), '(x)\n', (39255, 39258), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39281, 39291), 'numpy.ma.core.maximum', 'maximum', (['x'], {}), '(x)\n', (39288, 39291), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((39311, 39320), 'numpy.ma.core.arange', 'arange', (['(4)'], {}), '(4)\n', (39317, 39320), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((40396, 40414), 'numpy.random.rand', 'np.random.rand', (['(12)'], {}), '(12)\n', (40410, 40414), True, 'import numpy as np\n'), ((42297, 42305), 'numpy.ma.core.array', 'array', (['(4)'], {}), '(4)\n', (42302, 42305), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42344, 42352), 'numpy.ma.core.array', 'array', (['(4)'], {}), '(4)\n', (42349, 42352), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42447, 42460), 'numpy.ma.core.filled', 'filled', (['xm', '(0)'], {}), '(xm, 0)\n', (42453, 42460), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42684, 42697), 'numpy.ma.core.filled', 'filled', (['xm', '(1)'], {}), '(xm, 1)\n', (42690, 42697), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42848, 42873), 'numpy.concatenate', 'np.concatenate', (['(x, y)', '(1)'], {}), '((x, y), 1)\n', (42862, 42873), True, 'import numpy as np\n'), ((42875, 42899), 'numpy.ma.core.concatenate', 'concatenate', (['(xm, ym)', '(1)'], {}), '((xm, ym), 1)\n', (42886, 42899), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42926, 42945), 'numpy.add.reduce', 'np.add.reduce', (['x', '(1)'], {}), '(x, 1)\n', (42939, 42945), True, 'import numpy as np\n'), ((42947, 42963), 'numpy.ma.core.add.reduce', 'add.reduce', (['x', '(1)'], {}), '(x, 1)\n', (42957, 42963), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((42990, 43002), 'numpy.sum', 'np.sum', (['x', '(1)'], {}), '(x, 1)\n', (42996, 43002), True, 'import numpy as np\n'), ((43004, 43013), 'numpy.ma.core.sum', 'sum', (['x', '(1)'], {}), '(x, 1)\n', (43007, 43013), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((43040, 43056), 'numpy.product', 'np.product', (['x', '(1)'], {}), '(x, 1)\n', (43050, 43056), True, 'import numpy as np\n'), ((43058, 43071), 'numpy.ma.core.product', 'product', (['x', '(1)'], {}), '(x, 1)\n', (43065, 43071), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47069, 47094), 'numpy.ma.core.mask_or', 'mask_or', (['xm.mask', 'ym.mask'], {}), '(xm.mask, ym.mask)\n', (47076, 47094), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47519, 47531), 'numpy.ma.core.filled', 'filled', (['x', '(0)'], {}), '(x, 0)\n', (47525, 47531), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47533, 47545), 'numpy.ma.core.filled', 'filled', (['y', '(0)'], {}), '(y, 0)\n', (47539, 47545), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47612, 47624), 'numpy.ma.core.filled', 'filled', (['x', '(0)'], {}), '(x, 0)\n', (47618, 47624), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((47626, 47638), 'numpy.ma.core.filled', 'filled', (['y', '(0)'], {}), '(y, 0)\n', (47632, 47638), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((49212, 49228), 'numpy.zeros', 'np.zeros', (['(2, 2)'], {}), '((2, 2))\n', (49220, 49228), True, 'import numpy as np\n'), ((52105, 52114), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (52111, 52114), True, 'import numpy as np\n'), ((58333, 58342), 'numpy.eye', 'np.eye', (['(2)'], {}), '(2)\n', (58339, 58342), True, 'import numpy as np\n'), ((60474, 60488), 'numpy.compat.asbytes', 'asbytes', (['"""???"""'], {}), "('???')\n", (60481, 60488), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((60677, 60698), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0)'], {}), '(0)\n', (60695, 60698), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((60735, 60758), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0.0)'], {}), '(0.0)\n', (60753, 60758), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((61119, 61133), 'numpy.compat.asbytes', 'asbytes', (['"""???"""'], {}), "('???')\n", (61126, 61133), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((61776, 61790), 'numpy.compat.asbytes', 'asbytes', (['"""???"""'], {}), "('???')\n", (61783, 61790), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((62124, 62138), 'numpy.compat.asbytes', 'asbytes', (['"""???"""'], {}), "('???')\n", (62131, 62138), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((64061, 64075), 'numpy.compat.asbytes', 'asbytes', (['"""999"""'], {}), "('999')\n", (64068, 64075), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((64260, 64274), 'numpy.compat.asbytes', 'asbytes', (['"""???"""'], {}), "('???')\n", (64267, 64274), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((64456, 64480), 'numpy.asarray', 'np.asarray', (['x.fill_value'], {}), '(x.fill_value)\n', (64466, 64480), True, 'import numpy as np\n'), ((64823, 64844), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0)'], {}), '(0)\n', (64841, 64844), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((64874, 64897), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['"""0"""'], {}), "('0')\n", (64892, 64897), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((64927, 64950), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0.0)'], {}), '(0.0)\n', (64945, 64950), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((65335, 65372), 'numpy.array', 'np.array', (['(0,)'], {'dtype': "[('f0', float)]"}), "((0,), dtype=[('f0', float)])\n", (65343, 65372), True, 'import numpy as np\n'), ((65828, 65874), 'numpy.array', 'np.array', (['(0, 0, 0)'], {'dtype': '"""int, float, float"""'}), "((0, 0, 0), dtype='int, float, float')\n", (65836, 65874), True, 'import numpy as np\n'), ((68605, 68626), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0)'], {}), '(0)\n', (68623, 68626), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((68925, 68943), 'numpy.dtype', 'np.dtype', (['[adtype]'], {}), '([adtype])\n', (68933, 68943), True, 'import numpy as np\n'), ((73864, 73882), 'numpy.ma.core.alltrue', 'alltrue', (['a'], {'axis': '(0)'}), '(a, axis=0)\n', (73871, 73882), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((74138, 74151), 'numpy.ma.core.arange', 'arange', (['(1)', '(13)'], {}), '(1, 13)\n', (74144, 74151), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((74718, 74728), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (74725, 74728), True, 'import numpy as np\n'), ((77379, 77390), 'numpy.dtype', 'np.dtype', (['_'], {}), '(_)\n', (77387, 77390), True, 'import numpy as np\n'), ((80277, 80295), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (80284, 80295), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((86336, 86372), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (86359, 86372), False, 'import warnings\n'), ((86395, 86428), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (86418, 86428), False, 'import warnings\n'), ((86868, 86904), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (86891, 86904), False, 'import warnings\n'), ((86927, 86960), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (86950, 86960), False, 'import warnings\n'), ((87076, 87095), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (87082, 87095), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((87190, 87212), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y + a)'], {}), '(x, y + a)\n', (87202, 87212), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((87229, 87252), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y + a)'], {}), '(xm, y + a)\n', (87241, 87252), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((87521, 87557), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (87544, 87557), False, 'import warnings\n'), ((87580, 87613), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (87603, 87613), False, 'import warnings\n'), ((88028, 88064), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (88051, 88064), False, 'import warnings\n'), ((88087, 88120), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (88110, 88120), False, 'import warnings\n'), ((88236, 88255), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (88242, 88255), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((88350, 88372), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y - a)'], {}), '(x, y - a)\n', (88362, 88372), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((88389, 88412), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y - a)'], {}), '(xm, y - a)\n', (88401, 88412), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((88686, 88722), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (88709, 88722), False, 'import warnings\n'), ((88745, 88778), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (88768, 88778), False, 'import warnings\n'), ((89198, 89234), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (89221, 89234), False, 'import warnings\n'), ((89257, 89290), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (89280, 89290), False, 'import warnings\n'), ((89406, 89425), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (89412, 89425), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((89520, 89542), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y * a)'], {}), '(x, y * a)\n', (89532, 89542), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((89559, 89582), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y * a)'], {}), '(xm, y * a)\n', (89571, 89582), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((89850, 89886), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (89873, 89886), False, 'import warnings\n'), ((89909, 89942), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (89932, 89942), False, 'import warnings\n'), ((90207, 90225), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', 'y'], {}), '(x, y)\n', (90219, 90225), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((90242, 90261), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', 'y'], {}), '(xm, y)\n', (90254, 90261), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((90470, 90506), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (90493, 90506), False, 'import warnings\n'), ((90529, 90562), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (90552, 90562), False, 'import warnings\n'), ((90678, 90697), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (90684, 90697), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((90794, 90817), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y // a)'], {}), '(x, y // a)\n', (90806, 90817), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((90834, 90858), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y // a)'], {}), '(xm, y // a)\n', (90846, 90858), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((91200, 91236), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (91223, 91236), False, 'import warnings\n'), ((91259, 91292), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (91282, 91292), False, 'import warnings\n'), ((92732, 92768), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (92755, 92768), False, 'import warnings\n'), ((92791, 92824), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (92814, 92824), False, 'import warnings\n'), ((92940, 92959), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (92946, 92959), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((94394, 94430), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {'record': '(True)'}), '(record=True)\n', (94417, 94430), False, 'import warnings\n'), ((94453, 94486), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""always"""'], {}), "('always')\n", (94476, 94486), False, 'import warnings\n'), ((94544, 94585), 'numpy.ma.core.array', 'array', (['[1, 2, 3]'], {'mask': '[0, 0, 1]', 'dtype': 't'}), '([1, 2, 3], mask=[0, 0, 1], dtype=t)\n', (94549, 94585), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((94640, 94686), 'numpy.ma.core.array', 'array', (['[1, 2 ** 2, 3]'], {'mask': '[0, 0, 1]', 'dtype': 't'}), '([1, 2 ** 2, 3], mask=[0, 0, 1], dtype=t)\n', (94645, 94686), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((94703, 94735), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.data', 'xx_r.data'], {}), '(xx.data, xx_r.data)\n', (94715, 94735), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((94752, 94784), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xx.mask', 'xx_r.mask'], {}), '(xx.mask, xx_r.mask)\n', (94764, 94784), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((94866, 94897), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.data', 'xx_r.data'], {}), '(x.data, xx_r.data)\n', (94878, 94897), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((94914, 94945), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x.mask', 'xx_r.mask'], {}), '(x.mask, xx_r.mask)\n', (94926, 94945), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((97356, 97374), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (97370, 97374), True, 'import numpy as np\n'), ((97504, 97518), 'numpy.ma.core.allclose', 'allclose', (['a', 'b'], {}), '(a, b)\n', (97512, 97518), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((97754, 97788), 'numpy.ma.core.allclose', 'allclose', (['a', 'b'], {'masked_equal': '(False)'}), '(a, b, masked_equal=False)\n', (97762, 97788), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((99771, 99802), 'numpy.matrix', 'np.matrix', (['[False, False, True]'], {}), '([False, False, True])\n', (99780, 99802), True, 'import numpy as np\n'), ((99909, 99938), 'numpy.matrix', 'np.matrix', (['[True, True, True]'], {}), '([True, True, True])\n', (99918, 99938), True, 'import numpy as np\n'), ((100128, 100160), 'numpy.matrix', 'np.matrix', (['[False, False, False]'], {}), '([False, False, False])\n', (100137, 100160), True, 'import numpy as np\n'), ((100270, 100300), 'numpy.matrix', 'np.matrix', (['[True, True, False]'], {}), '([True, True, False])\n', (100279, 100300), True, 'import numpy as np\n'), ((104889, 104924), 'numpy.may_share_memory', 'np.may_share_memory', (['a.mask', 'b.mask'], {}), '(a.mask, b.mask)\n', (104908, 104924), True, 'import numpy as np\n'), ((114153, 114169), 'numpy.ma.core.array', 'array', (['x'], {'mask': 'm'}), '(x, mask=m)\n', (114158, 114169), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((115360, 115372), 'numpy.arange', 'np.arange', (['(3)'], {}), '(3)\n', (115369, 115372), True, 'import numpy as np\n'), ((115383, 115395), 'numpy.arange', 'np.arange', (['(5)'], {}), '(5)\n', (115392, 115395), True, 'import numpy as np\n'), ((127489, 127507), 'numpy.sqrt', 'np.sqrt', (['mXvar0[k]'], {}), '(mXvar0[k])\n', (127496, 127507), True, 'import numpy as np\n'), ((128074, 128099), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (128097, 128099), False, 'import warnings\n'), ((128117, 128148), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (128138, 128148), False, 'import warnings\n'), ((128338, 128363), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (128361, 128363), False, 'import warnings\n'), ((128381, 128412), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (128402, 128412), False, 'import warnings\n'), ((128474, 128488), 'numpy.isnan', 'np.isnan', (['nout'], {}), '(nout)\n', (128482, 128488), True, 'import numpy as np\n'), ((129100, 129114), 'numpy.isnan', 'np.isnan', (['nout'], {}), '(nout)\n', (129108, 129114), True, 'import numpy as np\n'), ((129662, 129671), 'numpy.ma.core.arange', 'arange', (['(9)'], {}), '(9)\n', (129668, 129671), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((133012, 133030), 'numpy.sqrt', 'np.sqrt', (['mXvar0[k]'], {}), '(mXvar0[k])\n', (133019, 133030), True, 'import numpy as np\n'), ((134378, 134391), 'numpy.ma.core.greater', 'greater', (['x', '(2)'], {}), '(x, 2)\n', (134385, 134391), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134453, 134472), 'numpy.ma.core.greater_equal', 'greater_equal', (['x', '(2)'], {}), '(x, 2)\n', (134466, 134472), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134561, 134571), 'numpy.ma.core.less', 'less', (['x', '(2)'], {}), '(x, 2)\n', (134565, 134571), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134630, 134646), 'numpy.ma.core.less_equal', 'less_equal', (['x', '(2)'], {}), '(x, 2)\n', (134640, 134646), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134732, 134747), 'numpy.ma.core.not_equal', 'not_equal', (['x', '(2)'], {}), '(x, 2)\n', (134741, 134747), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134811, 134822), 'numpy.ma.core.equal', 'equal', (['x', '(2)'], {}), '(x, 2)\n', (134816, 134822), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((134882, 134897), 'numpy.ma.core.not_equal', 'not_equal', (['x', '(2)'], {}), '(x, 2)\n', (134891, 134897), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((136014, 136026), 'numpy.zeros', 'np.zeros', (['(10)'], {}), '(10)\n', (136022, 136026), True, 'import numpy as np\n'), ((136028, 136039), 'numpy.ones', 'np.ones', (['(10)'], {}), '(10)\n', (136035, 136039), True, 'import numpy as np\n'), ((139381, 139397), 'numpy.ma.core.power', 'power', (['x', 'masked'], {}), '(x, masked)\n', (139386, 139397), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((144073, 144084), 'numpy.ma.core.getmask', 'getmask', (['zm'], {}), '(zm)\n', (144080, 144084), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((146641, 146660), 'numpy.ma.core.empty', 'empty', (['(4)'], {'dtype': 'int'}), '(4, dtype=int)\n', (146646, 146660), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((157531, 157544), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (157540, 157544), True, 'import numpy as np\n'), ((157546, 157564), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (157560, 157564), True, 'import numpy as np\n'), ((160451, 160464), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (160460, 160464), True, 'import numpy as np\n'), ((160466, 160484), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (160480, 160484), True, 'import numpy as np\n'), ((163381, 163396), 'numpy.arange', 'np.arange', (['(24.0)'], {}), '(24.0)\n', (163390, 163396), True, 'import numpy as np\n'), ((163426, 163450), 'numpy.zeros', 'np.zeros', (['(24)'], {'dtype': 'bool'}), '(24, dtype=bool)\n', (163434, 163450), True, 'import numpy as np\n'), ((165073, 165088), 'numpy.arange', 'np.arange', (['(24.0)'], {}), '(24.0)\n', (165082, 165088), True, 'import numpy as np\n'), ((165118, 165142), 'numpy.zeros', 'np.zeros', (['(24)'], {'dtype': 'bool'}), '(24, dtype=bool)\n', (165126, 165142), True, 'import numpy as np\n'), ((165296, 165308), 'numpy.ma.core.ones', 'ones', (['(2, 4)'], {}), '((2, 4))\n', (165300, 165308), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165354, 165364), 'numpy.ma.core.ones', 'ones', (['(4,)'], {}), '((4,))\n', (165358, 165364), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165415, 165430), 'numpy.ma.core.ones', 'ones', (['(1, 1, 1)'], {}), '((1, 1, 1))\n', (165419, 165430), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165486, 165501), 'numpy.ma.core.ones', 'ones', (['(2, 1, 4)'], {}), '((2, 1, 4))\n', (165490, 165501), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165561, 165576), 'numpy.ma.core.ones', 'ones', (['(1, 1, 4)'], {}), '((1, 1, 4))\n', (165565, 165576), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165618, 165630), 'numpy.ma.core.ones', 'ones', (['(2, 4)'], {}), '((2, 4))\n', (165622, 165630), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165891, 165903), 'numpy.ma.core.ones', 'ones', (['(2, 4)'], {}), '((2, 4))\n', (165895, 165903), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((165949, 165959), 'numpy.ma.core.ones', 'ones', (['(4,)'], {}), '((4,))\n', (165953, 165959), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166010, 166025), 'numpy.ma.core.ones', 'ones', (['(1, 1, 1)'], {}), '((1, 1, 1))\n', (166014, 166025), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166081, 166096), 'numpy.ma.core.ones', 'ones', (['(2, 1, 4)'], {}), '((2, 1, 4))\n', (166085, 166096), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166156, 166171), 'numpy.ma.core.ones', 'ones', (['(1, 1, 4)'], {}), '((1, 1, 4))\n', (166160, 166171), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((166213, 166225), 'numpy.ma.core.ones', 'ones', (['(2, 4)'], {}), '((2, 4))\n', (166217, 166225), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((4465, 4481), 'numpy.ma.core.isMaskedArray', 'isMaskedArray', (['x'], {}), '(x)\n', (4478, 4481), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((4717, 4747), 'functools.reduce', 'reduce', (['(lambda x, y: x + y)', 'm1'], {}), '(lambda x, y: x + y, m1)\n', (4723, 4747), False, 'from functools import reduce\n'), ((6278, 6296), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (6292, 6296), True, 'import numpy as np\n'), ((6335, 6348), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (6344, 6348), True, 'import numpy as np\n'), ((13076, 13087), 'numpy.ma.core.getmask', 'getmask', (['x3'], {}), '(x3)\n', (13083, 13087), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((14741, 14751), 'numpy.ma.core.filled', 'filled', (['y3'], {}), '(y3)\n', (14747, 14751), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20149, 20161), 'numpy.ma.core.conjugate', 'conjugate', (['z'], {}), '(z)\n', (20158, 20161), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20337, 20361), 'numpy.ma.core.where', 'where', (['c', 'masked', 'masked'], {}), '(c, masked, masked)\n', (20342, 20361), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((20391, 20415), 'numpy.ma.core.where', 'where', (['c', 'masked', 'masked'], {}), '(c, masked, masked)\n', (20396, 20415), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((33339, 33345), 'numpy.ma.core.abs', 'abs', (['x'], {}), '(x)\n', (33342, 33345), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((33354, 33361), 'numpy.ma.core.abs', 'abs', (['xm'], {}), '(xm)\n', (33357, 33361), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((34919, 34927), 'numpy.ma.core.array', 'array', (['(0)'], {}), '(0)\n', (34924, 34927), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((48326, 48354), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(10)', '(12)'], {}), '(0, 10, 12)\n', (48343, 48354), True, 'import numpy as np\n'), ((60802, 60825), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['"""0"""'], {}), "('0')\n", (60820, 60825), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((76036, 76061), 'numpy.ma.core.multiply.outer', 'multiply.outer', (['a', 'me_too'], {}), '(a, me_too)\n', (76050, 76061), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((87291, 87309), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (87298, 87309), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((88451, 88469), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (88458, 88469), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((89621, 89639), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (89628, 89639), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((90030, 90049), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (90036, 90049), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((90078, 90097), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (90084, 90097), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((91380, 91399), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (91386, 91399), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((91428, 91447), 'numpy.ma.core.arange', 'arange', (['(10)'], {'dtype': 't'}), '(10, dtype=t)\n', (91434, 91447), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((92071, 92089), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', 'y'], {}), '(x, y)\n', (92083, 92089), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((92265, 92284), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', 'y'], {}), '(xm, y)\n', (92277, 92284), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((93573, 93595), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['x', '(y / a)'], {}), '(x, y / a)\n', (93585, 93595), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((93768, 93791), 'numpy.ma.testutils.assert_equal', 'assert_equal', (['xm', '(y / a)'], {}), '(xm, y / a)\n', (93780, 93791), False, 'from numpy.ma.testutils import assert_, assert_array_equal, assert_equal, assert_almost_equal, assert_equal_records, fail_if_equal, assert_not_equal, assert_mask_equal\n'), ((98019, 98036), 'numpy.iinfo', 'np.iinfo', (['np.int_'], {}), '(np.int_)\n', (98027, 98036), True, 'import numpy as np\n'), ((117254, 117268), 'numpy.compat.asbytes', 'asbytes', (['"""one"""'], {}), "('one')\n", (117261, 117268), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((117302, 117316), 'numpy.compat.asbytes', 'asbytes', (['"""two"""'], {}), "('two')\n", (117309, 117316), False, 'from numpy.compat import asbytes, asbytes_nested\n'), ((122697, 122725), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(10)', '(12)'], {}), '(0, 10, 12)\n', (122714, 122725), True, 'import numpy as np\n'), ((136815, 136859), 'numpy.ma.core.array', 'array', (['[2, 2, 1, 2, 1]'], {'mask': '[1, 0, 0, 0, 0]'}), '([2, 2, 1, 2, 1], mask=[1, 0, 0, 0, 0])\n', (136820, 136859), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((137840, 137868), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(10)', '(12)'], {}), '(0, 10, 12)\n', (137857, 137868), True, 'import numpy as np\n'), ((158308, 158326), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (158322, 158326), True, 'import numpy as np\n'), ((158328, 158341), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (158337, 158341), True, 'import numpy as np\n'), ((19509, 19529), 'numpy.ma.core.array', 'array', (['[1]'], {'mask': '[1]'}), '([1], mask=[1])\n', (19514, 19529), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((21778, 21799), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0)'], {}), '(0)\n', (21796, 21799), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((21833, 21856), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['"""0"""'], {}), "('0')\n", (21851, 21856), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((21890, 21913), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0.0)'], {}), '(0.0)\n', (21908, 21913), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((65163, 65186), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0.0)'], {}), '(0.0)\n', (65181, 65186), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((65529, 65550), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0)'], {}), '(0)\n', (65547, 65550), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((65580, 65603), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0.0)'], {}), '(0.0)\n', (65598, 65603), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((65632, 65655), 'numpy.ma.core.default_fill_value', 'default_fill_value', (['(0.0)'], {}), '(0.0)\n', (65650, 65655), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((90946, 90964), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (90953, 90964), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n'), ((118834, 118847), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (118843, 118847), True, 'import numpy as np\n'), ((118972, 118990), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (118986, 118990), True, 'import numpy as np\n'), ((119305, 119318), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (119314, 119318), True, 'import numpy as np\n'), ((119375, 119393), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (119389, 119393), True, 'import numpy as np\n'), ((119450, 119468), 'numpy.random.rand', 'np.random.rand', (['(10)'], {}), '(10)\n', (119464, 119468), True, 'import numpy as np\n'), ((164825, 164838), 'numpy.arange', 'np.arange', (['(24)'], {}), '(24)\n', (164834, 164838), True, 'import numpy as np\n'), ((93891, 93909), 'numpy.ma.core.mask_or', 'mask_or', (['m', 'a.mask'], {}), '(m, a.mask)\n', (93898, 93909), False, 'from numpy.ma.core import MAError, MaskError, MaskType, MaskedArray, abs, absolute, add, all, allclose, allequal, alltrue, angle, anom, arange, arccos, arccosh, arctan2, arcsin, arctan, argsort, array, asarray, choose, concatenate, conjugate, cos, cosh, count, default_fill_value, diag, divide, empty, empty_like, equal, exp, flatten_mask, filled, fix_invalid, flatten_structured_array, fromflex, getmask, getmaskarray, greater, greater_equal, identity, inner, isMaskedArray, less, less_equal, log, log10, make_mask, make_mask_descr, mask_or, masked, masked_array, masked_equal, masked_greater, masked_greater_equal, masked_inside, masked_less, masked_less_equal, masked_not_equal, masked_outside, masked_print_option, masked_values, masked_where, max, maximum, maximum_fill_value, min, minimum, minimum_fill_value, mod, multiply, mvoid, nomask, not_equal, ones, outer, power, product, put, putmask, ravel, repeat, reshape, resize, shape, sin, sinh, sometrue, sort, sqrt, subtract, sum, take, tan, tanh, transpose, where, zeros\n')]
|
import unittest
from align.jaccard import *
from align.roc import *
import numpy as np
from PIL import Image
class JaccardIndexTest(unittest.TestCase):
def setUp(self):
self.y_true = np.ones((10, 3, 100, 100))
self.y_pred = np.zeros((10, 3, 100, 100))
self.y_pred[1] = np.ones((3,100,100))
def test_jaccard(self):
scores = jaccard_index(self.y_true, self.y_pred)
assert scores.mean() == 0.1
precision_recalls = precision_recall(self.y_true, self.y_pred, iou=0.05)
print ("[email protected]:{}".format(compute_ap(precision_recalls)))
print("[email protected]:0.95:0.05={}".format(compute_map(self.y_true, self.y_pred)))
def test_jaccard_2(self):
y_true = np.array(Image.open('data/label.png').convert('L'), dtype=np.float32)[np.newaxis,...] / 255.
y_pred = np.array(Image.open('data/generation.png').convert('L'), dtype=np.float32)[np.newaxis,...] / 255.
print('Jaccard Index: {}'.format(jaccard_index(y_true, y_pred)))
print("[email protected]:0.95:0.05={}".format(compute_map(y_true, y_pred)))
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"numpy.zeros",
"numpy.ones",
"PIL.Image.open"
] |
[((1114, 1129), 'unittest.main', 'unittest.main', ([], {}), '()\n', (1127, 1129), False, 'import unittest\n'), ((197, 223), 'numpy.ones', 'np.ones', (['(10, 3, 100, 100)'], {}), '((10, 3, 100, 100))\n', (204, 223), True, 'import numpy as np\n'), ((246, 273), 'numpy.zeros', 'np.zeros', (['(10, 3, 100, 100)'], {}), '((10, 3, 100, 100))\n', (254, 273), True, 'import numpy as np\n'), ((299, 321), 'numpy.ones', 'np.ones', (['(3, 100, 100)'], {}), '((3, 100, 100))\n', (306, 321), True, 'import numpy as np\n'), ((736, 764), 'PIL.Image.open', 'Image.open', (['"""data/label.png"""'], {}), "('data/label.png')\n", (746, 764), False, 'from PIL import Image\n'), ((846, 879), 'PIL.Image.open', 'Image.open', (['"""data/generation.png"""'], {}), "('data/generation.png')\n", (856, 879), False, 'from PIL import Image\n')]
|
import theano
import theano.tensor as T
import numpy as np
from itertools import chain, izip
from learntools.libs.logger import log_me
from learntools.libs.auc import auc
from learntools.model.mlp import ConvolutionalMLP
from learntools.model.theano_utils import make_shared
from learntools.model import Model, gen_batches_by_size
from learntools.model.math import sigmoid
class ConvEmotiv(Model):
@log_me('...building ConvEmotiv')
def __init__(self, prepared_data, batch_size=30, L1_reg=0., L2_reg=0.,
field_width=20, ds_factor=2, rng_seed=42, dropout_p=0.5,
learning_rate=0.02, **kwargs):
"""
Args:
prepared_data : (Dataset, [int], [int])
a tuple that holds the data to be used, the row indices of the
training set, and the row indices of the validation set
batch_size : int
The size of the batches used to train
"""
# 1: Organize data into batches
ds, train_idx, valid_idx = prepared_data
input_size = ds.get_data('eeg').shape[1]
self._xs = make_shared(ds.get_data('eeg'), name='eeg')
self._ys = make_shared(ds.get_data('condition'), to_int=True, name='condition')
self.train_batches = gen_batches_by_size(train_idx, batch_size)
self.valid_batches = gen_batches_by_size(valid_idx, batch_size)
# 2: Connect the model
rng = np.random.RandomState(rng_seed)
t_dropout = T.scalar('dropout')
classifier = ConvolutionalMLP(rng=rng,
n_in=input_size,
size=[input_size],
n_out=2,
field_width=field_width,
ds_factor=ds_factor,
dropout=t_dropout)
input_idxs = T.ivector('input_idxs')
classifier_input = self._xs[input_idxs]
classifier_input.name = 'classifier_input'
pY = classifier.instance(classifier_input)
true_y = self._ys[input_idxs]
true_y.name = 'true_y'
# 3: Create theano functions
loss = -T.mean(T.log(pY)[T.arange(input_idxs.shape[0]), true_y])
loss.name = 'loss'
subnets = [classifier]
cost = (
loss
+ L1_reg * sum([net.L1 for net in subnets])
+ L2_reg * sum([net.L2_sqr for net in subnets])
)
cost.name = 'overall_cost'
# compute parameter updates
training_updates = []
params = list(chain.from_iterable(net.params for net in subnets))
deltas = [T.grad(cost, param) for param in params]
update_parameters = [(param, param - learning_rate * delta)
for param, delta in izip(params, deltas)]
training_updates += update_parameters
common_args = {
'inputs': [input_idxs],
'outputs': [loss, pY[:, 1] - pY[:, 0], input_idxs],
'allow_input_downcast': True,
}
self._tf_valid = theano.function(givens={t_dropout: 0.}, **common_args)
self._tf_train = theano.function(
updates=training_updates,
givens={t_dropout: dropout_p},
**common_args)
def evaluate(self, idxs, pred):
y = self._ys.owner.inputs[0].get_value(borrow=True)[idxs]
return auc(y[:len(pred)], pred, pos_label=1)
def validate(self, idxs, **kwargs):
res = self._tf_valid(idxs)
return res[:3]
def train(self, idxs, **kwargs):
res = self._tf_train(idxs)
return res[:3]
|
[
"itertools.chain.from_iterable",
"theano.tensor.log",
"learntools.model.mlp.ConvolutionalMLP",
"learntools.libs.logger.log_me",
"theano.function",
"learntools.model.gen_batches_by_size",
"theano.tensor.ivector",
"numpy.random.RandomState",
"theano.tensor.grad",
"itertools.izip",
"theano.tensor.arange",
"theano.tensor.scalar"
] |
[((407, 439), 'learntools.libs.logger.log_me', 'log_me', (['"""...building ConvEmotiv"""'], {}), "('...building ConvEmotiv')\n", (413, 439), False, 'from learntools.libs.logger import log_me\n'), ((1281, 1323), 'learntools.model.gen_batches_by_size', 'gen_batches_by_size', (['train_idx', 'batch_size'], {}), '(train_idx, batch_size)\n', (1300, 1323), False, 'from learntools.model import Model, gen_batches_by_size\n'), ((1353, 1395), 'learntools.model.gen_batches_by_size', 'gen_batches_by_size', (['valid_idx', 'batch_size'], {}), '(valid_idx, batch_size)\n', (1372, 1395), False, 'from learntools.model import Model, gen_batches_by_size\n'), ((1442, 1473), 'numpy.random.RandomState', 'np.random.RandomState', (['rng_seed'], {}), '(rng_seed)\n', (1463, 1473), True, 'import numpy as np\n'), ((1494, 1513), 'theano.tensor.scalar', 'T.scalar', (['"""dropout"""'], {}), "('dropout')\n", (1502, 1513), True, 'import theano.tensor as T\n'), ((1536, 1675), 'learntools.model.mlp.ConvolutionalMLP', 'ConvolutionalMLP', ([], {'rng': 'rng', 'n_in': 'input_size', 'size': '[input_size]', 'n_out': '(2)', 'field_width': 'field_width', 'ds_factor': 'ds_factor', 'dropout': 't_dropout'}), '(rng=rng, n_in=input_size, size=[input_size], n_out=2,\n field_width=field_width, ds_factor=ds_factor, dropout=t_dropout)\n', (1552, 1675), False, 'from learntools.model.mlp import ConvolutionalMLP\n'), ((1844, 1867), 'theano.tensor.ivector', 'T.ivector', (['"""input_idxs"""'], {}), "('input_idxs')\n", (1853, 1867), True, 'import theano.tensor as T\n'), ((3038, 3093), 'theano.function', 'theano.function', ([], {'givens': '{t_dropout: 0.0}'}), '(givens={t_dropout: 0.0}, **common_args)\n', (3053, 3093), False, 'import theano\n'), ((3118, 3210), 'theano.function', 'theano.function', ([], {'updates': 'training_updates', 'givens': '{t_dropout: dropout_p}'}), '(updates=training_updates, givens={t_dropout: dropout_p}, **\n common_args)\n', (3133, 3210), False, 'import theano\n'), ((2540, 2590), 'itertools.chain.from_iterable', 'chain.from_iterable', (['(net.params for net in subnets)'], {}), '(net.params for net in subnets)\n', (2559, 2590), False, 'from itertools import chain, izip\n'), ((2610, 2629), 'theano.tensor.grad', 'T.grad', (['cost', 'param'], {}), '(cost, param)\n', (2616, 2629), True, 'import theano.tensor as T\n'), ((2768, 2788), 'itertools.izip', 'izip', (['params', 'deltas'], {}), '(params, deltas)\n', (2772, 2788), False, 'from itertools import chain, izip\n'), ((2148, 2157), 'theano.tensor.log', 'T.log', (['pY'], {}), '(pY)\n', (2153, 2157), True, 'import theano.tensor as T\n'), ((2158, 2187), 'theano.tensor.arange', 'T.arange', (['input_idxs.shape[0]'], {}), '(input_idxs.shape[0])\n', (2166, 2187), True, 'import theano.tensor as T\n')]
|
from __future__ import print_function, division
"""
@ About :
@ Author : <NAME>
@ ref. : https://labrosa.ee.columbia.edu/matlab/rastamat/
"""
import warnings
import librosa
import scipy.fftpack as fft
import numpy as np
import spectrum
from scipy import signal
def specgram(x, nfft=256, fs=8000, window=np.array([]), overlap=None):
"""
input:
x - input audio_array
nfft - # fft points [default : 256]
fs - sampling frequency [default : 8000]
window - window to FFT analysis [default : hanning(nfft)]
overlap - overlap for FFT analysis ( overlap = window_length - hop_length ) [default : nfft/2]
"""
nsamples = x.shape[0]
if type(window) == int:
window = np.hanning(window)
if overlap == None:
overlap = np.ceil(nfft/2).astype(int)
if window.shape[0] == 0:
window = np.hanning(nfft);
if (nsamples <= nfft):
raise AssertionError("expected nframes > nfft.")
# compute window offsets
win_size = window.shape[0];
if win_size > nfft:
nfft = win_size
warnings.warn("fft points adjusted to win_size as win_size > nfft")
win_step = win_size - overlap
# build matrix of windowed data slices
offset = list(range(0,(nsamples-win_size), win_step))
npad = (nsamples - offset[-1])+1
if npad > 0:
x = np.concatenate((x,np.zeros(npad)))
S = []
for i in offset:
S.append((x[i:i+win_size]*window)[np.newaxis,:])
S=np.concatenate(S)
S = np.fft.fft(S,nfft)
# extract the positive frequency components
ret_n = int(nfft/2);
if nfft%2==1:
ret_n = int((nfft+1)/2);
S = S[:, 0:ret_n];
f = np.array(range(ret_n))*fs/nfft;
t = np.array(offset)/fs;
return (S, f, t)
def powspec(x, fs = 8000,
winlen_in_sec = 0.025, hoplen_in_sec = 0.010,
dither = 0
):
"""
pow_spec, e = powspec(x, sr, winlen_in_sec, hoplen_in_sec, dither)
where x : audio array
sr : sampling rate
winlen_in_sec : window length for audio analysis ()
compute the powerspectrum and frame energy of the input signal.
basically outputs a power spectrogram
each column represents a power spectrum for a given frame
each row represents a frequency
"""
# sec2sample
win_length = int(np.round(winlen_in_sec * fs))
hop_length = int(np.round(hoplen_in_sec * fs))
# next power of two of window length is NFFT
nfft = int(np.power(2, np.ceil(np.log2(winlen_in_sec * fs))))
specgm,f,t = specgram(x, nfft=nfft, fs=fs, overlap = win_length-hop_length, window=np.hamming(win_length))
pow_spec = np.power(np.abs(specgm), 2)
if dither:
pow_spec = np.add(pow_spec, win_length)
# Calculate log energy - after windowing
e = np.log(np.sum(pow_spec, axis = 0))
return pow_spec, e
def hz2bark(f):
"""
@About: Converts frequencies Hertz (Hz) to Bark
It uses;
Traunmueller-formula for f > 200 Hz
linear mapping for f <= 200 Hz
z_gt_200 = 26.81 .* f ./ (1960 + f) - 0.53;
z_le_200 = f ./ 102.9;
z = (f>200) .* z_gt_200 + (f<=200) .* z_le_200;
@ Author: Kyrill, Oct. 1996
Kyrill, March 1997 (linear mapping added)
"""
# Inverse of Hynek's formula (see bark2hz)
# z = 6 * log(f/600 + sqrt(1+ ((f/600).^2)));
# z = 6 * asinh(f/600); # (matlab equivalent)
z = np.multiply(6.0, np.arcsinh(np.divide(f, 600.0)))
return z
def bark2hz(z):
"""
@Author: Converts frequencies Bark to Hertz (Hz)
It uses;
Traunmueller-formula for z > 2 Bark
linear mapping for z <= 2 Bark
hz_gt_2 = 1960 .* (z + 0.53) ./ (26.28 - z);
hz_le_2 = z .* 102.9;
hz = (z>2) .* hz_gt_2 + (z<=2) .* hz_le_2;
@Author: Kyrill, Oct. 1996
Kyrill, March 1997 (linear mapping added)
"""
hz = np.multiply(600.0, np.sinh(np.divide(z, 6.0)))
return hz
def fft2barkmx(
nfft, sr, nfilts = 0,
band_width = 1, min_freq = 0.0,
max_freq = 0.0
):
"""
@About: Generate a matrix of weights to combine FFT bins into Bark bins
weights = fft2barkmx(nfft, sr, nfilts, width, minfreq, maxfreq)
where, nfft : source FFT size
sr : sampling frequency (Hz)
nfilts : number of output bands required (else per one bark).
band_width : a constant width of each band in Bark
weights : It nfft columns, the second half are all zero.
Note: Bark spectrum is fft2barkmx(nfft,sr)*abs(fft(xincols,nfft));
2004-09-05 <EMAIL> based on rastamat/audspec.m
"""
if max_freq == 0:
max_freq = sr / 2.0
min_bark = hz2bark(min_freq)
nyqbark = hz2bark(max_freq) - min_bark
if nfilts == 0 :
nfilts = np.add(np.ceil(nyqbark), 1)
weights = np.zeros((int(nfilts), int(nfft)))
step_barks = np.divide(nyqbark, np.subtract(nfilts, 1))
binbarks = hz2bark(np.multiply(np.arange(0, np.add(np.divide(nfft, 2),1)), np.divide(sr, nfft)))
for i in range (int(nfilts)):
f_bark_mid = min_bark + np.multiply(i, step_barks)
# Linear slopes in log-space (i.e. dB) intersect to trapezoidal window
lof = np.subtract(np.subtract(binbarks, f_bark_mid), 0.5)
hif = np.add(np.subtract(binbarks, f_bark_mid), 0.5)
weights[i, 0 : int(nfft / 2) + 1] = np.power(10, np.minimum(0, np.divide(np.minimum(hif, np.multiply(-2.5, lof)), band_width)))
return weights
def rastafilt(x):
"""
y = rastafilt(x)
xrow, xcol = x.shape()
where, x : input signal
xrow : critical bands
xcol : no of frames
y : rasta filtered signal
"""
# rasta filter
numer = np.arange(-2, 3)
numer = np.divide(-1.0*numer,sum(np.power(numer,2)))
denom = np.array([1, -0.94])
"""
Initialize the state.
This avoids a big spike at the beginning resulting from the dc offset level in each band.
"""
zi = signal.lfilter_zi(numer,1)
y = np.zeros((x.shape))
for i in range(x.shape[0]):
# FIR for initial state response compuation
y1, zi = signal.lfilter(numer, 1, x[i, 0:4], axis = 0, zi = zi * x[i, 0])
y1 = y1*0
# IIR
y2, _ = signal.lfilter(numer, denom, x[i, 4:x.shape[1]], axis = 0, zi = zi)
y[i, :] = np.append(y1, y2)
return y
def dolpc(x, modelorder = 8):
"""
y = dolpc(x,modelorder)
@About: compute autoregressive model from spectral magnitude samples
where, x : input signal
row_x, col_x = x.shape()
row_x : critical band
col_y : nframes
modelorder : order of model, defaults to 8
y : lpc coeff.
row_y, col_y = y.shape()
row_y :
"""
nbands, nframes = x.shape
ncorr = 2 * (nbands - 1)
# @TO-DO : This need optimisation
R = np.zeros((ncorr, nframes))
R[0:nbands, :] = x
for i in range(nbands - 1):
R[i + nbands - 1, :] = x[nbands - (i + 1), :]
# Calculate autocorrelation
r = fft.ifft(R.T).real.T
# First half only
r = r[0:nbands, :]
y = np.ones((nframes, modelorder + 1))
e = np.zeros((nframes, 1))
# Find LPC coeffs by durbin
if modelorder == 0:
for i in range(nframes):
_ , e_tmp, _ = spectrum.LEVINSON(r[:, i], modelorder, allow_singularity = True)
e[i, 0] = e_tmp
else:
for i in range(nframes):
y_tmp, e_tmp, _ = spectrum.LEVINSON(r[:, i], modelorder, allow_singularity = True)
y[i, 1:modelorder + 1] = y_tmp
e[i, 0] = e_tmp
# Normalize each poly by gain
y = np.divide(y.T, np.add(np.tile(e.T, (modelorder + 1, 1)), 1e-8))
return y
def lpc2cep(a, nout = 0):
"""
cep = lpc2cep(lpcas,nout)
where, lpcas = lp coeff.
nout = number of cepstra to produce, defaults to size(lpcas,1)
"""
nin, ncol = a.shape
order = nin - 1
if nout == 0:
nout = order + 1
# First cep is log(Error) from Durbin
cep = np.zeros((nout, ncol))
cep[0, :] = -np.log(a[0, :])
# Renormalize lpc A coeffs
norm_a = np.divide(a, np.add(np.tile(a[0, :], (nin, 1)), 1e-8))
for n in range(1, nout):
sum = 0
for m in range(1, n):
sum = np.add(sum, np.multiply(np.multiply((n - m), norm_a[m, :]), cep[(n - m), :]))
cep[n, :] = -np.add(norm_a[n, :], np.divide(sum, n))
return cep
def lifter(x, lift = 0.6, invs = False):
"""
@About : Apply lifter to matrix of cepstra
y = lifter(x, lift, invs)
lift = exponent of x i^n liftering or, as a negative integer, the length of HTK-style sin-curve liftering.
If inverse == True (default False), undo the liftering.
"""
ncep = x.shape[0]
if lift == 0:
y = x
else:
if lift < 0:
warnings.warn('HTK liftering does not support yet; default liftering')
lift = 0.6
lift_weights = np.power(np.arange(1, ncep), lift)
lift_weights = np.append(1, lift_weights)
if (invs):
lift_weights = np.divide(1, lift_weights)
y = np.matmul(np.diag(lift_weights), x)
return y
def hz2mel(f, htk = False):
"""
@About : Convert frequencies in Hz to mel 'scale'.
z = hz2mel(f,htk)
where, f : frequency in Hz
htk : True uses the mel axis defined in the HTKBook otherwise use Slaney's formula
"""
if htk:
z = np.multiply(2595, np.log10(np.add(1, np.divide(f, 700))))
else:
f_0 = 0.0 # 133.33333;
f_sp = 200.0 / 3 # 66.66667;
brkfrq = 1000.0
# starting mel value for log region
brkpt = (brkfrq - f_0) / f_sp
# the magic 1.0711703 which is the ratio needed to get from 1000 Hz to 6400 Hz in 27 steps, and is *almost* the ratio between 1000 Hz and the preceding linear filter center at 933.33333 Hz (actually 1000/933.33333 = 1.07142857142857 and exp(log(6.4)/27) = 1.07117028749447)
logstep = np.exp(np.log(6.4) / 27.0)
f = np.array(f, ndmin = 1)
z = np.zeros((f.shape[0], ))
# fill in parts separately
for i in range(f.shape[0]):
if f[i] < brkpt:
z[i] = (f[i] - f_0) / f_sp
else:
z[i] = brkpt + (np.log(f[i] / brkfrq) / np.log(logstep))
return z
def mel2hz(z, htk = False):
"""
@About : Converts 'mel scale' into Frequency in Hz
f = mel2hz(z, htk)
where, z : frequency in mel scale
htk : "True" means use the HTK formula else use the formula from Slaney's mfcc
f : frequency in Hz
"""
if htk:
f = np.multiply(700, np.subtract(np.power(10, np.divide(z, 2595)), 1))
else:
f_0 = 0.0 # 133.33333;
f_sp = 200.0/3 # 66.66667;
brkfrq = 1000.0
brkpt = (brkfrq - f_0) / f_sp # starting mel value for log region
logstep = np.exp(np.log(6.4) / 27.0) # the magic 1.0711703 which is the ratio needed to get from 1000 Hz to 6400 Hz in 27 steps, and is *almost* the ratio between 1000 Hz and the preceding linear filter center at 933.33333 Hz (actually 1000/933.33333 = 1.07142857142857 and exp(log(6.4)/27) = 1.07117028749447)
z = np.array(z, ndmin = 1)
f = np.zeros((z.shape[0], ))
# fill in parts separately
for i in range(z.shape[0]):
if z[i] < brkpt:
f[i] = f_0 + f_sp * z[i]
else:
f[i] = brkfrq * np.exp(np.log(logstep) * (z[i] - brkpt))
return f
def fft2melmx(
nfft, sr=8000, nfilts = 0,
band_width = 1, min_freq = 0.0,
max_freq = 0.0, htkmel = False,
constamp = False
):
"""
@About : Generate a matrix of weights to combine FFT bins into Mel
bins.
[weights, binfrqs] = fft2melmx(nfft, sr, nfilts, width, min_freq, max_freq, htkmel, constamp)
where, nfft : no of FFT point considered for given sampling rate.
sr : sampling rate.
nfilts : number of output bands required (else one per "mel/width")
width : the constant width of each band relative to standard Mel (default 1).
minfrq : frequency (in Hz) of the lowest band edge;
maxfrq : frequency (in Hz) of upper edge; default sr/2.
htkmel : "True" means use HTK's version of the mel curve, not Slaney's.
constamp : "True" means make integration windows peak at 1, not sum to 1.
weights : output model weights. weight has nfft columns, the second half are all zero.
binfrqs : returns bin center frequencies.
Note: You can exactly duplicate the mel matrix in Slaney's mfcc.m
as fft2melmx(512, 8000, 40, 1, 133.33, 6855.5, 0);
"""
if nfilts == 0 :
nfilts = np.ceil(hz2mel(max_freq, htkmel) / 2)
if max_freq == 0:
max_freq = sr / 2.0
weights = np.zeros((int(nfilts), int(nfft)))
# Center freqs of each FFT bin
fftfrqs = np.multiply(np.divide(np.arange(0,nfft / 2 + 1), nfft), sr)
# 'Center freqs' of mel bands - uniformly spaced between limits
min_mel = hz2mel(min_freq, htkmel)
max_mel = hz2mel(max_freq, htkmel)
binfrqs = mel2hz(np.add(min_mel, np.multiply(np.arange(0, nfilts + 2),
(max_mel - min_mel) / (nfilts + 1))), htkmel)
for i in range (int(nfilts)):
freq_tmp = binfrqs[np.add(np.arange(0,3), i)]
# scale by width
freq_tmp = np.add(freq_tmp[1], np.multiply(band_width, np.subtract(freq_tmp, freq_tmp[1])))
# lower and upper slopes for all bins
loslope = np.divide(np.subtract(fftfrqs, freq_tmp[0]), np.subtract(freq_tmp[1], freq_tmp[0]))
hislope = np.divide(np.subtract(freq_tmp[2], fftfrqs), np.subtract(freq_tmp[2], freq_tmp[1]))
weights[i, 0 : int(nfft / 2) + 1] = np.maximum(0, np.minimum(loslope, hislope))
if constamp == False:
# Slaney-style mel is scaled to be approx constant E per channel
weights = np.matmul(np.diag(np.divide(2, np.subtract(binfrqs[2 : int(nfilts) + 2],
binfrqs[0 : int(nfilts)]))), weights)
return weights, binfrqs
def audspec(p_spectrum,
fs = 8000, nfilts = 0, fbtype = 'bark',
min_freq = 0, max_freq = 0, sumpower = 1,
band_width = 1
):
"""
@About: Performs critical band analysis on power spectrogram (see PLP)
[aspectrum,weights] = audspec(pspectrum, sr, nfilts, fbtype, minfreq, maxfreq, sumpower, bwidth)
where, pspectrum : power spectrogram
sr : sampling frequency
nfilts : number of output bands required
fbtype : filterbank type
minfrq : frequency (in Hz) of the lowest band edge;
maxfrq : frequency (in Hz) of upper edge; default sr/2.
sumpower :
band_width : the constant width of each band relative to standard Mel (default 1).
aspectrum : spectrogram aftar band analysis
weight : output model weights
"""
if nfilts == 0:
np.add(np.ceil(hz2bark(fs / 2)), 1)
if max_freq == 0:
max_freq = fs / 2
nframes, nfreqs = p_spectrum.shape
# print("nfreq: ", nfreqs, p_spectrum.shape, type(nfreqs))
nfft = (int(nfreqs) - 1) * 2
weights = None
binfrqs = None
if fbtype == 'bark':
weights = fft2barkmx(nfft, fs, nfilts, band_width, min_freq, max_freq)
elif fbtype == 'mel':
weights,binfrqs = fft2melmx(nfft, fs, nfilts, band_width, min_freq, max_freq)
elif fbtype == 'htkmel':
weights,binfrqs = fft2melmx(nfft, fs, nfilts, band_width, min_freq, max_freq, htkmel = True, constamp = True)
elif fbtype == 'fcmel':
weights,binfrqs = fft2melmx(nfft, fs, nfilts, band_width, min_freq, max_freq, htkmel = True, constamp = False)
else:
raise TypeError("fbtype is not recognised. choose from 'bark', 'mel', 'htkmel', 'fcmel'")
weights = weights[:, 0 : nfreqs]
# Integrate FFT bins into Mel bins, in abs or abs^2 domains:
if sumpower:
aspectrum = weights.dot(p_spectrum.T).T
else:
aspectrum = np.power(weights.dot(np.sqrt(p_spectrum.T)).T, 2)
return aspectrum, weights
def postaud(x, fmax, fbtype = 'bark', broaden = 0):
nbands, nframes = x.shape
# print("postaud :: ",nbands, nframes)
nfpts = int(nbands + 2 * broaden)
if fbtype == 'bark':
bandcfhz = bark2hz(np.linspace(0, hz2bark(fmax), nfpts))
elif fbtype == 'mel':
bandcfhz = mel2hz(np.linspace(0, hz2mel(fmax), nfpts))
elif fbtype == 'htkmel' or fbtype == 'fcmel':
bandcfhz = mel2hz(np.linspace(0, hz2mel(fmax, htk = True), nfpts), htk = True)
bandcfhz = bandcfhz[broaden : (nfpts - broaden)]
# Hynek's magic equal-loudness-curve formula
fsq = np.power(bandcfhz, 2)
ftmp = np.add(fsq, 1.6e5)
eql = np.multiply(np.power(np.divide(fsq, ftmp), 2), np.divide(np.add(fsq, 1.44e6), np.add(fsq, 9.61e6)))
# weight the critical bands
z = np.multiply(np.tile(eql, (nframes, 1)).T, x)
# cube root compress
z = np.power(z, 0.33)
# replicate first and last band (because they are unreliable as calculated)
if broaden:
y = np.zeros((z.shape[0] + 2, z.shape[1]))
y[0, :] = z[0, :]
y[1:nbands + 1, :] = z
y[nbands + 1, :] = z[z.shape[0] - 1, :]
else:
y = np.zeros((z.shape[0], z.shape[1]))
y[0, :] = z[1, :]
y[1:nbands - 1, :] = z[1:z.shape[0] - 1, :]
y[nbands - 1, :] = z[z.shape[0] - 2, :]
return y.T
def spec2cep(spec, ncep=13, dcttype=2):
nrow, ncol = spec.shape[0], spec.shape[1]
dctm = np.zeros((ncep, nrow))
if dcttype == 2 or dcttype == 3:
for i in range(ncep):
dctm[i, :] = np.multiply(np.cos(i*np.arange(1, 2 * nrow, 2)/(2 * nrow)*np.pi), np.sqrt(2 / nrow))
if dcttype == 2:
dctm[0, :] = np.divide(dctm[0, :], np.sqrt(2))
elif dcttype == 4:
for i in range(ncep):
dctm[i, :] = np.multiply(np.cos(np.multiply(np.divide(np.multiply(i, np.arange(1, nrow + 1)), (nrow + 1)), np.pi)), 2)
dctm[i, 0] = np.add(dctm[i, 0], 1)
dctm[i, int(nrow - 1)] = np.multiply(dctm[i, int(nrow - 1)], np.power(-1, i))
dctm = np.divide(dctm, 2 * (nrow + 1))
else:
for i in range(ncep):
dctm[i, :] = np.divide(np.multiply(np.cos(np.multiply(np.divide(np.multiply(i, np.arange(0, nrow)), (nrow - 1)), np.pi)), 2), 2 * (nrow - 1))
dctm[:, 0] = np.divide(dctm[:, 0], 2)
dctm[:, int(nrow - 1)] = np.divide(dctm[:, int(nrow - 1)], 2)
# cep = np.matmul(dctm, np.log(np.add(spec, 1e-8)))
cep = dctm.dot(np.log(np.add(spec, 1e-8)))
return cep.T, dctm
def lpc2spec(lpcas, nout = 17, FMout = False):
rows, cols = lpcas.shape
order = rows - 1
gg = lpcas[0, :]
aa = np.divide(lpcas, np.tile(gg, (rows, 1)))
# Calculate the actual z-plane polyvals: nout points around unit circle
tmp_1 = np.array(np.arange(0, nout), ndmin = 2).T
tmp_1 = np.divide(np.multiply(-1j, np.multiply(tmp_1, np.pi)), (nout - 1))
tmp_2 = np.array(np.arange(0, order + 1), ndmin = 2)
zz = np.exp(np.matmul(tmp_1, tmp_2))
# Actual polyvals, in power (mag^2)
features = np.divide(np.power(np.divide(1, np.abs(np.matmul(zz, aa))), 2), np.tile(gg, (nout, 1)))
F = np.zeros((cols, int(np.ceil(rows / 2))))
M = F
if FMout == True:
for c in range(cols):
aaa = aa[:, c]
rr = np.roots(aaa)
ff_tmp = np.angle(rr)
ff = np.array(ff_tmp, ndmin = 2).T
zz = np.exp(np.multiply(1j, np.matmul(ff, np.array(np.arange(0, aaa.shape[0]), ndmin = 2))))
mags = np.sqrt(np.divide(np.power(np.divide(1, np.abs(np.matmul(zz, np.array(aaa, ndmin = 2).T))), 2), gg[c]))
ix = np.argsort(ff_tmp)
dummy = np.sort(ff_tmp)
tmp_F_list = []
tmp_M_list = []
for i in range(ff.shape[0]):
if dummy[i] > 0:
tmp_F_list = np.append(tmp_F_list, dummy[i])
tmp_M_list = np.append(tmp_M_list, mags[ix[i]])
M[c, 0 : tmp_M_list.shape[0]] = tmp_M_list
F[c, 0 : tmp_F_list.shape[0]] = tmp_F_list
return features, F, M
def deltas(x, w = 9):
rows, cols = x.shape
hlen = np.floor(w / 2)
win = np.arange(hlen,-(hlen + 1),-1, dtype = 'float32')
xx = np.append(np.append(np.tile(x[:, 0], (int(hlen), 1)).T, x, axis = 1),
np.tile(x[:, cols - 1], (int(hlen), 1)).T, axis = 1)
d = signal.lfilter(win, 1, xx, axis = 1)
d = d[:, int(2 * hlen) : int(2 * hlen + cols)]
return d
def cep2spec(cep, nfreq, dcttype = 2):
ncep, ncol = cep.shape
dctm = np.zeros((ncep, nfreq))
idctm = np.zeros((nfreq, ncep))
if dcttype == 2 or dcttype == 3:
for i in range(ncep):
dctm[i, :] = np.multiply(np.cos(np.multiply(np.divide(np.multiply(i, np.arange(1, 2 * nfreq, 2)),
(2 * nfreq)), np.pi)), np.sqrt(2 / nfreq))
if dcttype == 2:
dctm[0, :] = np.divide(dctm[0, :], np.sqrt(2))
else:
dctm[0, :] = np.divide(dctm[0, :], 2)
idctm = dctm.T
elif dcttype == 4:
for i in range(ncep):
idctm[:, i] = np.multiply(np.cos(np.multiply(np.divide(np.multiply(i, np.arange(1, nfreq + 1).T), (nfreq + 1)), np.pi)), 2)
idctm[:, 0:ncep] = np.divide(idctm[:, 0:ncep], 2)
else:
for i in range(ncep):
idctm[:, i] = np.multiply(np.cos(np.multiply(np.divide(np.multiply(i, np.arange(0, nfreq).T), (nfreq - 1)), np.pi)), 2)
idctm[:, [0, -1]] = np.divide(idctm[:, [0, -1]], 2)
spec = np.exp(np.matmul(idctm, cep))
return spec, idctm
def invpostaud(y, fmax, fbtype = 'bark', broaden = 0):
nbands, nframes = y.shape
if fbtype == 'bark':
bandcfhz = bark2hz(np.linspace(0, hz2bark(fmax), nbands))
elif fbtype == 'mel':
bandcfhz = mel2hz(np.linspace(0, hz2mel(fmax), nbands))
elif fbtype == 'htkmel' or fbtype == 'fcmel':
bandcfhz = mel2hz(np.linspace(0, hz2mel(fmax, htk = True), nbands), htk = True)
bandcfhz = bandcfhz[broaden : (nbands - broaden)]
fsq = np.power(bandcfhz, 2)
ftmp = np.add(fsq, 1.6e5)
eql = np.multiply(np.power(np.divide(fsq, ftmp), 2),
np.divide(np.add(fsq, 1.44e6), np.add(fsq, 9.61e6)))
x = np.power(y, np.divide(1, 0.33))
if eql[0] == 0:
eql[0] = eql[1]
eql[-1] = eql[-2]
x = np.divide(x[broaden : (nbands - broaden + 1), :], np.add(np.tile(eql.T, (nframes, 1)).T, 1e-8))
return x, eql
def invpowspec(y, fs, win_time, hoplen_in_sec, excit = []):
nrow, ncol = y.shape
r = excit
winpts = int(np.round(np.multiply(win_time, fs)))
steppts = int(np.round(np.multiply(hoplen_in_sec, fs)))
nfft = int(np.power(2, np.ceil(np.divide(np.log(winpts), np.log(2)))))
# Can't predict librosa stft length...
tmp = librosa.istft(y, hop_length = steppts, win_length = winpts,
window='hann', center = False)
xlen = len(tmp)
# xlen = int(np.add(winpts, np.multiply(steppts, np.subtract(ncol, 1))))
# xlen = int(np.multiply(steppts, np.subtract(ncol, 1)))
if len(r) == 0:
r = np.squeeze(np.random.randn(xlen, 1))
r = r[0:xlen]
R = librosa.stft(np.divide(r, 32768 * 12), n_fft = nfft, hop_length = steppts,
win_length = winpts, window = 'hann', center = False)
R = np.multiply(R, np.sqrt(y))
x = librosa.istft(R, hop_length = steppts, win_length = winpts,
window = 'hann', center = False)
return x
def invaudspec(aspectrum, fs = 16000, nfft = 512, fbtype = 'bark',
min_freq = 0, max_freq = 0, sumpower = True, band_width = 1):
if max_freq == 0:
max_freq = fs / 2
nfilts, nframes = aspectrum.shape
if fbtype == 'bark':
weights = fft2barkmx(nfft, fs, nfilts, band_width, min_freq, max_freq)
elif fbtype == 'mel':
weights = fft2melmx(nfft, fs, nfilts, band_width, min_freq, max_freq)
elif fbtype == 'htkmel':
weights = fft2melmx(nfft, fs, nfilts, band_width, min_freq, max_freq, htkmel = True, constamp = True)
elif fbtype == 'fcmel':
weights = fft2melmx(nfft, fs, nfilts, band_width, min_freq, max_freq, htkmel = True, constamp = False)
weights = weights[:, 0:int(nfft / 2 + 1)]
ww = np.matmul(weights.T, weights)
itws = np.divide(weights.T, np.tile(np.maximum(np.divide(np.mean(np.diag(ww)), 100),
np.sum(ww, axis = 0)), (nfilts, 1)).T)
if sumpower == True:
spec = np.matmul(itws, aspectrum)
else:
spec = np.power(np.matmul(itws, np.sqrt(aspectrum)))
return spec, weights, itws
def delta_voicebox(CepCoeff, d):
"""
delta_coeff = mfcc2delta(CepCoeff,d);
Input:
CepCoeff: Cepstral Coefficient (Row Represents a feature vector for a frame)
d : Lag size for delta feature computation
Output:
delta_coeff: Output delta coefficient
Ref . http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
"""
vf = np.arange(d,-(d+1),-1)
vf=vf/sum(vf**2);
ww=np.ones((d,1));
NoOfFrame, NoOfCoeff = CepCoeff.shape
cx = np.concatenate(
(np.concatenate(CepCoeff[(ww-1).astype(int)]),
CepCoeff ,
np.concatenate(CepCoeff[(ww*NoOfFrame-1).astype(int)]))
)
cx_r, cx_c = cx.shape
cx_col = cx.T.reshape(cx_r*cx_c)
vx = signal.lfilter(vf,1,cx_col.T).reshape((cx_r,cx_c), order='F')
delta_coeff=vx[2*d::,:]
return delta_coeff
def sdc(CepCoeff, N=7, D=1, P=3, K=7):
"""
About: Shifted Delta Coefficient Computation.
Usage: sdc_coeff = mfcc2sdc(CepCoeff,N,d,P,k)
input:
CepCoeff : MFCC Coefficients stored in row-wise
N: NoOfCepstrum i.e. no of column of CepCoeff
d: Amount of shift for delta computation
P: Amount of shift for next frame whose deltas are to be computed.
K: No of frame whose deltas are to be stacked.
output:
sdc_coeff: Shifted delta coefficient of CepCoeff.
Dimension of the output: NumberOfFrame x N*K
Ref. <NAME>, J.P.Campbell, <NAME>, <NAME>, <NAME>, Support
vector machines for speaker and language recognition,
Computer Speech & Language, Volume 20, Issues 2-3,
Odyssey 2004: The speaker and Language Recognition
Workshop - Odyssey-04, April-July 2006, Pages 210-229.
"""
nframe, ncoeff = CepCoeff.shape
CepCoeff = np.concatenate((CepCoeff,CepCoeff[0:P*(K-1),:]))
NoOfFrame, NoOfCoeff = CepCoeff.shape
delta_coeff = delta_voicebox(CepCoeff,D).T
sdc_coeff = []
for i in range(K):
temp=(delta_coeff[:,P*i::])[:,0:nframe]
sdc_coeff.append(temp)
sdc_coeff = np.concatenate(sdc_coeff)
return sdc_coeff
|
[
"numpy.roots",
"numpy.abs",
"numpy.sum",
"numpy.angle",
"numpy.floor",
"numpy.ones",
"numpy.argsort",
"librosa.istft",
"numpy.arange",
"numpy.tile",
"numpy.diag",
"numpy.round",
"spectrum.LEVINSON",
"numpy.multiply",
"numpy.random.randn",
"scipy.signal.lfilter",
"numpy.fft.fft",
"numpy.power",
"numpy.append",
"numpy.hanning",
"numpy.add",
"numpy.divide",
"numpy.minimum",
"numpy.ceil",
"numpy.hamming",
"numpy.log2",
"scipy.fftpack.ifft",
"numpy.sort",
"numpy.concatenate",
"scipy.signal.lfilter_zi",
"numpy.subtract",
"numpy.log",
"numpy.zeros",
"numpy.array",
"numpy.matmul",
"warnings.warn",
"numpy.sqrt"
] |
[((305, 317), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (313, 317), True, 'import numpy as np\n'), ((1490, 1507), 'numpy.concatenate', 'np.concatenate', (['S'], {}), '(S)\n', (1504, 1507), True, 'import numpy as np\n'), ((1516, 1535), 'numpy.fft.fft', 'np.fft.fft', (['S', 'nfft'], {}), '(S, nfft)\n', (1526, 1535), True, 'import numpy as np\n'), ((5823, 5839), 'numpy.arange', 'np.arange', (['(-2)', '(3)'], {}), '(-2, 3)\n', (5832, 5839), True, 'import numpy as np\n'), ((5909, 5929), 'numpy.array', 'np.array', (['[1, -0.94]'], {}), '([1, -0.94])\n', (5917, 5929), True, 'import numpy as np\n'), ((6076, 6103), 'scipy.signal.lfilter_zi', 'signal.lfilter_zi', (['numer', '(1)'], {}), '(numer, 1)\n', (6093, 6103), False, 'from scipy import signal\n'), ((6111, 6128), 'numpy.zeros', 'np.zeros', (['x.shape'], {}), '(x.shape)\n', (6119, 6128), True, 'import numpy as np\n'), ((7008, 7034), 'numpy.zeros', 'np.zeros', (['(ncorr, nframes)'], {}), '((ncorr, nframes))\n', (7016, 7034), True, 'import numpy as np\n'), ((7260, 7294), 'numpy.ones', 'np.ones', (['(nframes, modelorder + 1)'], {}), '((nframes, modelorder + 1))\n', (7267, 7294), True, 'import numpy as np\n'), ((7303, 7325), 'numpy.zeros', 'np.zeros', (['(nframes, 1)'], {}), '((nframes, 1))\n', (7311, 7325), True, 'import numpy as np\n'), ((8198, 8220), 'numpy.zeros', 'np.zeros', (['(nout, ncol)'], {}), '((nout, ncol))\n', (8206, 8220), True, 'import numpy as np\n'), ((17097, 17118), 'numpy.power', 'np.power', (['bandcfhz', '(2)'], {}), '(bandcfhz, 2)\n', (17105, 17118), True, 'import numpy as np\n'), ((17130, 17151), 'numpy.add', 'np.add', (['fsq', '(160000.0)'], {}), '(fsq, 160000.0)\n', (17136, 17151), True, 'import numpy as np\n'), ((17379, 17396), 'numpy.power', 'np.power', (['z', '(0.33)'], {}), '(z, 0.33)\n', (17387, 17396), True, 'import numpy as np\n'), ((17947, 17969), 'numpy.zeros', 'np.zeros', (['(ncep, nrow)'], {}), '((ncep, nrow))\n', (17955, 17969), True, 'import numpy as np\n'), ((20683, 20698), 'numpy.floor', 'np.floor', (['(w / 2)'], {}), '(w / 2)\n', (20691, 20698), True, 'import numpy as np\n'), ((20709, 20758), 'numpy.arange', 'np.arange', (['hlen', '(-(hlen + 1))', '(-1)'], {'dtype': '"""float32"""'}), "(hlen, -(hlen + 1), -1, dtype='float32')\n", (20718, 20758), True, 'import numpy as np\n'), ((20916, 20950), 'scipy.signal.lfilter', 'signal.lfilter', (['win', '(1)', 'xx'], {'axis': '(1)'}), '(win, 1, xx, axis=1)\n', (20930, 20950), False, 'from scipy import signal\n'), ((21097, 21120), 'numpy.zeros', 'np.zeros', (['(ncep, nfreq)'], {}), '((ncep, nfreq))\n', (21105, 21120), True, 'import numpy as np\n'), ((21133, 21156), 'numpy.zeros', 'np.zeros', (['(nfreq, ncep)'], {}), '((nfreq, ncep))\n', (21141, 21156), True, 'import numpy as np\n'), ((22639, 22660), 'numpy.power', 'np.power', (['bandcfhz', '(2)'], {}), '(bandcfhz, 2)\n', (22647, 22660), True, 'import numpy as np\n'), ((22672, 22693), 'numpy.add', 'np.add', (['fsq', '(160000.0)'], {}), '(fsq, 160000.0)\n', (22678, 22693), True, 'import numpy as np\n'), ((23403, 23491), 'librosa.istft', 'librosa.istft', (['y'], {'hop_length': 'steppts', 'win_length': 'winpts', 'window': '"""hann"""', 'center': '(False)'}), "(y, hop_length=steppts, win_length=winpts, window='hann',\n center=False)\n", (23416, 23491), False, 'import librosa\n'), ((23965, 24053), 'librosa.istft', 'librosa.istft', (['R'], {'hop_length': 'steppts', 'win_length': 'winpts', 'window': '"""hann"""', 'center': '(False)'}), "(R, hop_length=steppts, win_length=winpts, window='hann',\n center=False)\n", (23978, 24053), False, 'import librosa\n'), ((24870, 24899), 'numpy.matmul', 'np.matmul', (['weights.T', 'weights'], {}), '(weights.T, weights)\n', (24879, 24899), True, 'import numpy as np\n'), ((25630, 25656), 'numpy.arange', 'np.arange', (['d', '(-(d + 1))', '(-1)'], {}), '(d, -(d + 1), -1)\n', (25639, 25656), True, 'import numpy as np\n'), ((25682, 25697), 'numpy.ones', 'np.ones', (['(d, 1)'], {}), '((d, 1))\n', (25689, 25697), True, 'import numpy as np\n'), ((27037, 27091), 'numpy.concatenate', 'np.concatenate', (['(CepCoeff, CepCoeff[0:P * (K - 1), :])'], {}), '((CepCoeff, CepCoeff[0:P * (K - 1), :]))\n', (27051, 27091), True, 'import numpy as np\n'), ((27312, 27337), 'numpy.concatenate', 'np.concatenate', (['sdc_coeff'], {}), '(sdc_coeff)\n', (27326, 27337), True, 'import numpy as np\n'), ((725, 743), 'numpy.hanning', 'np.hanning', (['window'], {}), '(window)\n', (735, 743), True, 'import numpy as np\n'), ((862, 878), 'numpy.hanning', 'np.hanning', (['nfft'], {}), '(nfft)\n', (872, 878), True, 'import numpy as np\n'), ((1088, 1155), 'warnings.warn', 'warnings.warn', (['"""fft points adjusted to win_size as win_size > nfft"""'], {}), "('fft points adjusted to win_size as win_size > nfft')\n", (1101, 1155), False, 'import warnings\n'), ((1732, 1748), 'numpy.array', 'np.array', (['offset'], {}), '(offset)\n', (1740, 1748), True, 'import numpy as np\n'), ((2354, 2382), 'numpy.round', 'np.round', (['(winlen_in_sec * fs)'], {}), '(winlen_in_sec * fs)\n', (2362, 2382), True, 'import numpy as np\n'), ((2405, 2433), 'numpy.round', 'np.round', (['(hoplen_in_sec * fs)'], {}), '(hoplen_in_sec * fs)\n', (2413, 2433), True, 'import numpy as np\n'), ((2688, 2702), 'numpy.abs', 'np.abs', (['specgm'], {}), '(specgm)\n', (2694, 2702), True, 'import numpy as np\n'), ((2741, 2769), 'numpy.add', 'np.add', (['pow_spec', 'win_length'], {}), '(pow_spec, win_length)\n', (2747, 2769), True, 'import numpy as np\n'), ((2831, 2855), 'numpy.sum', 'np.sum', (['pow_spec'], {'axis': '(0)'}), '(pow_spec, axis=0)\n', (2837, 2855), True, 'import numpy as np\n'), ((4992, 5014), 'numpy.subtract', 'np.subtract', (['nfilts', '(1)'], {}), '(nfilts, 1)\n', (5003, 5014), True, 'import numpy as np\n'), ((6232, 6292), 'scipy.signal.lfilter', 'signal.lfilter', (['numer', '(1)', 'x[i, 0:4]'], {'axis': '(0)', 'zi': '(zi * x[i, 0])'}), '(numer, 1, x[i, 0:4], axis=0, zi=zi * x[i, 0])\n', (6246, 6292), False, 'from scipy import signal\n'), ((6346, 6409), 'scipy.signal.lfilter', 'signal.lfilter', (['numer', 'denom', 'x[i, 4:x.shape[1]]'], {'axis': '(0)', 'zi': 'zi'}), '(numer, denom, x[i, 4:x.shape[1]], axis=0, zi=zi)\n', (6360, 6409), False, 'from scipy import signal\n'), ((6432, 6449), 'numpy.append', 'np.append', (['y1', 'y2'], {}), '(y1, y2)\n', (6441, 6449), True, 'import numpy as np\n'), ((8238, 8253), 'numpy.log', 'np.log', (['a[0, :]'], {}), '(a[0, :])\n', (8244, 8253), True, 'import numpy as np\n'), ((9184, 9210), 'numpy.append', 'np.append', (['(1)', 'lift_weights'], {}), '(1, lift_weights)\n', (9193, 9210), True, 'import numpy as np\n'), ((10216, 10236), 'numpy.array', 'np.array', (['f'], {'ndmin': '(1)'}), '(f, ndmin=1)\n', (10224, 10236), True, 'import numpy as np\n'), ((10251, 10274), 'numpy.zeros', 'np.zeros', (['(f.shape[0],)'], {}), '((f.shape[0],))\n', (10259, 10274), True, 'import numpy as np\n'), ((11419, 11439), 'numpy.array', 'np.array', (['z'], {'ndmin': '(1)'}), '(z, ndmin=1)\n', (11427, 11439), True, 'import numpy as np\n'), ((11454, 11477), 'numpy.zeros', 'np.zeros', (['(z.shape[0],)'], {}), '((z.shape[0],))\n', (11462, 11477), True, 'import numpy as np\n'), ((17506, 17544), 'numpy.zeros', 'np.zeros', (['(z.shape[0] + 2, z.shape[1])'], {}), '((z.shape[0] + 2, z.shape[1]))\n', (17514, 17544), True, 'import numpy as np\n'), ((17672, 17706), 'numpy.zeros', 'np.zeros', (['(z.shape[0], z.shape[1])'], {}), '((z.shape[0], z.shape[1]))\n', (17680, 17706), True, 'import numpy as np\n'), ((19188, 19210), 'numpy.tile', 'np.tile', (['gg', '(rows, 1)'], {}), '(gg, (rows, 1))\n', (19195, 19210), True, 'import numpy as np\n'), ((19446, 19469), 'numpy.arange', 'np.arange', (['(0)', '(order + 1)'], {}), '(0, order + 1)\n', (19455, 19469), True, 'import numpy as np\n'), ((19498, 19521), 'numpy.matmul', 'np.matmul', (['tmp_1', 'tmp_2'], {}), '(tmp_1, tmp_2)\n', (19507, 19521), True, 'import numpy as np\n'), ((19646, 19668), 'numpy.tile', 'np.tile', (['gg', '(nout, 1)'], {}), '(gg, (nout, 1))\n', (19653, 19668), True, 'import numpy as np\n'), ((22119, 22140), 'numpy.matmul', 'np.matmul', (['idctm', 'cep'], {}), '(idctm, cep)\n', (22128, 22140), True, 'import numpy as np\n'), ((22844, 22862), 'numpy.divide', 'np.divide', (['(1)', '(0.33)'], {}), '(1, 0.33)\n', (22853, 22862), True, 'import numpy as np\n'), ((23784, 23808), 'numpy.divide', 'np.divide', (['r', '(32768 * 12)'], {}), '(r, 32768 * 12)\n', (23793, 23808), True, 'import numpy as np\n'), ((23945, 23955), 'numpy.sqrt', 'np.sqrt', (['y'], {}), '(y)\n', (23952, 23955), True, 'import numpy as np\n'), ((25115, 25141), 'numpy.matmul', 'np.matmul', (['itws', 'aspectrum'], {}), '(itws, aspectrum)\n', (25124, 25141), True, 'import numpy as np\n'), ((2639, 2661), 'numpy.hamming', 'np.hamming', (['win_length'], {}), '(win_length)\n', (2649, 2661), True, 'import numpy as np\n'), ((3489, 3508), 'numpy.divide', 'np.divide', (['f', '(600.0)'], {}), '(f, 600.0)\n', (3498, 3508), True, 'import numpy as np\n'), ((3987, 4004), 'numpy.divide', 'np.divide', (['z', '(6.0)'], {}), '(z, 6.0)\n', (3996, 4004), True, 'import numpy as np\n'), ((4885, 4901), 'numpy.ceil', 'np.ceil', (['nyqbark'], {}), '(nyqbark)\n', (4892, 4901), True, 'import numpy as np\n'), ((5095, 5114), 'numpy.divide', 'np.divide', (['sr', 'nfft'], {}), '(sr, nfft)\n', (5104, 5114), True, 'import numpy as np\n'), ((5184, 5210), 'numpy.multiply', 'np.multiply', (['i', 'step_barks'], {}), '(i, step_barks)\n', (5195, 5210), True, 'import numpy as np\n'), ((5317, 5350), 'numpy.subtract', 'np.subtract', (['binbarks', 'f_bark_mid'], {}), '(binbarks, f_bark_mid)\n', (5328, 5350), True, 'import numpy as np\n'), ((5378, 5411), 'numpy.subtract', 'np.subtract', (['binbarks', 'f_bark_mid'], {}), '(binbarks, f_bark_mid)\n', (5389, 5411), True, 'import numpy as np\n'), ((5877, 5895), 'numpy.power', 'np.power', (['numer', '(2)'], {}), '(numer, 2)\n', (5885, 5895), True, 'import numpy as np\n'), ((7185, 7198), 'scipy.fftpack.ifft', 'fft.ifft', (['R.T'], {}), '(R.T)\n', (7193, 7198), True, 'import scipy.fftpack as fft\n'), ((7443, 7505), 'spectrum.LEVINSON', 'spectrum.LEVINSON', (['r[:, i]', 'modelorder'], {'allow_singularity': '(True)'}), '(r[:, i], modelorder, allow_singularity=True)\n', (7460, 7505), False, 'import spectrum\n'), ((7609, 7671), 'spectrum.LEVINSON', 'spectrum.LEVINSON', (['r[:, i]', 'modelorder'], {'allow_singularity': '(True)'}), '(r[:, i], modelorder, allow_singularity=True)\n', (7626, 7671), False, 'import spectrum\n'), ((7810, 7843), 'numpy.tile', 'np.tile', (['e.T', '(modelorder + 1, 1)'], {}), '(e.T, (modelorder + 1, 1))\n', (7817, 7843), True, 'import numpy as np\n'), ((8319, 8345), 'numpy.tile', 'np.tile', (['a[0, :]', '(nin, 1)'], {}), '(a[0, :], (nin, 1))\n', (8326, 8345), True, 'import numpy as np\n'), ((9009, 9079), 'warnings.warn', 'warnings.warn', (['"""HTK liftering does not support yet; default liftering"""'], {}), "('HTK liftering does not support yet; default liftering')\n", (9022, 9079), False, 'import warnings\n'), ((9135, 9153), 'numpy.arange', 'np.arange', (['(1)', 'ncep'], {}), '(1, ncep)\n', (9144, 9153), True, 'import numpy as np\n'), ((9258, 9284), 'numpy.divide', 'np.divide', (['(1)', 'lift_weights'], {}), '(1, lift_weights)\n', (9267, 9284), True, 'import numpy as np\n'), ((9308, 9329), 'numpy.diag', 'np.diag', (['lift_weights'], {}), '(lift_weights)\n', (9315, 9329), True, 'import numpy as np\n'), ((13243, 13269), 'numpy.arange', 'np.arange', (['(0)', '(nfft / 2 + 1)'], {}), '(0, nfft / 2 + 1)\n', (13252, 13269), True, 'import numpy as np\n'), ((13846, 13879), 'numpy.subtract', 'np.subtract', (['fftfrqs', 'freq_tmp[0]'], {}), '(fftfrqs, freq_tmp[0])\n', (13857, 13879), True, 'import numpy as np\n'), ((13881, 13918), 'numpy.subtract', 'np.subtract', (['freq_tmp[1]', 'freq_tmp[0]'], {}), '(freq_tmp[1], freq_tmp[0])\n', (13892, 13918), True, 'import numpy as np\n'), ((13948, 13981), 'numpy.subtract', 'np.subtract', (['freq_tmp[2]', 'fftfrqs'], {}), '(freq_tmp[2], fftfrqs)\n', (13959, 13981), True, 'import numpy as np\n'), ((13983, 14020), 'numpy.subtract', 'np.subtract', (['freq_tmp[2]', 'freq_tmp[1]'], {}), '(freq_tmp[2], freq_tmp[1])\n', (13994, 14020), True, 'import numpy as np\n'), ((14080, 14108), 'numpy.minimum', 'np.minimum', (['loslope', 'hislope'], {}), '(loslope, hislope)\n', (14090, 14108), True, 'import numpy as np\n'), ((17180, 17200), 'numpy.divide', 'np.divide', (['fsq', 'ftmp'], {}), '(fsq, ftmp)\n', (17189, 17200), True, 'import numpy as np\n'), ((17216, 17238), 'numpy.add', 'np.add', (['fsq', '(1440000.0)'], {}), '(fsq, 1440000.0)\n', (17222, 17238), True, 'import numpy as np\n'), ((17237, 17259), 'numpy.add', 'np.add', (['fsq', '(9610000.0)'], {}), '(fsq, 9610000.0)\n', (17243, 17259), True, 'import numpy as np\n'), ((17312, 17338), 'numpy.tile', 'np.tile', (['eql', '(nframes, 1)'], {}), '(eql, (nframes, 1))\n', (17319, 17338), True, 'import numpy as np\n'), ((18570, 18601), 'numpy.divide', 'np.divide', (['dctm', '(2 * (nrow + 1))'], {}), '(dctm, 2 * (nrow + 1))\n', (18579, 18601), True, 'import numpy as np\n'), ((18818, 18842), 'numpy.divide', 'np.divide', (['dctm[:, 0]', '(2)'], {}), '(dctm[:, 0], 2)\n', (18827, 18842), True, 'import numpy as np\n'), ((18996, 19015), 'numpy.add', 'np.add', (['spec', '(1e-08)'], {}), '(spec, 1e-08)\n', (19002, 19015), True, 'import numpy as np\n'), ((19313, 19331), 'numpy.arange', 'np.arange', (['(0)', 'nout'], {}), '(0, nout)\n', (19322, 19331), True, 'import numpy as np\n'), ((19385, 19410), 'numpy.multiply', 'np.multiply', (['tmp_1', 'np.pi'], {}), '(tmp_1, np.pi)\n', (19396, 19410), True, 'import numpy as np\n'), ((19826, 19839), 'numpy.roots', 'np.roots', (['aaa'], {}), '(aaa)\n', (19834, 19839), True, 'import numpy as np\n'), ((19861, 19873), 'numpy.angle', 'np.angle', (['rr'], {}), '(rr)\n', (19869, 19873), True, 'import numpy as np\n'), ((20167, 20185), 'numpy.argsort', 'np.argsort', (['ff_tmp'], {}), '(ff_tmp)\n', (20177, 20185), True, 'import numpy as np\n'), ((20206, 20221), 'numpy.sort', 'np.sort', (['ff_tmp'], {}), '(ff_tmp)\n', (20213, 20221), True, 'import numpy as np\n'), ((21568, 21592), 'numpy.divide', 'np.divide', (['dctm[0, :]', '(2)'], {}), '(dctm[0, :], 2)\n', (21577, 21592), True, 'import numpy as np\n'), ((21835, 21865), 'numpy.divide', 'np.divide', (['idctm[:, 0:ncep]', '(2)'], {}), '(idctm[:, 0:ncep], 2)\n', (21844, 21865), True, 'import numpy as np\n'), ((22068, 22099), 'numpy.divide', 'np.divide', (['idctm[:, [0, -1]]', '(2)'], {}), '(idctm[:, [0, -1]], 2)\n', (22077, 22099), True, 'import numpy as np\n'), ((22722, 22742), 'numpy.divide', 'np.divide', (['fsq', 'ftmp'], {}), '(fsq, ftmp)\n', (22731, 22742), True, 'import numpy as np\n'), ((22780, 22802), 'numpy.add', 'np.add', (['fsq', '(1440000.0)'], {}), '(fsq, 1440000.0)\n', (22786, 22802), True, 'import numpy as np\n'), ((22801, 22823), 'numpy.add', 'np.add', (['fsq', '(9610000.0)'], {}), '(fsq, 9610000.0)\n', (22807, 22823), True, 'import numpy as np\n'), ((23186, 23211), 'numpy.multiply', 'np.multiply', (['win_time', 'fs'], {}), '(win_time, fs)\n', (23197, 23211), True, 'import numpy as np\n'), ((23241, 23271), 'numpy.multiply', 'np.multiply', (['hoplen_in_sec', 'fs'], {}), '(hoplen_in_sec, fs)\n', (23252, 23271), True, 'import numpy as np\n'), ((23718, 23742), 'numpy.random.randn', 'np.random.randn', (['xlen', '(1)'], {}), '(xlen, 1)\n', (23733, 23742), True, 'import numpy as np\n'), ((25985, 26016), 'scipy.signal.lfilter', 'signal.lfilter', (['vf', '(1)', 'cx_col.T'], {}), '(vf, 1, cx_col.T)\n', (25999, 26016), False, 'from scipy import signal\n'), ((787, 804), 'numpy.ceil', 'np.ceil', (['(nfft / 2)'], {}), '(nfft / 2)\n', (794, 804), True, 'import numpy as np\n'), ((1377, 1391), 'numpy.zeros', 'np.zeros', (['npad'], {}), '(npad)\n', (1385, 1391), True, 'import numpy as np\n'), ((2520, 2547), 'numpy.log2', 'np.log2', (['(winlen_in_sec * fs)'], {}), '(winlen_in_sec * fs)\n', (2527, 2547), True, 'import numpy as np\n'), ((8569, 8586), 'numpy.divide', 'np.divide', (['sum', 'n'], {}), '(sum, n)\n', (8578, 8586), True, 'import numpy as np\n'), ((10183, 10194), 'numpy.log', 'np.log', (['(6.4)'], {}), '(6.4)\n', (10189, 10194), True, 'import numpy as np\n'), ((11111, 11122), 'numpy.log', 'np.log', (['(6.4)'], {}), '(6.4)\n', (11117, 11122), True, 'import numpy as np\n'), ((13477, 13501), 'numpy.arange', 'np.arange', (['(0)', '(nfilts + 2)'], {}), '(0, nfilts + 2)\n', (13486, 13501), True, 'import numpy as np\n'), ((13626, 13641), 'numpy.arange', 'np.arange', (['(0)', '(3)'], {}), '(0, 3)\n', (13635, 13641), True, 'import numpy as np\n'), ((13735, 13769), 'numpy.subtract', 'np.subtract', (['freq_tmp', 'freq_tmp[1]'], {}), '(freq_tmp, freq_tmp[1])\n', (13746, 13769), True, 'import numpy as np\n'), ((18129, 18146), 'numpy.sqrt', 'np.sqrt', (['(2 / nrow)'], {}), '(2 / nrow)\n', (18136, 18146), True, 'import numpy as np\n'), ((18221, 18231), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (18228, 18231), True, 'import numpy as np\n'), ((18443, 18464), 'numpy.add', 'np.add', (['dctm[i, 0]', '(1)'], {}), '(dctm[i, 0], 1)\n', (18449, 18464), True, 'import numpy as np\n'), ((19698, 19715), 'numpy.ceil', 'np.ceil', (['(rows / 2)'], {}), '(rows / 2)\n', (19705, 19715), True, 'import numpy as np\n'), ((19891, 19916), 'numpy.array', 'np.array', (['ff_tmp'], {'ndmin': '(2)'}), '(ff_tmp, ndmin=2)\n', (19899, 19916), True, 'import numpy as np\n'), ((21424, 21442), 'numpy.sqrt', 'np.sqrt', (['(2 / nfreq)'], {}), '(2 / nfreq)\n', (21431, 21442), True, 'import numpy as np\n'), ((21517, 21527), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (21524, 21527), True, 'import numpy as np\n'), ((23001, 23029), 'numpy.tile', 'np.tile', (['eql.T', '(nframes, 1)'], {}), '(eql.T, (nframes, 1))\n', (23008, 23029), True, 'import numpy as np\n'), ((25192, 25210), 'numpy.sqrt', 'np.sqrt', (['aspectrum'], {}), '(aspectrum)\n', (25199, 25210), True, 'import numpy as np\n'), ((5071, 5089), 'numpy.divide', 'np.divide', (['nfft', '(2)'], {}), '(nfft, 2)\n', (5080, 5089), True, 'import numpy as np\n'), ((8472, 8504), 'numpy.multiply', 'np.multiply', (['(n - m)', 'norm_a[m, :]'], {}), '(n - m, norm_a[m, :])\n', (8483, 8504), True, 'import numpy as np\n'), ((9670, 9687), 'numpy.divide', 'np.divide', (['f', '(700)'], {}), '(f, 700)\n', (9679, 9687), True, 'import numpy as np\n'), ((10887, 10905), 'numpy.divide', 'np.divide', (['z', '(2595)'], {}), '(z, 2595)\n', (10896, 10905), True, 'import numpy as np\n'), ((16442, 16463), 'numpy.sqrt', 'np.sqrt', (['p_spectrum.T'], {}), '(p_spectrum.T)\n', (16449, 16463), True, 'import numpy as np\n'), ((18538, 18553), 'numpy.power', 'np.power', (['(-1)', 'i'], {}), '(-1, i)\n', (18546, 18553), True, 'import numpy as np\n'), ((19621, 19638), 'numpy.matmul', 'np.matmul', (['zz', 'aa'], {}), '(zz, aa)\n', (19630, 19638), True, 'import numpy as np\n'), ((20386, 20417), 'numpy.append', 'np.append', (['tmp_F_list', 'dummy[i]'], {}), '(tmp_F_list, dummy[i])\n', (20395, 20417), True, 'import numpy as np\n'), ((20451, 20485), 'numpy.append', 'np.append', (['tmp_M_list', 'mags[ix[i]]'], {}), '(tmp_M_list, mags[ix[i]])\n', (20460, 20485), True, 'import numpy as np\n'), ((23319, 23333), 'numpy.log', 'np.log', (['winpts'], {}), '(winpts)\n', (23325, 23333), True, 'import numpy as np\n'), ((23335, 23344), 'numpy.log', 'np.log', (['(2)'], {}), '(2)\n', (23341, 23344), True, 'import numpy as np\n'), ((25036, 25054), 'numpy.sum', 'np.sum', (['ww'], {'axis': '(0)'}), '(ww, axis=0)\n', (25042, 25054), True, 'import numpy as np\n'), ((5515, 5537), 'numpy.multiply', 'np.multiply', (['(-2.5)', 'lof'], {}), '(-2.5, lof)\n', (5526, 5537), True, 'import numpy as np\n'), ((10470, 10491), 'numpy.log', 'np.log', (['(f[i] / brkfrq)'], {}), '(f[i] / brkfrq)\n', (10476, 10491), True, 'import numpy as np\n'), ((10494, 10509), 'numpy.log', 'np.log', (['logstep'], {}), '(logstep)\n', (10500, 10509), True, 'import numpy as np\n'), ((11678, 11693), 'numpy.log', 'np.log', (['logstep'], {}), '(logstep)\n', (11684, 11693), True, 'import numpy as np\n'), ((19984, 20010), 'numpy.arange', 'np.arange', (['(0)', 'aaa.shape[0]'], {}), '(0, aaa.shape[0])\n', (19993, 20010), True, 'import numpy as np\n'), ((24969, 24980), 'numpy.diag', 'np.diag', (['ww'], {}), '(ww)\n', (24976, 24980), True, 'import numpy as np\n'), ((18084, 18109), 'numpy.arange', 'np.arange', (['(1)', '(2 * nrow)', '(2)'], {}), '(1, 2 * nrow, 2)\n', (18093, 18109), True, 'import numpy as np\n'), ((21306, 21332), 'numpy.arange', 'np.arange', (['(1)', '(2 * nfreq)', '(2)'], {}), '(1, 2 * nfreq, 2)\n', (21315, 21332), True, 'import numpy as np\n'), ((18368, 18390), 'numpy.arange', 'np.arange', (['(1)', '(nrow + 1)'], {}), '(1, nrow + 1)\n', (18377, 18390), True, 'import numpy as np\n'), ((18734, 18752), 'numpy.arange', 'np.arange', (['(0)', 'nrow'], {}), '(0, nrow)\n', (18743, 18752), True, 'import numpy as np\n'), ((20106, 20128), 'numpy.array', 'np.array', (['aaa'], {'ndmin': '(2)'}), '(aaa, ndmin=2)\n', (20114, 20128), True, 'import numpy as np\n'), ((21753, 21776), 'numpy.arange', 'np.arange', (['(1)', '(nfreq + 1)'], {}), '(1, nfreq + 1)\n', (21762, 21776), True, 'import numpy as np\n'), ((21989, 22008), 'numpy.arange', 'np.arange', (['(0)', 'nfreq'], {}), '(0, nfreq)\n', (21998, 22008), True, 'import numpy as np\n')]
|
import numpy as np
initial_state = globals().copy()
non_element_functions = ['element_metadata',
'initial_state',
'non_element_functions',
'typeChecker',
'circuit_elements']
# populated at the end of the file -
# this maps ex. 'R' to the function R to always give us a list of
# active elements in any context
circuit_elements = {}
def element_metadata(num_params, units):
""" decorator to store metadata for a circuit element
Parameters
----------
num_params : int
number of parameters for an element
units : list of str
list of units for the element parameters
"""
def decorator(func):
def wrapper(p, f):
typeChecker(p, f, func.__name__, num_params)
return func(p, f)
wrapper.num_params = num_params
wrapper.units = units
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
return wrapper
return decorator
def s(series):
""" sums elements in series
Notes
---------
.. math::
Z = Z_1 + Z_2 + ... + Z_n
"""
z = len(series[0])*[0 + 0*1j]
for elem in series:
z += elem
return z
def p(parallel):
""" adds elements in parallel
Notes
---------
.. math::
Z = \\frac{1}{\\frac{1}{Z_1} + \\frac{1}{Z_2} + ... + \\frac{1}{Z_n}}
"""
z = len(parallel[0])*[0 + 0*1j]
for elem in parallel:
z += 1/elem
return 1/z
@element_metadata(num_params=1, units=['Ohm'])
def R(p, f):
""" defines a resistor
Notes
---------
.. math::
Z = R
"""
return np.array(len(f)*[p[0]])
@element_metadata(num_params=1, units=['F'])
def C(p, f):
""" defines a capacitor
.. math::
Z = \\frac{1}{C \\times j 2 \\pi f}
"""
omega = 2*np.pi*np.array(f)
return 1.0/(p[0]*1j*omega)
@element_metadata(num_params=1, units=['H'])
def L(p, f):
""" defines an inductor
.. math::
Z = L \\times j 2 \\pi f
"""
omega = 2*np.pi*np.array(f)
return p[0]*1j*omega
@element_metadata(num_params=1, units=['Ohm sec^-1/2'])
def W(p, f):
""" defines a semi-infinite Warburg element
Notes
-----
.. math::
Z = \\frac{A_W}{\\sqrt{ 2 \\pi f}} (1-j)
"""
omega = 2*np.pi*np.array(f)
Aw = p[0]
Zw = Aw*(1-1j)/np.sqrt(omega)
return Zw
@element_metadata(num_params=2, units=['Ohm', 'sec'])
def Wo(p, f):
""" defines an open (finite-space) Warburg element
Notes
---------
.. math::
Z = \\frac{Z_0}{\\sqrt{ j \\omega \\tau }}
\\coth{\\sqrt{j \\omega \\tau }}
where :math:`Z_0` = p[0] (Ohms) and
:math:`\\tau` = p[1] (sec) = :math:`\\frac{L^2}{D}`
"""
omega = 2*np.pi*np.array(f)
Z0, tau = p[0], p[1]
Z = Z0/(np.sqrt(1j*omega*tau)*np.tanh(np.sqrt(1j*omega*tau)))
return Z # Zw(omega)
@element_metadata(num_params=2, units=['Ohm', 'sec'])
def Ws(p, f):
""" defines a short (finite-length) Warburg element
Notes
---------
.. math::
Z = \\frac{Z_0}{\\sqrt{ j \\omega \\tau }}
\\tanh{\\sqrt{j \\omega \\tau }}
where :math:`Z_0` = p[0] (Ohms) and
:math:`\\tau` = p[1] (sec) = :math:`\\frac{L^2}{D}`
"""
omega = 2*np.pi*np.array(f)
Z0, tau = p[0], p[1]
Z = Z0*np.tanh(np.sqrt(1j*omega*tau))/np.sqrt(1j*omega*tau)
return Z
@element_metadata(num_params=2, units=['Ohm^-1 sec^a', ''])
def CPE(p, f):
""" defines a constant phase element
Notes
-----
.. math::
Z = \\frac{1}{Q \\times (j 2 \\pi f)^\\alpha}
where :math:`Q` = p[0] and :math:`\\alpha` = p[1].
"""
omega = 2*np.pi*np.array(f)
Q, alpha = p
return 1.0/(Q*(1j*omega)**alpha)
@element_metadata(num_params=2, units=['Ohm', 'sec'])
def G(p, f):
""" defines a Gerischer Element as represented in [1]
Notes
---------
.. math::
Z = \\frac{R_G}{\\sqrt{1 + j \\, 2 \\pi f \\, t_G}}
where :math:`R_G` = p[0] and :math:`t_G` = p[1]
Gerischer impedance is also commonly represented as [2]:
.. math::
Z = \\frac{Z_o}{\\sqrt{K+ j \\, 2 \\pi f}}
where :math:`Z_o = \\frac{R_G}{\\sqrt{t_G}}`
and :math:`K = \\frac{1}{t_G}`
with units :math:`\\Omega sec^{1/2}` and
:math:`sec^{-1}` , respectively.
[1] <NAME>, <NAME>, and <NAME>,
Journal of The Electrochemical Society, 156, B513-B525 (2009)
`doi:10.1149/1.3079337
<https://doi.org/10.1149/1.3079337>`_.
[2] <NAME>, <NAME>, <NAME>,
<NAME>, and <NAME>, <NAME>, 1,
256-264 (2001) `doi:10.1016/0013-4686(93)85083-B
<https://doi.org/10.1016/0013-4686(93)85083-B>`_.
"""
omega = 2*np.pi*np.array(f)
R_G, t_G = p
return R_G/np.sqrt(1 + 1j*omega*t_G)
@element_metadata(num_params=3, units=['Ohm', 'sec', ''])
def Gs(p, f):
""" defines a finite-length Gerischer Element as represented in [1]
Notes
---------
.. math::
Z = \\frac{R_G}{\\sqrt{1 + j \\, 2 \\pi f \\, t_G} \\,
tanh(\\phi \\sqrt{1 + j \\, 2 \\pi f \\, t_G})}
where :math:`R_G` = p[0], :math:`t_G` = p[1] and :math:`\\phi` = p[2]
[1] <NAME>, <NAME>, and <NAME>,
Solid State Ionics, 179, 647-660 (2008)
`doi:10.1016/j.ssi.2008.04.024
<https://doi.org/10.1016/j.ssi.2008.04.024>`_.
"""
omega = 2*np.pi*np.array(f)
R_G, t_G, phi = p
Z = R_G/(np.sqrt(1 + 1j*omega*t_G) *
np.tanh(phi * np.sqrt(1 + 1j*omega*t_G)))
return Z
@element_metadata(num_params=2, units=['Ohm', 'sec'])
def K(p, f):
""" An RC element for use in lin-KK model
Notes
-----
.. math::
Z = \\frac{R}{1 + j \\omega \\tau_k}
"""
omega = 2*np.pi*np.array(f)
return p[0]/(1 + 1j*omega*p[1])
@element_metadata(num_params=4, units=['Ohm-m^2', 'Ohm-m^2', '', 'sec'])
def T(p, f):
""" A macrohomogeneous porous electrode model from Paasch et al. [1]
Notes
-----
.. math::
Z = A\\frac{\\coth{\\beta}}{\\beta} + B\\frac{1}{\\beta\\sinh{\\beta}}
where
.. math::
A = d\\frac{\\rho_1^2 + \\rho_2^2}{\\rho_1 + \\rho_2} \\quad
B = d\\frac{2 \\rho_1 \\rho_2}{\\rho_1 + \\rho_2}
and
.. math::
\\beta = (a + j \\omega b)^{1/2} \\quad
a = \\frac{k d^2}{K} \\quad b = \\frac{d^2}{K}
[1] <NAME>, <NAME>, and <NAME>,
Electrochimica Acta, 38, 2653–2662 (1993)
`doi: 10.1016/0013-4686(93)85083-B
<https://doi.org/10.1016/0013-4686(93)85083-B>`_.
"""
omega = 2*np.pi*np.array(f)
A, B, a, b = p
beta = (a + 1j*omega*b)**(1/2)
sinh = []
for x in beta:
if x < 100:
sinh.append(np.sinh(x))
else:
sinh.append(1e10)
return A/(beta*np.tanh(beta)) + B/(beta*np.array(sinh))
circuit_elements = {key: eval(key) for key in set(globals())-set(initial_state)
if key not in non_element_functions}
def get_element_from_name(name):
excluded_chars = '0123456789_'
return ''.join(char for char in name if char not in excluded_chars)
def typeChecker(p, f, name, length):
assert isinstance(p, list), \
'in {}, input must be of type list'.format(name)
for i in p:
assert isinstance(i, (float, int, np.int32, np.float64)), \
'in {}, value {} in {} is not a number'.format(name, i, p)
for i in f:
assert isinstance(i, (float, int, np.int32, np.float64)), \
'in {}, value {} in {} is not a number'.format(name, i, f)
assert len(p) == length, \
'in {}, input list must be length {}'.format(name, length)
return
|
[
"numpy.sinh",
"numpy.array",
"numpy.tanh",
"numpy.sqrt"
] |
[((1933, 1944), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (1941, 1944), True, 'import numpy as np\n'), ((2143, 2154), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (2151, 2154), True, 'import numpy as np\n'), ((2412, 2423), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (2420, 2423), True, 'import numpy as np\n'), ((2457, 2471), 'numpy.sqrt', 'np.sqrt', (['omega'], {}), '(omega)\n', (2464, 2471), True, 'import numpy as np\n'), ((2868, 2879), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (2876, 2879), True, 'import numpy as np\n'), ((3382, 3393), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (3390, 3393), True, 'import numpy as np\n'), ((3462, 3489), 'numpy.sqrt', 'np.sqrt', (['(1.0j * omega * tau)'], {}), '(1.0j * omega * tau)\n', (3469, 3489), True, 'import numpy as np\n'), ((3790, 3801), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (3798, 3801), True, 'import numpy as np\n'), ((4809, 4820), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (4817, 4820), True, 'import numpy as np\n'), ((4853, 4884), 'numpy.sqrt', 'np.sqrt', (['(1 + 1.0j * omega * t_G)'], {}), '(1 + 1.0j * omega * t_G)\n', (4860, 4884), True, 'import numpy as np\n'), ((5455, 5466), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (5463, 5466), True, 'import numpy as np\n'), ((5824, 5835), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (5832, 5835), True, 'import numpy as np\n'), ((6635, 6646), 'numpy.array', 'np.array', (['f'], {}), '(f)\n', (6643, 6646), True, 'import numpy as np\n'), ((2918, 2945), 'numpy.sqrt', 'np.sqrt', (['(1.0j * omega * tau)'], {}), '(1.0j * omega * tau)\n', (2925, 2945), True, 'import numpy as np\n'), ((5503, 5534), 'numpy.sqrt', 'np.sqrt', (['(1 + 1.0j * omega * t_G)'], {}), '(1 + 1.0j * omega * t_G)\n', (5510, 5534), True, 'import numpy as np\n'), ((2948, 2975), 'numpy.sqrt', 'np.sqrt', (['(1.0j * omega * tau)'], {}), '(1.0j * omega * tau)\n', (2955, 2975), True, 'import numpy as np\n'), ((3439, 3466), 'numpy.sqrt', 'np.sqrt', (['(1.0j * omega * tau)'], {}), '(1.0j * omega * tau)\n', (3446, 3466), True, 'import numpy as np\n'), ((6779, 6789), 'numpy.sinh', 'np.sinh', (['x'], {}), '(x)\n', (6786, 6789), True, 'import numpy as np\n'), ((6855, 6868), 'numpy.tanh', 'np.tanh', (['beta'], {}), '(beta)\n', (6862, 6868), True, 'import numpy as np\n'), ((6880, 6894), 'numpy.array', 'np.array', (['sinh'], {}), '(sinh)\n', (6888, 6894), True, 'import numpy as np\n'), ((5558, 5589), 'numpy.sqrt', 'np.sqrt', (['(1 + 1.0j * omega * t_G)'], {}), '(1 + 1.0j * omega * t_G)\n', (5565, 5589), True, 'import numpy as np\n')]
|
import random
import time
from copy import deepcopy
import gym
import networkx as nx
import numpy as np
from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple
class MyTestEnv(gym.Env):
"""This is a "going right" task. The task is to go right ``size`` steps.
"""
def __init__(
self,
size,
sleep=0,
dict_state=False,
recurse_state=False,
ma_rew=0,
multidiscrete_action=False,
random_sleep=False,
array_state=False
):
assert dict_state + recurse_state + array_state <= 1, \
"dict_state / recurse_state / array_state can be only one true"
self.size = size
self.sleep = sleep
self.random_sleep = random_sleep
self.dict_state = dict_state
self.recurse_state = recurse_state
self.array_state = array_state
self.ma_rew = ma_rew
self._md_action = multidiscrete_action
# how many steps this env has stepped
self.steps = 0
if dict_state:
self.observation_space = Dict(
{
"index": Box(shape=(1, ), low=0, high=size - 1),
"rand": Box(shape=(1, ), low=0, high=1, dtype=np.float64)
}
)
elif recurse_state:
self.observation_space = Dict(
{
"index":
Box(shape=(1, ), low=0, high=size - 1),
"dict":
Dict(
{
"tuple":
Tuple(
(
Discrete(2),
Box(shape=(2, ), low=0, high=1, dtype=np.float64)
)
),
"rand":
Box(shape=(1, 2), low=0, high=1, dtype=np.float64)
}
)
}
)
elif array_state:
self.observation_space = Box(shape=(4, 84, 84), low=0, high=255)
else:
self.observation_space = Box(shape=(1, ), low=0, high=size - 1)
if multidiscrete_action:
self.action_space = MultiDiscrete([2, 2])
else:
self.action_space = Discrete(2)
self.done = False
self.index = 0
self.seed()
def seed(self, seed=0):
self.rng = np.random.RandomState(seed)
return [seed]
def reset(self, state=0):
self.done = False
self.do_sleep()
self.index = state
return self._get_state()
def _get_reward(self):
"""Generate a non-scalar reward if ma_rew is True."""
end_flag = int(self.done)
if self.ma_rew > 0:
return [end_flag] * self.ma_rew
return end_flag
def _get_state(self):
"""Generate state(observation) of MyTestEnv"""
if self.dict_state:
return {
'index': np.array([self.index], dtype=np.float32),
'rand': self.rng.rand(1)
}
elif self.recurse_state:
return {
'index': np.array([self.index], dtype=np.float32),
'dict': {
"tuple": (np.array([1], dtype=int), self.rng.rand(2)),
"rand": self.rng.rand(1, 2)
}
}
elif self.array_state:
img = np.zeros([4, 84, 84], int)
img[3, np.arange(84), np.arange(84)] = self.index
img[2, np.arange(84)] = self.index
img[1, :, np.arange(84)] = self.index
img[0] = self.index
return img
else:
return np.array([self.index], dtype=np.float32)
def do_sleep(self):
if self.sleep > 0:
sleep_time = random.random() if self.random_sleep else 1
sleep_time *= self.sleep
time.sleep(sleep_time)
def step(self, action):
self.steps += 1
if self._md_action:
action = action[0]
if self.done:
raise ValueError('step after done !!!')
self.do_sleep()
if self.index == self.size:
self.done = True
return self._get_state(), self._get_reward(), self.done, {}
if action == 0:
self.index = max(self.index - 1, 0)
return self._get_state(), self._get_reward(), self.done, \
{'key': 1, 'env': self} if self.dict_state else {}
elif action == 1:
self.index += 1
self.done = self.index == self.size
return self._get_state(), self._get_reward(), \
self.done, {'key': 1, 'env': self}
class NXEnv(gym.Env):
def __init__(self, size, obs_type, feat_dim=32):
self.size = size
self.feat_dim = feat_dim
self.graph = nx.Graph()
self.graph.add_nodes_from(list(range(size)))
assert obs_type in ["array", "object"]
self.obs_type = obs_type
def _encode_obs(self):
if self.obs_type == "array":
return np.stack([v["data"] for v in self.graph._node.values()])
return deepcopy(self.graph)
def reset(self):
graph_state = np.random.rand(self.size, self.feat_dim)
for i in range(self.size):
self.graph.nodes[i]["data"] = graph_state[i]
return self._encode_obs()
def step(self, action):
next_graph_state = np.random.rand(self.size, self.feat_dim)
for i in range(self.size):
self.graph.nodes[i]["data"] = next_graph_state[i]
return self._encode_obs(), 1.0, 0, {}
|
[
"copy.deepcopy",
"gym.spaces.Discrete",
"numpy.zeros",
"numpy.random.RandomState",
"gym.spaces.MultiDiscrete",
"time.sleep",
"random.random",
"networkx.Graph",
"numpy.array",
"gym.spaces.Box",
"numpy.arange",
"numpy.random.rand"
] |
[((2491, 2518), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (2512, 2518), True, 'import numpy as np\n'), ((4941, 4951), 'networkx.Graph', 'nx.Graph', ([], {}), '()\n', (4949, 4951), True, 'import networkx as nx\n'), ((5241, 5261), 'copy.deepcopy', 'deepcopy', (['self.graph'], {}), '(self.graph)\n', (5249, 5261), False, 'from copy import deepcopy\n'), ((5306, 5346), 'numpy.random.rand', 'np.random.rand', (['self.size', 'self.feat_dim'], {}), '(self.size, self.feat_dim)\n', (5320, 5346), True, 'import numpy as np\n'), ((5529, 5569), 'numpy.random.rand', 'np.random.rand', (['self.size', 'self.feat_dim'], {}), '(self.size, self.feat_dim)\n', (5543, 5569), True, 'import numpy as np\n'), ((2294, 2315), 'gym.spaces.MultiDiscrete', 'MultiDiscrete', (['[2, 2]'], {}), '([2, 2])\n', (2307, 2315), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((2362, 2373), 'gym.spaces.Discrete', 'Discrete', (['(2)'], {}), '(2)\n', (2370, 2373), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((3991, 4013), 'time.sleep', 'time.sleep', (['sleep_time'], {}), '(sleep_time)\n', (4001, 4013), False, 'import time\n'), ((3058, 3098), 'numpy.array', 'np.array', (['[self.index]'], {'dtype': 'np.float32'}), '([self.index], dtype=np.float32)\n', (3066, 3098), True, 'import numpy as np\n'), ((3898, 3913), 'random.random', 'random.random', ([], {}), '()\n', (3911, 3913), False, 'import random\n'), ((1127, 1164), 'gym.spaces.Box', 'Box', ([], {'shape': '(1,)', 'low': '(0)', 'high': '(size - 1)'}), '(shape=(1,), low=0, high=size - 1)\n', (1130, 1164), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((1195, 1243), 'gym.spaces.Box', 'Box', ([], {'shape': '(1,)', 'low': '(0)', 'high': '(1)', 'dtype': 'np.float64'}), '(shape=(1,), low=0, high=1, dtype=np.float64)\n', (1198, 1243), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((2099, 2138), 'gym.spaces.Box', 'Box', ([], {'shape': '(4, 84, 84)', 'low': '(0)', 'high': '(255)'}), '(shape=(4, 84, 84), low=0, high=255)\n', (2102, 2138), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((2190, 2227), 'gym.spaces.Box', 'Box', ([], {'shape': '(1,)', 'low': '(0)', 'high': '(size - 1)'}), '(shape=(1,), low=0, high=size - 1)\n', (2193, 2227), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((3234, 3274), 'numpy.array', 'np.array', (['[self.index]'], {'dtype': 'np.float32'}), '([self.index], dtype=np.float32)\n', (3242, 3274), True, 'import numpy as np\n'), ((3506, 3532), 'numpy.zeros', 'np.zeros', (['[4, 84, 84]', 'int'], {}), '([4, 84, 84], int)\n', (3514, 3532), True, 'import numpy as np\n'), ((3780, 3820), 'numpy.array', 'np.array', (['[self.index]'], {'dtype': 'np.float32'}), '([self.index], dtype=np.float32)\n', (3788, 3820), True, 'import numpy as np\n'), ((1415, 1452), 'gym.spaces.Box', 'Box', ([], {'shape': '(1,)', 'low': '(0)', 'high': '(size - 1)'}), '(shape=(1,), low=0, high=size - 1)\n', (1418, 1452), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((3332, 3356), 'numpy.array', 'np.array', (['[1]'], {'dtype': 'int'}), '([1], dtype=int)\n', (3340, 3356), True, 'import numpy as np\n'), ((3552, 3565), 'numpy.arange', 'np.arange', (['(84)'], {}), '(84)\n', (3561, 3565), True, 'import numpy as np\n'), ((3567, 3580), 'numpy.arange', 'np.arange', (['(84)'], {}), '(84)\n', (3576, 3580), True, 'import numpy as np\n'), ((3614, 3627), 'numpy.arange', 'np.arange', (['(84)'], {}), '(84)\n', (3623, 3627), True, 'import numpy as np\n'), ((3664, 3677), 'numpy.arange', 'np.arange', (['(84)'], {}), '(84)\n', (3673, 3677), True, 'import numpy as np\n'), ((1905, 1955), 'gym.spaces.Box', 'Box', ([], {'shape': '(1, 2)', 'low': '(0)', 'high': '(1)', 'dtype': 'np.float64'}), '(shape=(1, 2), low=0, high=1, dtype=np.float64)\n', (1908, 1955), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((1677, 1688), 'gym.spaces.Discrete', 'Discrete', (['(2)'], {}), '(2)\n', (1685, 1688), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n'), ((1726, 1774), 'gym.spaces.Box', 'Box', ([], {'shape': '(2,)', 'low': '(0)', 'high': '(1)', 'dtype': 'np.float64'}), '(shape=(2,), low=0, high=1, dtype=np.float64)\n', (1729, 1774), False, 'from gym.spaces import Box, Dict, Discrete, MultiDiscrete, Tuple\n')]
|
# Based on https://colab.research.google.com/github/reiinakano/neural-painters/blob/master/notebooks/generate_stroke_examples.ipynb
from lib import surface, tiledsurface, brush
import torch
import numpy as np
from PIL import Image
def point_on_curve_1(t, cx, cy, sx, sy, x1, y1, x2, y2):
ratio = t / 100.0
x3, y3 = multiply_add(sx, sy, x1, y1, ratio)
x4, y4 = multiply_add(cx, cy, x2, y2, ratio)
x5, y5 = difference(x3, y3, x4, y4)
x, y = multiply_add(x3, y3, x5, y5, ratio)
return x, y
def length_and_normal(x1, y1, x2, y2):
x, y = difference(x1, y1, x2, y2)
length = np.sqrt(x * x + y * y)
if length == 0.0:
x, y = 0.0, 0.0
else:
x, y = x / length, y / length
return length, x, y
def multiply_add(x1, y1, x2, y2, d):
x3, y3 = multiply(x2, y2, d)
x, y = add(x1, y1, x3, y3)
return x, y
def multiply(x, y, d):
# Multiply vector
x = x * d
y = y * d
return x, y
def add(x1, y1, x2, y2):
# Add vectors
x = x1 + x2
y = y1 + y2
return x, y
def difference(x1, y1, x2, y2):
# Difference in x and y between two points
x = x2 - x1
y = y2 - y1
return x, y
def midpoint(x1, y1, x2, y2):
# Midpoint between 2 points
x = (x1 + x2) / 2.0
y = (y1 + y2) / 2.0
return x, y
class MyPaintImagesDataLoader:
def __init__(self, H=32, W=32):
self.rng = np.random.default_rng(42)
self.head = 0.25
self.tail = 0.75
self.surface = tiledsurface.Surface()
with open("gan_stroke_generator/brushes/classic/dry_brush.myb") as brush_file:
self.brush_info = brush.BrushInfo(brush_file.read())
self.brush = brush.Brush(self.brush_info)
self.H = H
self.W = W
self.num_action = 9
self.num_images = int(10e9)
def _stroke_to(self, x, y, pressure):
duration = 0.1
self.brush.stroke_to(
self.surface.backend, x, y, pressure, 0.0, 0.0, duration, 0.0, 0.0, 0.0
)
self.surface.end_atomic()
self.surface.begin_atomic()
def _line_settings(self, entry_pressure, pressure):
p2 = (entry_pressure + pressure) / 2
prange1 = p2 - entry_pressure
prange2 = pressure - p2
return p2, prange1, prange2
def curve(
self, control_x, control_y, start_x, start_y, ex, ey, entry_pressure, pressure
):
(
midpoint_p,
prange1,
prange2,
) = self._line_settings(entry_pressure, pressure)
points_in_curve = 100
mx, my = midpoint(start_x, start_y, ex, ey)
length, nx, ny = length_and_normal(mx, my, control_x, control_y)
cx, cy = multiply_add(mx, my, nx, ny, length * 2)
x1, y1 = difference(start_x, start_y, cx, cy)
x2, y2 = difference(cx, cy, ex, ey)
head = points_in_curve * self.head
head_range = int(head) + 1
tail = points_in_curve * self.tail
tail_range = int(tail) + 1
tail_length = points_in_curve - tail
# Beginning
px, py = point_on_curve_1(1, cx, cy, start_x, start_y, x1, y1, x2, y2)
length, nx, ny = length_and_normal(start_x, start_y, px, py)
bx, by = multiply_add(start_x, start_y, nx, ny, 0.25)
self._stroke_to(bx, by, entry_pressure)
pressure = abs(1 / head * prange1 + entry_pressure)
self._stroke_to(px, py, pressure)
for i in range(2, head_range):
px, py = point_on_curve_1(i, cx, cy, start_x, start_y, x1, y1, x2, y2)
pressure = abs(i / head * prange1 + entry_pressure)
self._stroke_to(px, py, pressure)
# Middle
for i in range(head_range, tail_range):
px, py = point_on_curve_1(i, cx, cy, start_x, start_y, x1, y1, x2, y2)
self._stroke_to(px, py, midpoint_p)
# End
for i in range(tail_range, points_in_curve + 1):
px, py = point_on_curve_1(i, cx, cy, start_x, start_y, x1, y1, x2, y2)
pressure = abs((i - tail) / tail_length * prange2 + midpoint_p)
self._stroke_to(px, py, pressure)
return pressure
def draw_stroke(
self,
start_x,
start_y,
end_x,
end_y,
control_x,
control_y,
entry_pressure,
pressure,
size,
color_rgb,
):
start_x = start_x * self.H
start_y = start_y * self.W
end_x = end_x * self.H
end_y = end_y * self.W
control_x = control_x * self.H
control_y = control_y * self.W
self.brush.brushinfo.set_color_rgb(color_rgb)
self.brush.brushinfo.set_base_value("radius_logarithmic", size)
# Move brush to starting point without leaving it on the canvas.
self._stroke_to(start_x, start_y, 0)
self.curve(
control_x,
control_y,
start_x,
start_y,
end_x,
end_y,
entry_pressure,
pressure,
)
# Relieve brush pressure for next jump
self._stroke_to(end_x, end_y, 0)
self.surface.end_atomic()
self.surface.begin_atomic()
def get_mypaint_image(
self,
start_x,
start_y,
end_x,
end_y,
control_x,
control_y,
entry_pressure,
pressure,
size,
color_rgb,
):
self.draw_stroke(
start_x,
start_y,
end_x,
end_y,
control_x,
control_y,
entry_pressure,
pressure,
size,
color_rgb,
)
rect = [0, 0, self.H, self.W]
scanline_strips = surface.scanline_strips_iter(self.surface, rect, single_tile_pattern=True)
img = next(scanline_strips)
self.surface.clear()
self.surface.end_atomic()
self.surface.begin_atomic()
return img
def random_action(self):
return self.rng.uniform(size=[self.num_action])
def __len__(self):
return self.num_images
def __iter__(self):
for _ in range(self.num_images):
action = self.random_action()
img = self.get_mypaint_image(
start_x=action[0],
start_y=action[1],
end_x=action[2],
end_y=action[3],
control_x=action[4],
control_y=action[5],
pressure=action[6],
entry_pressure=action[7],
size=action[8],
color_rgb=[1, 1, 1],
)
img = Image.fromarray(img).convert('L')
# We need to create batch of size 1
img = np.expand_dims(img, axis=0)
# We need to create a channel for img
img = np.expand_dims(img, axis=0)
action = np.expand_dims(action, axis=0)
yield {
"stroke": torch.from_numpy(img.astype(float) / 255.0),
"action": torch.from_numpy(action),
}
|
[
"torch.from_numpy",
"lib.tiledsurface.Surface",
"lib.brush.Brush",
"lib.surface.scanline_strips_iter",
"numpy.expand_dims",
"numpy.random.default_rng",
"PIL.Image.fromarray",
"numpy.sqrt"
] |
[((607, 629), 'numpy.sqrt', 'np.sqrt', (['(x * x + y * y)'], {}), '(x * x + y * y)\n', (614, 629), True, 'import numpy as np\n'), ((1396, 1421), 'numpy.random.default_rng', 'np.random.default_rng', (['(42)'], {}), '(42)\n', (1417, 1421), True, 'import numpy as np\n'), ((1495, 1517), 'lib.tiledsurface.Surface', 'tiledsurface.Surface', ([], {}), '()\n', (1515, 1517), False, 'from lib import surface, tiledsurface, brush\n'), ((1691, 1719), 'lib.brush.Brush', 'brush.Brush', (['self.brush_info'], {}), '(self.brush_info)\n', (1702, 1719), False, 'from lib import surface, tiledsurface, brush\n'), ((5742, 5816), 'lib.surface.scanline_strips_iter', 'surface.scanline_strips_iter', (['self.surface', 'rect'], {'single_tile_pattern': '(True)'}), '(self.surface, rect, single_tile_pattern=True)\n', (5770, 5816), False, 'from lib import surface, tiledsurface, brush\n'), ((6752, 6779), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (6766, 6779), True, 'import numpy as np\n'), ((6848, 6875), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(0)'}), '(img, axis=0)\n', (6862, 6875), True, 'import numpy as np\n'), ((6897, 6927), 'numpy.expand_dims', 'np.expand_dims', (['action'], {'axis': '(0)'}), '(action, axis=0)\n', (6911, 6927), True, 'import numpy as np\n'), ((6652, 6672), 'PIL.Image.fromarray', 'Image.fromarray', (['img'], {}), '(img)\n', (6667, 6672), False, 'from PIL import Image\n'), ((7045, 7069), 'torch.from_numpy', 'torch.from_numpy', (['action'], {}), '(action)\n', (7061, 7069), False, 'import torch\n')]
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from numba import f8
from numba import i8
from numba import jit
from numba import prange
from numpy import argmin
from numpy import array
from numpy import empty
from numpy import min
from numpy.random import rand
from numpy.random import choice
__author__ = ['<NAME> <<EMAIL>>']
__copyright__ = 'Copyright 2017, BLOCK Research Group - ETH Zurich'
__license__ = 'MIT License'
__email__ = '<EMAIL>'
__all__ = [
'devo_numba',
]
args = 0
@jit(nogil=True, nopython=True, parallel=True)
def _fn(u, args):
# Booth's function, fopt=0, uopt=(1, 3)
x = u[0]
y = u[1]
z = (x + 2 * y - 7)**2 + (2 * x + y - 5)**2
return z
@jit((f8[:, :], i8, i8), nogil=True, nopython=True, parallel=False)
def devo_numba(bounds, population, generations):
""" Call the Numba accelerated Differential Evolution solver.
Parameters:
bounds (array): Lower and upper bounds for each DoF.
population (int): Number of agents in the population.
generations (int): Number of cross-over cycles/steps to perform.
F (float): Differential evolution parameter.
CR (float): Differential evolution cross-over ratio parameter.
Returns:
array: Values that give the optimum (minimised) function.
"""
# Heading
print('\n---------------------------------')
print('Differential Evolution started...')
print('---------------------------------')
F = 0.8
CR = 0.9
# Setup population
k = bounds.shape[0]
agents = rand(k, population)
for i in prange(k):
for j in prange(population):
agents[i, j] *= bounds[i, 1] - bounds[i, 0]
agents[i, j] += bounds[i, 0]
candidates = empty((population, population - 1))
for i in prange(population):
c = 0
for j in prange(population - 1):
if j == i:
c += 1
candidates[i, j] = c
c += 1
# Initial conditions
f = empty(population)
for i in prange(population):
f[i] = _fn(agents[:, i], args)
fopt = min(f)
agents_ = empty((k, population))
ts = 0
print('\nGeneration: ', ts, ' fopt: ', fopt)
# Start evolution
while ts < generations + 1:
ind = rand(k, population) < CR
for i in prange(population):
choices = choice(population - 1, 3, replace=False)
ind0 = int(candidates[i, choices[0]])
ind1 = int(candidates[i, choices[1]])
ind2 = int(candidates[i, choices[2]])
ac = agents[:, ind0]
bc = agents[:, ind1]
cc = agents[:, ind2]
for j in prange(k):
if ind[j, i]:
val = ac[j] + F * (bc[j] - cc[j])
if val < bounds[j, 0]:
val = bounds[j, 0]
elif val > bounds[j, 1]:
val = bounds[j, 1]
agents_[j, i] = val
else:
agents_[j, i] = agents[j, i]
f_ = _fn(agents_[:, i], args)
if f_ < f[i]:
agents[:, i] = agents_[:, i]
f[i] = f_
fopt = min(f)
xopt = agents[:, argmin(f)]
ts += 1
print('Generation: ', ts, ' fopt: ', fopt)
# Summary
print('\n-------------------------------')
print('Differential Evolution finished')
print('fopt: ', fopt)
print('-------------------------------')
return xopt
# ==============================================================================
# Main
# ==============================================================================
if __name__ == "__main__":
from time import time
tic = time()
bounds = array([[-10., 10.], [-10., 10.]])
devo_numba(bounds=bounds, population=1000, generations=1000)
print(time() - tic)
|
[
"numpy.random.choice",
"numpy.empty",
"numpy.argmin",
"time.time",
"numpy.min",
"numba.jit",
"numpy.array",
"numba.prange",
"numpy.random.rand"
] |
[((568, 613), 'numba.jit', 'jit', ([], {'nogil': '(True)', 'nopython': '(True)', 'parallel': '(True)'}), '(nogil=True, nopython=True, parallel=True)\n', (571, 613), False, 'from numba import jit\n'), ((766, 832), 'numba.jit', 'jit', (['(f8[:, :], i8, i8)'], {'nogil': '(True)', 'nopython': '(True)', 'parallel': '(False)'}), '((f8[:, :], i8, i8), nogil=True, nopython=True, parallel=False)\n', (769, 832), False, 'from numba import jit\n'), ((1620, 1639), 'numpy.random.rand', 'rand', (['k', 'population'], {}), '(k, population)\n', (1624, 1639), False, 'from numpy.random import rand\n'), ((1653, 1662), 'numba.prange', 'prange', (['k'], {}), '(k)\n', (1659, 1662), False, 'from numba import prange\n'), ((1816, 1851), 'numpy.empty', 'empty', (['(population, population - 1)'], {}), '((population, population - 1))\n', (1821, 1851), False, 'from numpy import empty\n'), ((1865, 1883), 'numba.prange', 'prange', (['population'], {}), '(population)\n', (1871, 1883), False, 'from numba import prange\n'), ((2073, 2090), 'numpy.empty', 'empty', (['population'], {}), '(population)\n', (2078, 2090), False, 'from numpy import empty\n'), ((2104, 2122), 'numba.prange', 'prange', (['population'], {}), '(population)\n', (2110, 2122), False, 'from numba import prange\n'), ((2174, 2180), 'numpy.min', 'min', (['f'], {}), '(f)\n', (2177, 2180), False, 'from numpy import min\n'), ((2195, 2217), 'numpy.empty', 'empty', (['(k, population)'], {}), '((k, population))\n', (2200, 2217), False, 'from numpy import empty\n'), ((3830, 3836), 'time.time', 'time', ([], {}), '()\n', (3834, 3836), False, 'from time import time\n'), ((3851, 3888), 'numpy.array', 'array', (['[[-10.0, 10.0], [-10.0, 10.0]]'], {}), '([[-10.0, 10.0], [-10.0, 10.0]])\n', (3856, 3888), False, 'from numpy import array\n'), ((1681, 1699), 'numba.prange', 'prange', (['population'], {}), '(population)\n', (1687, 1699), False, 'from numba import prange\n'), ((1916, 1938), 'numba.prange', 'prange', (['(population - 1)'], {}), '(population - 1)\n', (1922, 1938), False, 'from numba import prange\n'), ((2394, 2412), 'numba.prange', 'prange', (['population'], {}), '(population)\n', (2400, 2412), False, 'from numba import prange\n'), ((3284, 3290), 'numpy.min', 'min', (['f'], {}), '(f)\n', (3287, 3290), False, 'from numpy import min\n'), ((2351, 2370), 'numpy.random.rand', 'rand', (['k', 'population'], {}), '(k, population)\n', (2355, 2370), False, 'from numpy.random import rand\n'), ((2436, 2476), 'numpy.random.choice', 'choice', (['(population - 1)', '(3)'], {'replace': '(False)'}), '(population - 1, 3, replace=False)\n', (2442, 2476), False, 'from numpy.random import choice\n'), ((2748, 2757), 'numba.prange', 'prange', (['k'], {}), '(k)\n', (2754, 2757), False, 'from numba import prange\n'), ((3961, 3967), 'time.time', 'time', ([], {}), '()\n', (3965, 3967), False, 'from time import time\n'), ((3316, 3325), 'numpy.argmin', 'argmin', (['f'], {}), '(f)\n', (3322, 3325), False, 'from numpy import argmin\n')]
|
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import re
import spacy
import pickle
import time
from collections import defaultdict
import pmi_tfidf_classifier as ptic
path = "../data/"
np.random.seed(250)
#spacy.prefer_gpu()
#nlp = spacy.load("en_core_sci_sm", disable=['ner', 'parser'])
data_raw = pd.read_csv(path + 'DILI_data.csv')
indices = np.random.permutation(data_raw.index)
data = data_raw.loc[indices]
data = data_raw.sample(frac=1)
idx = int(data.shape[0] * 0.2)
test_data = data.iloc[:idx]
train_data = data.iloc[idx:]
targets_train = train_data['Label'].values
targets_test = test_data['Label'].values
tokenized_texts = ptic.tokenization(train_data)
tokenized_test_texts = ptic.tokenization(test_data)
N = len(tokenized_texts)
accuracies = []
precisions = []
recalls = []
F1s = []
dict_size = [i for i in range(0.02, 1, 0.01)]
for i in dict_size:
part = tokenized_texts[:int(N * i)]
word2text_count = ptic.get_word_stat(part)
words_pmis = ptic.create_pmi_dict(part, targets_train, min_count=20)
results = ptic.classify_pmi_based(words_pmis, word2text_count, tokenized_test_texts, N)
precision = np.sum( np.logical_and(results, targets_test) ) / np.sum(results)
recall = np.sum( np.logical_and(results, targets_test) ) / np.sum(targets_test)
F1 = 2 * (recall * precision)/(recall + precision)
accuracy = (results == targets_test).mean()
accuracies.append( accuracy )
precisions.append( precisions )
recalls.append( recall )
FP_rate = ((results - targets_test) == 1).sum()/np.sum(targets_test)
FN_rate = ((results - targets_test) == -1).sum()/np.sum(targets_test == 0)
print("Accuracy: %s\t \nPrecision: %s\t \nRecall: %s\t \nF1: %s\t" % (accuracy, precision, recall, F1))
print("FP: %s\t \nFN: %s\t" % (FP_rate, FN_rate))
|
[
"pmi_tfidf_classifier.get_word_stat",
"numpy.random.seed",
"numpy.sum",
"numpy.logical_and",
"pandas.read_csv",
"pmi_tfidf_classifier.create_pmi_dict",
"pmi_tfidf_classifier.classify_pmi_based",
"numpy.random.permutation",
"pmi_tfidf_classifier.tokenization"
] |
[((211, 230), 'numpy.random.seed', 'np.random.seed', (['(250)'], {}), '(250)\n', (225, 230), True, 'import numpy as np\n'), ((326, 361), 'pandas.read_csv', 'pd.read_csv', (["(path + 'DILI_data.csv')"], {}), "(path + 'DILI_data.csv')\n", (337, 361), True, 'import pandas as pd\n'), ((372, 409), 'numpy.random.permutation', 'np.random.permutation', (['data_raw.index'], {}), '(data_raw.index)\n', (393, 409), True, 'import numpy as np\n'), ((661, 690), 'pmi_tfidf_classifier.tokenization', 'ptic.tokenization', (['train_data'], {}), '(train_data)\n', (678, 690), True, 'import pmi_tfidf_classifier as ptic\n'), ((714, 742), 'pmi_tfidf_classifier.tokenization', 'ptic.tokenization', (['test_data'], {}), '(test_data)\n', (731, 742), True, 'import pmi_tfidf_classifier as ptic\n'), ((952, 976), 'pmi_tfidf_classifier.get_word_stat', 'ptic.get_word_stat', (['part'], {}), '(part)\n', (970, 976), True, 'import pmi_tfidf_classifier as ptic\n'), ((994, 1049), 'pmi_tfidf_classifier.create_pmi_dict', 'ptic.create_pmi_dict', (['part', 'targets_train'], {'min_count': '(20)'}), '(part, targets_train, min_count=20)\n', (1014, 1049), True, 'import pmi_tfidf_classifier as ptic\n'), ((1065, 1142), 'pmi_tfidf_classifier.classify_pmi_based', 'ptic.classify_pmi_based', (['words_pmis', 'word2text_count', 'tokenized_test_texts', 'N'], {}), '(words_pmis, word2text_count, tokenized_test_texts, N)\n', (1088, 1142), True, 'import pmi_tfidf_classifier as ptic\n'), ((1563, 1583), 'numpy.sum', 'np.sum', (['targets_test'], {}), '(targets_test)\n', (1569, 1583), True, 'import numpy as np\n'), ((1633, 1658), 'numpy.sum', 'np.sum', (['(targets_test == 0)'], {}), '(targets_test == 0)\n', (1639, 1658), True, 'import numpy as np\n'), ((1210, 1225), 'numpy.sum', 'np.sum', (['results'], {}), '(results)\n', (1216, 1225), True, 'import numpy as np\n'), ((1289, 1309), 'numpy.sum', 'np.sum', (['targets_test'], {}), '(targets_test)\n', (1295, 1309), True, 'import numpy as np\n'), ((1168, 1205), 'numpy.logical_and', 'np.logical_and', (['results', 'targets_test'], {}), '(results, targets_test)\n', (1182, 1205), True, 'import numpy as np\n'), ((1247, 1284), 'numpy.logical_and', 'np.logical_and', (['results', 'targets_test'], {}), '(results, targets_test)\n', (1261, 1284), True, 'import numpy as np\n')]
|
import numpy as np
def msaeye(msa, unique, turbo):
tic1 = timeit.default_timer()
length = msa.shape[1]
number = msa.shape[0]
# number = 5
array = np.eye(int(number))
seqs = []
for i in range(number):
seqs.append(msa[i,:])
iseq = np.zeros((number, length), dtype=int)
for i in range(0,number-1):
if i == 0:
for k in range(length):
if ord(seqs[i][k])>90:
iseq[i,k]=ord(seqs[i][k])-96 if ord(seqs[i][k])-96 > 0 \
and ord(seqs[i][k])-96 < 26 else 0
else:
iseq[i,k]=ord(seqs[i][k])-64 if ord(seqs[i][k])-64 > 0 \
and ord(seqs[i][k])-64 < 26 else 0
for j in range(i+1,number):
score=0.
ncols=0.
for k in range(length):
if ord(seqs[j][k])>90:
iseq[j,k]=ord(seqs[j][k])-96 if ord(seqs[j][k])-96 > 0 \
and ord(seqs[j][k])-96 < 26 else 0
else:
iseq[j,k]=ord(seqs[j][k])-64 if ord(seqs[j][k])-64 > 0 and ord(seqs[j][k])-64 < 26 else 0
if iseq[i,k] or iseq[j,k]:
ncols += 1
if iseq[i,k]==iseq[j,k]:
score+=1
array[i,j]=float(score)/ncols
array[j,i]=array[i,j]
# print iseq[0]
# print seqs[0]
# raw_input()
else:
for j in range(i+1,number):
score=0.
ncols=0.
for k in range(length):
if iseq[i,k] or iseq[j,k]:
ncols += 1
if iseq[i,k]==iseq[j,k]:
score+=1
array[i,j]= float(score)/ncols#float(sum((iseq[i] == iseq[j])*(iseq[i]*iseq[j]!=0))) / sum(iseq[i]*iseq[j]!=0)
array[j,i]=array[i,j]
toc1 = timeit.default_timer()
elapsed1 = toc1 - tic1
LOGGER.debug('Elapsed: %4.2fs'%elapsed1)
def buildDaliEnsemble(PDBs, record):
daliInfo = record._alignPDB
n_confs = len(PDBs)
ref_pdb_ca = PDBs[0]
ref_chain = list(ref_pdb_ca.getHierView().iterChains())[0]
ref_indices_set = set(range(len(ref_chain)))
ensemble = PDBEnsemble('Dali ensemble - ' + record.getTitle())
ensemble.setAtoms(ref_chain)
ensemble.setCoords(ref_chain)
LOGGER.progress('Building PDB ensemble for {0} conformations from Dali...'
.format(n_confs), n_confs, '_prody_buildDaliEnsemble')
for i, pdb in enumerate(PDBs):
pdb_chain = pdb.getTitle()[:5]
temp_dict = daliInfo[pdb_chain]
sel_pdb_ca = PDBs[i]
map_ref = temp_dict['map_ref']
map_sel = temp_dict['map_sel']
dum_sel = list(ref_indices_set - set(map_ref))
atommap = AtomMap(sel_pdb_ca, indices=map_sel, mapping=map_ref, dummies=dum_sel)
ensemble.addCoordset(atommap, weights=atommap.getFlags('mapped'), degeneracy=True)
LOGGER.update(i, label='_prody_buildDaliEnsemble')
LOGGER.finish()
try:
ensemble.iterpose()
except:
LOGGER.warn('failed to iterpose the ensemble.')
return ensemble
def fetchCATH(filename, ftp_host=None, ftp_path=None, **kwargs):
"""Downloads CATH file via FTP."""
if ftp_host == None:
ftp_host = 'orengoftp.biochem.ucl.ac.uk'
if ftp_path == None:
ftp_path = '/cath/releases/daily-release/newest/'
from ftplib import FTP
output_folder = kwargs.pop('folder', None)
ftp_fn = filename
try:
ftp = FTP(ftp_host)
except Exception as error:
raise type(error)('FTP connection problem, potential reason: '
'no internet connectivity')
else:
success = 0
failure = 0
filenames = []
ftp.login('')
data = []
try:
ftp.cwd(ftp_path)
ftp.retrbinary('RETR ' + ftp_fn, data.append)
except Exception as error:
if ftp_fn in ftp.nlst():
LOGGER.warn('{0} download failed ({1}). It is '
'possible that you do not have rights to '
'download .gz files in the current network.'
.format(ftp_fn, str(error)))
else:
LOGGER.warn('{0} download failed. {1} does not exist '
'on {2}.'.format(ftp_fn, ftp_fn, ftp_host))
failure += 1
filenames.append(None)
else:
if len(data):
if output_folder is None:
output_folder = getcwd()
filename_full = join(output_folder, ftp_fn)
with open(filename_full, 'w+b') as pdbfile:
write = pdbfile.write
[write(block) for block in data]
filename_full = normpath(relpath(filename_full))
LOGGER.debug('{0} downloaded ({1})'
.format(ftp_fn, sympath(filename_full)))
success += 1
filenames.append(filename_full)
else:
LOGGER.warn('{0} download failed, reason unknown.'
.format(ftp_fn))
failure += 1
filenames.append(None)
ftp.quit()
def buildCATHNameDict(cath_file, iscommpressed=True):
"""Returns a dictionary for CATH names with key of CATH ID."""
if iscommpressed:
gunzip(cath_file, 'cath_b.names.temp')
cath_file = 'cath_b.names.temp'
cath_id2name = dict()
with open(cath_file, 'r') as file_temp:
for line in file_temp:
ind_temp = line.find(' ')
cath_id2name[line[:ind_temp]] = line[ind_temp:].strip()
if iscommpressed:
remove(cath_file)
return cath_id2name
def buildPDBChainCATHDict(cath_file, iscommpressed=True):
"""Returns a dictionary for CATH info (ID and version) with key of PDB chain."""
if iscommpressed:
gunzip(cath_file, 'cath_b.all.temp')
cath_file = 'cath_b.all.temp'
cath_dict_temp = dict()
cath_i_dict = dict()
with open(cath_file, 'r') as file_temp:
for line in file_temp:
line = line.strip()
if line != '':
line_list = line.split(' ')
cath_dict_temp[line_list[0]] = line_list[1:]
key, value = line[0:5], line[5:7]
if key in cath_i_dict:
cath_i_dict[key].append(value)
else:
cath_i_dict[key] = [value]
pdbChain2CATH = dict()
for key, values in cath_i_dict.items():
pdbChain2CATH[key] = []
for v in values:
pdbChain2CATH[key].append(cath_dict_temp[key+v])
if iscommpressed:
remove(cath_file)
return pdbChain2CATH
def fetchCATH(filename, ftp_host=None, ftp_path=None, **kwargs):
"""Downloads CATH file via FTP."""
if ftp_host == None:
ftp_host = 'orengoftp.biochem.ucl.ac.uk'
if ftp_path == None:
ftp_path = '/cath/releases/daily-release/newest/'
from ftplib import FTP
output_folder = kwargs.pop('folder', None)
ftp_fn = filename
try:
ftp = FTP(ftp_host)
except Exception as error:
raise type(error)('FTP connection problem, potential reason: '
'no internet connectivity')
else:
success = 0
failure = 0
filenames = []
ftp.login('')
data = []
try:
ftp.cwd(ftp_path)
ftp.retrbinary('RETR ' + ftp_fn, data.append)
except Exception as error:
if ftp_fn in ftp.nlst():
LOGGER.warn('{0} download failed ({1}). It is '
'possible that you do not have rights to '
'download .gz files in the current network.'
.format(ftp_fn, str(error)))
else:
LOGGER.warn('{0} download failed. {1} does not exist '
'on {2}.'.format(ftp_fn, ftp_fn, ftp_host))
failure += 1
filenames.append(None)
else:
if len(data):
if output_folder is None:
output_folder = getcwd()
filename_full = join(output_folder, ftp_fn)
with open(filename_full, 'w+b') as pdbfile:
write = pdbfile.write
[write(block) for block in data]
filename_full = normpath(relpath(filename_full))
LOGGER.debug('{0} downloaded ({1})'
.format(ftp_fn, sympath(filename_full)))
success += 1
filenames.append(filename_full)
else:
LOGGER.warn('{0} download failed, reason unknown.'
.format(ftp_fn))
failure += 1
filenames.append(None)
ftp.quit()
# ftp://orengoftp.biochem.ucl.ac.uk/cath/releases/daily-release/newest/
# fetchCATH('cath-b-newest-names.gz')
# cath_id2name = buildCATHNameDict('cath-b-newest-names.gz')
# fetchCATH('cath-b-newest-all.gz')
# pdbChain2CATH = buildPDBChainCATHDict('cath-b-newest-all.gz')
def extend(model, nodes, atoms):
"""Returns mapping indices and an :class:`.AtomMap`."""
try:
n_atoms = model.numAtoms()
is3d = model.is3d()
except AttributeError:
raise ValueError('model must be an NMA instance')
try:
n_nodes = nodes.numAtoms()
i_nodes = nodes.iterAtoms()
except AttributeError:
raise ValueError('nodes must be an Atomic instance')
if n_atoms != n_nodes:
raise ValueError('atom numbers must be the same')
if not nodes in atoms:
raise ValueError('nodes must be a subset of atoms')
atom_indices = []
indices = []
get = HierView(atoms).getResidue
for i, node in enumerate(i_nodes):
res = get(node.getChid() or None, node.getResnum(),
node.getIcode() or None, node.getSegname() or None)
if res is None:
raise ValueError('atoms must contain a residue for all atoms')
atom_indices.append(res._getIndices())
if is3d:
indices.append(list(range(i*3, (i+1)*3)) * len(res))
else:
indices.append([i] * len(res))
atom_indices = np.concatenate(atom_indices)
indices = np.concatenate(indices)
try:
ag = atoms.getAtomGroup()
except AttributeError:
ag = atoms
atommap = AtomMap(ag, atom_indices, atoms.getACSIndex(),
title=str(atoms), intarrays=True)
return indices, atommap
def extendAtomicData(data, nodes, atoms):
"""Extend a coarse grained data obtained for *nodes* to *atoms*.
:arg data: any data array
:type data: :class:`~numpy.ndarray`
:arg nodes: a set of atoms that has been used
as nodes in data generation
:type nodes: :class:`.Atomic`
:arg atoms: atoms to be selected from
:type atoms: :class:`.Atomic`
"""
from collections import Counter
try:
data = np.asarray(data)
except:
raise TypeError('The data must be array-like.')
if not isinstance(nodes, Atomic):
raise TypeError('nodes must be an Atomic instance')
if not isinstance(atoms, Atomic):
raise TypeError('atoms must be an Atomic instance')
nnodes = nodes.numAtoms()
is3d = False
if len(data) != nnodes:
if data.shape[0] == nnodes * 3:
is3d = True
else:
raise ValueError('data and atoms must have the same size')
indices = nodes.getResindices()
if is3d:
indices = np.array([[i*3, i*3+1, i*3+2]
for i in indices]
).reshape(3*len(indices))
data_ext = []
resid_counter = Counter(atoms.getResindices())
for i in indices:
data_ext.extend(resid_counter.values()[i]*[data[i]])
resid_selstr = ' '.join([str(resid) for resid in nodes.getResindices()])
rest = atoms.select('not resid {0}'.format(resid_selstr))
data_ext.extend(np.zeros(rest.numAtoms()))
return data_ext
def refineEnsemble(ens, lower=.5, upper=10.):
"""Refine a PDB ensemble based on RMSD criterions."""
from scipy.cluster.hierarchy import linkage, fcluster
from scipy.spatial.distance import squareform
from collections import Counter
### calculate pairwise RMSDs ###
RMSD = ens.getRMSDs(pairwise=True)
# convert the RMSD table to the compressed form
v = squareform(RMSD)
### apply upper threshold ###
Z_upper = linkage(v, method='complete')
labels = fcluster(Z_upper, upper, criterion='distance')
most_common_label = Counter(labels).most_common(1)[0][0]
I = np.where(labels==most_common_label)[0]
### apply lower threshold ###
Z_lower = linkage(v, method='single')
labels = fcluster(Z_lower, lower, criterion='distance')
uniq_labels = np.unique(labels)
clusters = []
for label in uniq_labels:
indices = np.where(labels==label)[0]
clusters.append(indices)
J = np.ones(len(clusters), dtype=int) * -1
rmsd = None
for i, cluster in enumerate(clusters):
if len(cluster) > 0:
# find the conformations with the largest coverage
# (the weight of the ref should be 1)
weights = [ens[j].getWeights().sum() for j in cluster]
js = np.where(weights==np.max(weights))[0]
# in the case where there are multiple structures with the same weight,
# the one with the smallest rmsd wrt the ens._coords is selected.
if len(js) > 1:
# rmsd is not calulated unless necessary for the sake of efficiency
rmsd = ens.getRMSDs() if rmsd is None else rmsd
j = js[np.argmin(rmsd[js])]
else:
j = js[0]
J[i] = cluster[j]
else:
J[i] = cluster[0]
### refine ensemble ###
K = np.intersect1d(I, J)
reens = ens[K]
return reens
def showVarianceBar(mode_ensemble, highlights=None, **kwargs):
from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot
from matplotlib.figure import Figure
from matplotlib.colorbar import ColorbarBase
from matplotlib.colors import Normalize, NoNorm
from matplotlib import cm, colors
fig = kwargs.pop('figure', None)
if isinstance(fig, Figure):
fig_num = fig.number
elif fig is None or isinstance(fig, (int, str)):
fig_num = fig
else:
raise TypeError('figure can be either an instance of matplotlib.figure.Figure '
'or a figure number.')
if SETTINGS['auto_show']:
if fig_num is None:
figure(figsize=(6, 2))
else:
figure(fig_num)
elif fig_num is not None:
figure(fig_num)
ax = gca()
# adjust layouts
box = ax.get_position()
_, _, _, height = box.bounds
ratio = 2.5
box.y1 = box.y0 + height/ratio
#box.y0 += height/7.
ax.set_position(box)
fract = kwargs.pop('fraction', True)
#defarrow = {'width':1, 'headwidth':2,
# 'facecolor':'black',
# 'headlength': 4}
defarrow = {'arrowstyle': '->'}
arrowprops = kwargs.pop('arrowprops', defarrow)
if fract:
sig = calcSignatureFractVariance(mode_ensemble)
else:
sig = mode_ensemble.getVariances()
variances = sig.getArray().sum(axis=1)
#meanVar = variances.mean()
#stdVar = variances.std()
#variances = (variances - meanVar)/stdVar
maxVar = variances.max()
minVar = variances.min()
cmap = kwargs.pop('cmap', 'jet')
norm = Normalize(vmin=minVar, vmax=maxVar)
cb = ColorbarBase(ax, cmap=cmap, norm=norm,
orientation='horizontal')
if not highlights:
highlights = []
indices = []; labels = []
ens_labels = mode_ensemble.getLabels()
for hl in highlights:
if isinstance(hl, str):
if not ens_labels:
raise TypeError('highlights should be a list of integers because '
'mode_ensemble has no label')
indices.append(ens_labels.index(hl))
labels.append(hl)
else:
try:
index = int(hl)
except:
raise TypeError('highlights should be a list of integers or strings')
indices.append(index)
if ens_labels:
labels.append(ens_labels[index])
else:
labels.append(str(index))
annotations = []
for i, label in zip(indices, labels):
x = norm(variances[i])
an = annotate(label, xy=(x, 1), xytext=(x, ratio), arrowprops=arrowprops)
annotations.append(an)
for i in range(len(variances)):
x = norm(variances[i])
plot([x, x], [0, 1], 'w')
cb.set_label('Variances')
if SETTINGS['auto_show']:
showFigure()
return cb, annotations
def mapChainByChain(atoms, target, **kwargs):
"""This function is similar to :func:`.mapOntoChain` but correspondence
of chains is found by their chain identifiers.
:arg atoms: atoms to be mapped onto *target*
:type atoms: :class:`.Atomic`
:arg target: reference structure for mapping
:type target: :class:`.Atomic`
:arg return_all: whether to return all mappings.
If False, only mappings for the first chain will be returned.
Default is **True**
:arg return_all: bool
:arg correspondence: chain IDs in atoms corresponding to those in ref
Default is to use the same chain IDs as in ref.
:type correspondence: str, list, dict
"""
mappings = []
if isinstance(target, AtomGroup):
chs_ref_ag = target.iterChains()
else:
chs_ref_ag = target.getAtomGroup().iterChains()
id_atm = atoms.getTitle()
id_ref = target.getTitle()
chs_atm = [chain for chain in atoms.getHierView().iterChains()]
chs_ref = [chain for chain in target.getHierView().iterChains()]
corr_input = kwargs.get('correspondence', None)
if isinstance(corr_input, dict):
correspondence = corr_input
elif corr_input is None:
correspondence = {}
elif isinstance(corr_input, str):
correspondence = {}
correspondence[atoms.getTitle()] = corr_input
else:
correspondence = {}
try:
correspondence[id_atm] = corr_input[0]
correspondence[id_ref] = corr_input[1]
except (IndexError, TypeError):
raise TypeError('correspondence should be a dict with keys being titles of atoms and ref, '
'and values are str indicating chID correspondences')
if not id_atm in correspondence:
correspondence[id_atm] = ''.join([chain.getChid() for chain in chs_atm])
if not id_ref in correspondence:
correspondence[id_ref] = ''.join([chain.getChid() for chain in chs_ref_ag])
corr_tar = correspondence[id_atm]
corr_ref = correspondence[id_ref]
for chain in chs_ref:
try:
i = corr_ref.index(chain.getChid())
chid = corr_tar[i]
except ValueError:
continue
for target_chain in chs_atm:
if target_chain.getChid() == chid:
mappings_ = mapOntoChainByAlignment(target_chain, chain, **kwargs)
if len(mappings_):
mappings.append(mappings_[0])
return mappings
def _extend(self, arr, defval=0):
mask = self.mask#.copy()
if self.is3d():
mask = np.repeat(mask, 3)
n_true = np.sum(mask)
N = len(mask)
if arr.ndim == 1:
whole_array = np.empty(N, dtype=arr.dtype)
whole_array.fill(defval)
whole_array[mask] = arr[:n_true]
elif arr.ndim == 2:
n, m = arr.shape
whole_array = np.empty((N, m), dtype=arr.dtype)
whole_array.fill(defval)
#mask = np.expand_dims(mask, axis=1)
#mask = mask.repeat(m, axis=1)
whole_array[mask] = arr[:n_true, :]
else: # only developers can trigger this case
raise ValueError('arr can only be either 1D or 2D')
return whole_array
|
[
"scipy.cluster.hierarchy.fcluster",
"numpy.sum",
"numpy.empty",
"scipy.cluster.hierarchy.linkage",
"numpy.argmin",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.gca",
"numpy.unique",
"matplotlib.colors.Normalize",
"numpy.max",
"collections.Counter",
"numpy.intersect1d",
"numpy.repeat",
"scipy.spatial.distance.squareform",
"numpy.asarray",
"matplotlib.colorbar.ColorbarBase",
"numpy.concatenate",
"matplotlib.pyplot.annotate",
"matplotlib.pyplot.plot",
"numpy.zeros",
"numpy.where",
"numpy.array",
"ftplib.FTP"
] |
[((271, 308), 'numpy.zeros', 'np.zeros', (['(number, length)'], {'dtype': 'int'}), '((number, length), dtype=int)\n', (279, 308), True, 'import numpy as np\n'), ((10729, 10757), 'numpy.concatenate', 'np.concatenate', (['atom_indices'], {}), '(atom_indices)\n', (10743, 10757), True, 'import numpy as np\n'), ((10772, 10795), 'numpy.concatenate', 'np.concatenate', (['indices'], {}), '(indices)\n', (10786, 10795), True, 'import numpy as np\n'), ((12941, 12957), 'scipy.spatial.distance.squareform', 'squareform', (['RMSD'], {}), '(RMSD)\n', (12951, 12957), False, 'from scipy.spatial.distance import squareform\n'), ((13007, 13036), 'scipy.cluster.hierarchy.linkage', 'linkage', (['v'], {'method': '"""complete"""'}), "(v, method='complete')\n", (13014, 13036), False, 'from scipy.cluster.hierarchy import linkage, fcluster\n'), ((13050, 13096), 'scipy.cluster.hierarchy.fcluster', 'fcluster', (['Z_upper', 'upper'], {'criterion': '"""distance"""'}), "(Z_upper, upper, criterion='distance')\n", (13058, 13096), False, 'from scipy.cluster.hierarchy import linkage, fcluster\n'), ((13254, 13281), 'scipy.cluster.hierarchy.linkage', 'linkage', (['v'], {'method': '"""single"""'}), "(v, method='single')\n", (13261, 13281), False, 'from scipy.cluster.hierarchy import linkage, fcluster\n'), ((13295, 13341), 'scipy.cluster.hierarchy.fcluster', 'fcluster', (['Z_lower', 'lower'], {'criterion': '"""distance"""'}), "(Z_lower, lower, criterion='distance')\n", (13303, 13341), False, 'from scipy.cluster.hierarchy import linkage, fcluster\n'), ((13360, 13377), 'numpy.unique', 'np.unique', (['labels'], {}), '(labels)\n', (13369, 13377), True, 'import numpy as np\n'), ((14416, 14436), 'numpy.intersect1d', 'np.intersect1d', (['I', 'J'], {}), '(I, J)\n', (14430, 14436), True, 'import numpy as np\n'), ((15321, 15326), 'matplotlib.pyplot.gca', 'gca', ([], {}), '()\n', (15324, 15326), False, 'from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot\n'), ((16148, 16183), 'matplotlib.colors.Normalize', 'Normalize', ([], {'vmin': 'minVar', 'vmax': 'maxVar'}), '(vmin=minVar, vmax=maxVar)\n', (16157, 16183), False, 'from matplotlib.colors import Normalize, NoNorm\n'), ((16193, 16257), 'matplotlib.colorbar.ColorbarBase', 'ColorbarBase', (['ax'], {'cmap': 'cmap', 'norm': 'norm', 'orientation': '"""horizontal"""'}), "(ax, cmap=cmap, norm=norm, orientation='horizontal')\n", (16205, 16257), False, 'from matplotlib.colorbar import ColorbarBase\n'), ((20150, 20162), 'numpy.sum', 'np.sum', (['mask'], {}), '(mask)\n', (20156, 20162), True, 'import numpy as np\n'), ((3715, 3728), 'ftplib.FTP', 'FTP', (['ftp_host'], {}), '(ftp_host)\n', (3718, 3728), False, 'from ftplib import FTP\n'), ((7474, 7487), 'ftplib.FTP', 'FTP', (['ftp_host'], {}), '(ftp_host)\n', (7477, 7487), False, 'from ftplib import FTP\n'), ((11482, 11498), 'numpy.asarray', 'np.asarray', (['data'], {}), '(data)\n', (11492, 11498), True, 'import numpy as np\n'), ((13166, 13203), 'numpy.where', 'np.where', (['(labels == most_common_label)'], {}), '(labels == most_common_label)\n', (13174, 13203), True, 'import numpy as np\n'), ((17167, 17235), 'matplotlib.pyplot.annotate', 'annotate', (['label'], {'xy': '(x, 1)', 'xytext': '(x, ratio)', 'arrowprops': 'arrowprops'}), '(label, xy=(x, 1), xytext=(x, ratio), arrowprops=arrowprops)\n', (17175, 17235), False, 'from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot\n'), ((17343, 17368), 'matplotlib.pyplot.plot', 'plot', (['[x, x]', '[0, 1]', '"""w"""'], {}), "([x, x], [0, 1], 'w')\n", (17347, 17368), False, 'from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot\n'), ((20117, 20135), 'numpy.repeat', 'np.repeat', (['mask', '(3)'], {}), '(mask, 3)\n', (20126, 20135), True, 'import numpy as np\n'), ((20226, 20254), 'numpy.empty', 'np.empty', (['N'], {'dtype': 'arr.dtype'}), '(N, dtype=arr.dtype)\n', (20234, 20254), True, 'import numpy as np\n'), ((13445, 13470), 'numpy.where', 'np.where', (['(labels == label)'], {}), '(labels == label)\n', (13453, 13470), True, 'import numpy as np\n'), ((15193, 15215), 'matplotlib.pyplot.figure', 'figure', ([], {'figsize': '(6, 2)'}), '(figsize=(6, 2))\n', (15199, 15215), False, 'from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot\n'), ((15242, 15257), 'matplotlib.pyplot.figure', 'figure', (['fig_num'], {}), '(fig_num)\n', (15248, 15257), False, 'from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot\n'), ((15296, 15311), 'matplotlib.pyplot.figure', 'figure', (['fig_num'], {}), '(fig_num)\n', (15302, 15311), False, 'from matplotlib.pyplot import figure, gca, annotate, subplots_adjust, plot\n'), ((20400, 20433), 'numpy.empty', 'np.empty', (['(N, m)'], {'dtype': 'arr.dtype'}), '((N, m), dtype=arr.dtype)\n', (20408, 20433), True, 'import numpy as np\n'), ((12059, 12117), 'numpy.array', 'np.array', (['[[i * 3, i * 3 + 1, i * 3 + 2] for i in indices]'], {}), '([[i * 3, i * 3 + 1, i * 3 + 2] for i in indices])\n', (12067, 12117), True, 'import numpy as np\n'), ((13121, 13136), 'collections.Counter', 'Counter', (['labels'], {}), '(labels)\n', (13128, 13136), False, 'from collections import Counter\n'), ((14240, 14259), 'numpy.argmin', 'np.argmin', (['rmsd[js]'], {}), '(rmsd[js])\n', (14249, 14259), True, 'import numpy as np\n'), ((13857, 13872), 'numpy.max', 'np.max', (['weights'], {}), '(weights)\n', (13863, 13872), True, 'import numpy as np\n')]
|
import numpy as np
import cv2 as cv
from split import SliceImage
import utils
class DocumentScanner:
def __init__(self, path):
self.path = path
self.contrast = 0
self.row = 4
self.column = 4
def setImage(self):
self.image = cv.imread(self.path, 1)
def copy(self):
self.clone = self.image.copy()
def resize(self, width):
# old_height/old_width
ratio = self.image.shape[0] / self.image.shape[1]
# Only resize when image's width > 600
if self.image.shape[1] > width:
# Resize (width, width*ratio)
self.image = cv.resize(self.image, (width, round(width * ratio)))
def convertGray(self):
self.grayscale = cv.cvtColor(self.clone, cv.COLOR_BGR2GRAY)
def calculate_contrast(self):
# Blur to decrease detail
blur = SliceImage(self.grayscale, self.column, self.row)
blur.divide()
blur.blur(50, 50)
self.contrast = blur.contrast()
def equalization(self):
equalization = cv.equalizeHist(self.grayscale)
self.median = cv.medianBlur(equalization,5)
def canny(self):
self.slice.edge_canny()
self.slice.merge()
self.edge = self.slice.image
def otsu(self):
self.slice.edge_otsu()
self.slice.merge()
self.edge = self.slice.image
def dilate(self):
kernel = cv.getStructuringElement(cv.MORPH_RECT, (3, 3))
self.dilation = cv.dilate(self.edge, kernel, 1)
def contour(self):
contours, hierarchy = cv.findContours(self.dilation, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)
contours = sorted(contours, key=cv.contourArea, reverse= True)
# Find matching contour
for i in contours:
elip = cv.arcLength(i, True)
approx = cv.approxPolyDP(i, 0.08*elip, True)
# Ordinary papers have 4 corner
if len(approx) == 4 :
doc = approx
break
cv.drawContours(self.clone, [doc], -1, (0, 255, 0), 2)
def write(self):
cv.imwrite('../process/grayscale.jpg', self.grayscale)
cv.imwrite('../process/edge.jpg', self.edge)
cv.imwrite('../process/dilation.jpg', self.dilation)
cv.imwrite('../process/contour.jpg', self.clone)
def test(self, name):
cv.imwrite('result/' + name, self.clone)
def detect(self):
self.setImage()
self.resize(600)
self.copy()
self.convertGray()
self.slice = SliceImage(self.grayscale, self.column, self.row)
self.slice.divide()
self.calculate_contrast()
if self.contrast < 25:
self.equalization()
self.slice.image = self.median
self.slice.divide()
self.slice.blur(70, 70)
else:
self.slice.blur(50, 50)
self.canny()
self.dilate()
self.contour()
def old(self):
#reshape to avoid errors ahead
doc=doc.reshape((4,2))
#create a new array and initialize
rect = np.zeros((4,2), dtype="float32")
Sum = doc.sum(axis = 1)
rect[0] = doc[np.argmin(Sum)]
rect[2] = doc[np.argmax(Sum)]
Diff = np.diff(doc, axis=1)
rect[1] = doc[np.argmin(Diff)]
rect[3] = doc[np.argmax(Diff)]
(topLeft,topRight,bottomRight,bottomLeft) = rect
#find distance between points and get max
dist1 = np.linalg.norm(bottomRight-bottomLeft)
dist2 = np.linalg.norm(topRight-topLeft)
maxWidth = max(int(dist1),int(dist2))
dist3 = np.linalg.norm(topRight-bottomRight)
dist4 = np.linalg.norm(topLeft-bottomLeft)
maxHeight = max(int(dist3), int(dist4))
dst = np.array([[0,0],[maxWidth-1, 0],[maxWidth-1, maxHeight-1], [0, maxHeight-1]], dtype="float32")
M = cv.getPerspectiveTransform(rect, dst)
warp = cv.warpPerspective(sourceImage, M, (maxWidth, maxHeight))
destinationImage = cv.cvtColor(warp, cv.COLOR_BGR2GRAY)
# sharpen image
sharpen = cv.GaussianBlur(destinationImage, (0, 0), 3)
sharpen = cv.addWeighted(destinationImage, 1.5, sharpen, -0.5, 0)
# apply adaptive threshold to get black and white effect
thresh = cv.adaptiveThreshold(
sharpen, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.THRESH_BINARY, 21, 15)
cv.imwrite('scanned.jpg', warp)
cv.imwrite('white effect.jpg', thresh)
return thresh
|
[
"cv2.GaussianBlur",
"cv2.medianBlur",
"cv2.getPerspectiveTransform",
"cv2.arcLength",
"cv2.approxPolyDP",
"numpy.argmax",
"cv2.adaptiveThreshold",
"numpy.argmin",
"numpy.linalg.norm",
"cv2.warpPerspective",
"cv2.dilate",
"cv2.cvtColor",
"cv2.imwrite",
"split.SliceImage",
"cv2.drawContours",
"cv2.equalizeHist",
"cv2.addWeighted",
"cv2.getStructuringElement",
"numpy.zeros",
"cv2.imread",
"numpy.diff",
"numpy.array",
"cv2.findContours"
] |
[((278, 301), 'cv2.imread', 'cv.imread', (['self.path', '(1)'], {}), '(self.path, 1)\n', (287, 301), True, 'import cv2 as cv\n'), ((749, 791), 'cv2.cvtColor', 'cv.cvtColor', (['self.clone', 'cv.COLOR_BGR2GRAY'], {}), '(self.clone, cv.COLOR_BGR2GRAY)\n', (760, 791), True, 'import cv2 as cv\n'), ((881, 930), 'split.SliceImage', 'SliceImage', (['self.grayscale', 'self.column', 'self.row'], {}), '(self.grayscale, self.column, self.row)\n', (891, 930), False, 'from split import SliceImage\n'), ((1072, 1103), 'cv2.equalizeHist', 'cv.equalizeHist', (['self.grayscale'], {}), '(self.grayscale)\n', (1087, 1103), True, 'import cv2 as cv\n'), ((1126, 1156), 'cv2.medianBlur', 'cv.medianBlur', (['equalization', '(5)'], {}), '(equalization, 5)\n', (1139, 1156), True, 'import cv2 as cv\n'), ((1448, 1495), 'cv2.getStructuringElement', 'cv.getStructuringElement', (['cv.MORPH_RECT', '(3, 3)'], {}), '(cv.MORPH_RECT, (3, 3))\n', (1472, 1495), True, 'import cv2 as cv\n'), ((1520, 1551), 'cv2.dilate', 'cv.dilate', (['self.edge', 'kernel', '(1)'], {}), '(self.edge, kernel, 1)\n', (1529, 1551), True, 'import cv2 as cv\n'), ((1611, 1679), 'cv2.findContours', 'cv.findContours', (['self.dilation', 'cv.RETR_LIST', 'cv.CHAIN_APPROX_SIMPLE'], {}), '(self.dilation, cv.RETR_LIST, cv.CHAIN_APPROX_SIMPLE)\n', (1626, 1679), True, 'import cv2 as cv\n'), ((2031, 2085), 'cv2.drawContours', 'cv.drawContours', (['self.clone', '[doc]', '(-1)', '(0, 255, 0)', '(2)'], {}), '(self.clone, [doc], -1, (0, 255, 0), 2)\n', (2046, 2085), True, 'import cv2 as cv\n'), ((2117, 2171), 'cv2.imwrite', 'cv.imwrite', (['"""../process/grayscale.jpg"""', 'self.grayscale'], {}), "('../process/grayscale.jpg', self.grayscale)\n", (2127, 2171), True, 'import cv2 as cv\n'), ((2180, 2224), 'cv2.imwrite', 'cv.imwrite', (['"""../process/edge.jpg"""', 'self.edge'], {}), "('../process/edge.jpg', self.edge)\n", (2190, 2224), True, 'import cv2 as cv\n'), ((2233, 2285), 'cv2.imwrite', 'cv.imwrite', (['"""../process/dilation.jpg"""', 'self.dilation'], {}), "('../process/dilation.jpg', self.dilation)\n", (2243, 2285), True, 'import cv2 as cv\n'), ((2294, 2342), 'cv2.imwrite', 'cv.imwrite', (['"""../process/contour.jpg"""', 'self.clone'], {}), "('../process/contour.jpg', self.clone)\n", (2304, 2342), True, 'import cv2 as cv\n'), ((2379, 2419), 'cv2.imwrite', 'cv.imwrite', (["('result/' + name)", 'self.clone'], {}), "('result/' + name, self.clone)\n", (2389, 2419), True, 'import cv2 as cv\n'), ((2562, 2611), 'split.SliceImage', 'SliceImage', (['self.grayscale', 'self.column', 'self.row'], {}), '(self.grayscale, self.column, self.row)\n', (2572, 2611), False, 'from split import SliceImage\n'), ((3148, 3181), 'numpy.zeros', 'np.zeros', (['(4, 2)'], {'dtype': '"""float32"""'}), "((4, 2), dtype='float32')\n", (3156, 3181), True, 'import numpy as np\n'), ((3305, 3325), 'numpy.diff', 'np.diff', (['doc'], {'axis': '(1)'}), '(doc, axis=1)\n', (3312, 3325), True, 'import numpy as np\n'), ((3530, 3570), 'numpy.linalg.norm', 'np.linalg.norm', (['(bottomRight - bottomLeft)'], {}), '(bottomRight - bottomLeft)\n', (3544, 3570), True, 'import numpy as np\n'), ((3585, 3619), 'numpy.linalg.norm', 'np.linalg.norm', (['(topRight - topLeft)'], {}), '(topRight - topLeft)\n', (3599, 3619), True, 'import numpy as np\n'), ((3682, 3720), 'numpy.linalg.norm', 'np.linalg.norm', (['(topRight - bottomRight)'], {}), '(topRight - bottomRight)\n', (3696, 3720), True, 'import numpy as np\n'), ((3735, 3771), 'numpy.linalg.norm', 'np.linalg.norm', (['(topLeft - bottomLeft)'], {}), '(topLeft - bottomLeft)\n', (3749, 3771), True, 'import numpy as np\n'), ((3834, 3944), 'numpy.array', 'np.array', (['[[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, maxHeight - 1]]'], {'dtype': '"""float32"""'}), "([[0, 0], [maxWidth - 1, 0], [maxWidth - 1, maxHeight - 1], [0, \n maxHeight - 1]], dtype='float32')\n", (3842, 3944), True, 'import numpy as np\n'), ((3942, 3979), 'cv2.getPerspectiveTransform', 'cv.getPerspectiveTransform', (['rect', 'dst'], {}), '(rect, dst)\n', (3968, 3979), True, 'import cv2 as cv\n'), ((3995, 4052), 'cv2.warpPerspective', 'cv.warpPerspective', (['sourceImage', 'M', '(maxWidth, maxHeight)'], {}), '(sourceImage, M, (maxWidth, maxHeight))\n', (4013, 4052), True, 'import cv2 as cv\n'), ((4081, 4117), 'cv2.cvtColor', 'cv.cvtColor', (['warp', 'cv.COLOR_BGR2GRAY'], {}), '(warp, cv.COLOR_BGR2GRAY)\n', (4092, 4117), True, 'import cv2 as cv\n'), ((4161, 4205), 'cv2.GaussianBlur', 'cv.GaussianBlur', (['destinationImage', '(0, 0)', '(3)'], {}), '(destinationImage, (0, 0), 3)\n', (4176, 4205), True, 'import cv2 as cv\n'), ((4224, 4279), 'cv2.addWeighted', 'cv.addWeighted', (['destinationImage', '(1.5)', 'sharpen', '(-0.5)', '(0)'], {}), '(destinationImage, 1.5, sharpen, -0.5, 0)\n', (4238, 4279), True, 'import cv2 as cv\n'), ((4362, 4458), 'cv2.adaptiveThreshold', 'cv.adaptiveThreshold', (['sharpen', '(255)', 'cv.ADAPTIVE_THRESH_GAUSSIAN_C', 'cv.THRESH_BINARY', '(21)', '(15)'], {}), '(sharpen, 255, cv.ADAPTIVE_THRESH_GAUSSIAN_C, cv.\n THRESH_BINARY, 21, 15)\n', (4382, 4458), True, 'import cv2 as cv\n'), ((4481, 4512), 'cv2.imwrite', 'cv.imwrite', (['"""scanned.jpg"""', 'warp'], {}), "('scanned.jpg', warp)\n", (4491, 4512), True, 'import cv2 as cv\n'), ((4522, 4560), 'cv2.imwrite', 'cv.imwrite', (['"""white effect.jpg"""', 'thresh'], {}), "('white effect.jpg', thresh)\n", (4532, 4560), True, 'import cv2 as cv\n'), ((1829, 1850), 'cv2.arcLength', 'cv.arcLength', (['i', '(True)'], {}), '(i, True)\n', (1841, 1850), True, 'import cv2 as cv\n'), ((1869, 1906), 'cv2.approxPolyDP', 'cv.approxPolyDP', (['i', '(0.08 * elip)', '(True)'], {}), '(i, 0.08 * elip, True)\n', (1884, 1906), True, 'import cv2 as cv\n'), ((3235, 3249), 'numpy.argmin', 'np.argmin', (['Sum'], {}), '(Sum)\n', (3244, 3249), True, 'import numpy as np\n'), ((3273, 3287), 'numpy.argmax', 'np.argmax', (['Sum'], {}), '(Sum)\n', (3282, 3287), True, 'import numpy as np\n'), ((3348, 3363), 'numpy.argmin', 'np.argmin', (['Diff'], {}), '(Diff)\n', (3357, 3363), True, 'import numpy as np\n'), ((3387, 3402), 'numpy.argmax', 'np.argmax', (['Diff'], {}), '(Diff)\n', (3396, 3402), True, 'import numpy as np\n')]
|
import tensorflow as tf
import numpy as np
(x_train, y_train), (x_test, y_test) = tf.keras.datasets.mnist.load_data()
x_train, x_test = np.array(x_train/255.0,dtype="<f4"), np.array(x_test/255.0,dtype="<f4")
idx=np.argsort(y_train.flatten())
vdx=np.array([6000*i+j for i in range(10) for j in range(5400,6000)])
tdx=np.array([6000*i+j for i in range(10) for j in range(5400)])
x_val, y_val = x_train[idx[vdx]] , y_train[idx[vdx]]
x_train, y_train = x_train[idx[tdx]] , y_train[idx[tdx]]
idx=np.random.permutation(54000)
x_train, y_train = tf.convert_to_tensor(x_train[idx]) , tf.convert_to_tensor(y_train[idx])
idx=np.random.permutation(6000)
x_val, y_val = tf.convert_to_tensor(x_val[idx]) , tf.convert_to_tensor(y_val[idx])
x_test, y_test = tf.convert_to_tensor(x_test) , tf.convert_to_tensor(y_test)
|
[
"numpy.random.permutation",
"tensorflow.convert_to_tensor",
"numpy.array",
"tensorflow.keras.datasets.mnist.load_data"
] |
[((86, 121), 'tensorflow.keras.datasets.mnist.load_data', 'tf.keras.datasets.mnist.load_data', ([], {}), '()\n', (119, 121), True, 'import tensorflow as tf\n'), ((508, 536), 'numpy.random.permutation', 'np.random.permutation', (['(54000)'], {}), '(54000)\n', (529, 536), True, 'import numpy as np\n'), ((636, 663), 'numpy.random.permutation', 'np.random.permutation', (['(6000)'], {}), '(6000)\n', (657, 663), True, 'import numpy as np\n'), ((141, 179), 'numpy.array', 'np.array', (['(x_train / 255.0)'], {'dtype': '"""<f4"""'}), "(x_train / 255.0, dtype='<f4')\n", (149, 179), True, 'import numpy as np\n'), ((178, 215), 'numpy.array', 'np.array', (['(x_test / 255.0)'], {'dtype': '"""<f4"""'}), "(x_test / 255.0, dtype='<f4')\n", (186, 215), True, 'import numpy as np\n'), ((557, 591), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x_train[idx]'], {}), '(x_train[idx])\n', (577, 591), True, 'import tensorflow as tf\n'), ((594, 628), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['y_train[idx]'], {}), '(y_train[idx])\n', (614, 628), True, 'import tensorflow as tf\n'), ((680, 712), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x_val[idx]'], {}), '(x_val[idx])\n', (700, 712), True, 'import tensorflow as tf\n'), ((715, 747), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['y_val[idx]'], {}), '(y_val[idx])\n', (735, 747), True, 'import tensorflow as tf\n'), ((768, 796), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['x_test'], {}), '(x_test)\n', (788, 796), True, 'import tensorflow as tf\n'), ((799, 827), 'tensorflow.convert_to_tensor', 'tf.convert_to_tensor', (['y_test'], {}), '(y_test)\n', (819, 827), True, 'import tensorflow as tf\n')]
|
import numpy as np
import mido
from mido import Message, MidiFile, MidiTrack
import argparse
from functools import partial
def main():
#Get options from input
parser = argparse.ArgumentParser(description='Superpermutation to midi converter')
parser.add_argument('inputfile',
help='The file containing the superpermutation to convert.')
parser.add_argument('outputfile', nargs='?', default='inputfile',
help='The file to store the midi output in.')
parser.add_argument('-s', '--scale', nargs='?', default="default",
help='Scale to translate the numbers into. Possible scales:\
major, natural-minor, harmonic-minor, whole-note')
parser.add_argument('-p', '--play', action='store_true',
help='Play back the midifile when running the script(requires python-rtmidi)')
parser.add_argument('-I', '--instrument', default=46,
help='General MIDI instrument number from 0 to 127. Default: 46 (harp)')
parser.add_argument('-l', '--note_length', default='edge-weight',
help='The method to decide note lengths.\
Possible values are: edge-weight, free-space, even')
args = parser.parse_args()
input_string = open(args.inputfile, 'r').read().strip()
superpermutation = np.array(list(input_string), dtype=int)
#Make sure it is zero indexed
superpermutation -= superpermutation.min()
N = superpermutation.max() + 1
note_lengths = np.zeros_like(superpermutation)
scale = args.scale
if args.scale == "default":
if N == 7:
scale = "major"
elif N == 6:
scale = "whole-note"
elif N == 5:
scale = "major-pentatonic"
scaleFunction = {
"major" : partial(numberToScale, scale=Scales.major),
"natural-minor" : partial(numberToScale, scale=Scales.natural_minor),
"harmonic-minor" : partial(numberToScale, scale=Scales.harmonic_minor),
"whole-note" : partial(numberToScale, scale=Scales.whole_note),
"major-pentatonic": partial(numberToScale, scale=Scales.major_pentatonic),
"miyako-bushi" : partial(numberToScale, scale=Scales.miyako_bushi)
}.get(scale, "major")
if args.note_length == 'free-space':
for i, number in enumerate(superpermutation):
num_perms = 0
# Length based on how far it is to the same value on both sides
for j in range(1, N):
if i-j < 0 or superpermutation[i-j] == number:
break
num_perms += 1
for j in range(1, N):
if i+j >= superpermutation.size or superpermutation[i+j] == number:
break
num_perms += 1
note_lengths[i] = num_perms - N + 1
elif args.note_length == 'edge-weight':
for i, number in enumerate(superpermutation):
weight = 0
for j in range(i+1, i+N+1):
if j >= N and j < superpermutation.size:
if isLegalPermutation(superpermutation[j-N:j]):
break;
weight += 1
note_lengths[i] = N - weight - 1
else:
note_lengths[:] = N - 1
# Fix the end values
note_lengths[0:N-1] = N - 1
mid = MidiFile()
track = MidiTrack()
mid.tracks.append(track)
track.append(Message('program_change', program=args.instrument, time=0))
for i in range(superpermutation.size):
note = scaleFunction(superpermutation[i])
track.append(Message('note_on', note=note, time=0))
track.append(Message('note_off', note=note, time=2**(note_lengths[i] + 10 - N)))
if args.outputfile == "inputfile":
mid.save(args.inputfile.split('.')[0] + ".mid")
else:
mid.save(args.outputfile)
if args.play:
port = mido.open_output()
for msg in mid.play():
port.send(msg)
def isLegalPermutation(array):
if np.unique(array).size == array.size:
return True
else:
return False
def numberToScale(number, scale, base_note=64):
octave = number // scale.__len__()
note = number % scale.__len__()
return base_note + octave*12 + scale.get(note, 0)
class Scales:
whole_note = {number: 2*number for number in range(7)}
major = {
0: 0,
1: 2,
2: 4,
3: 5,
4: 7,
5: 9,
6: 11
}
natural_minor = {
0: 0,
1: 2,
2: 3,
3: 5,
4: 7,
5: 8,
6: 10
}
harmonic_minor = {
0: 0,
1: 2,
2: 3,
3: 5,
4: 7,
5: 8,
6: 11
}
major_pentatonic = {
0: 0,
1: 2,
2: 4,
3: 7,
4: 9
}
miyako_bushi = {
0: 0,
1: 1,
2: 5,
3: 7,
4: 8
}
if __name__ == "__main__":
main()
|
[
"functools.partial",
"numpy.zeros_like",
"argparse.ArgumentParser",
"mido.MidiFile",
"mido.Message",
"mido.MidiTrack",
"mido.open_output",
"numpy.unique"
] |
[((178, 251), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Superpermutation to midi converter"""'}), "(description='Superpermutation to midi converter')\n", (201, 251), False, 'import argparse\n'), ((1550, 1581), 'numpy.zeros_like', 'np.zeros_like', (['superpermutation'], {}), '(superpermutation)\n', (1563, 1581), True, 'import numpy as np\n'), ((3400, 3410), 'mido.MidiFile', 'MidiFile', ([], {}), '()\n', (3408, 3410), False, 'from mido import Message, MidiFile, MidiTrack\n'), ((3423, 3434), 'mido.MidiTrack', 'MidiTrack', ([], {}), '()\n', (3432, 3434), False, 'from mido import Message, MidiFile, MidiTrack\n'), ((3482, 3540), 'mido.Message', 'Message', (['"""program_change"""'], {'program': 'args.instrument', 'time': '(0)'}), "('program_change', program=args.instrument, time=0)\n", (3489, 3540), False, 'from mido import Message, MidiFile, MidiTrack\n'), ((3960, 3978), 'mido.open_output', 'mido.open_output', ([], {}), '()\n', (3976, 3978), False, 'import mido\n'), ((3658, 3695), 'mido.Message', 'Message', (['"""note_on"""'], {'note': 'note', 'time': '(0)'}), "('note_on', note=note, time=0)\n", (3665, 3695), False, 'from mido import Message, MidiFile, MidiTrack\n'), ((3718, 3786), 'mido.Message', 'Message', (['"""note_off"""'], {'note': 'note', 'time': '(2 ** (note_lengths[i] + 10 - N))'}), "('note_off', note=note, time=2 ** (note_lengths[i] + 10 - N))\n", (3725, 3786), False, 'from mido import Message, MidiFile, MidiTrack\n'), ((4076, 4092), 'numpy.unique', 'np.unique', (['array'], {}), '(array)\n', (4085, 4092), True, 'import numpy as np\n'), ((1852, 1894), 'functools.partial', 'partial', (['numberToScale'], {'scale': 'Scales.major'}), '(numberToScale, scale=Scales.major)\n', (1859, 1894), False, 'from functools import partial\n'), ((1924, 1974), 'functools.partial', 'partial', (['numberToScale'], {'scale': 'Scales.natural_minor'}), '(numberToScale, scale=Scales.natural_minor)\n', (1931, 1974), False, 'from functools import partial\n'), ((2004, 2055), 'functools.partial', 'partial', (['numberToScale'], {'scale': 'Scales.harmonic_minor'}), '(numberToScale, scale=Scales.harmonic_minor)\n', (2011, 2055), False, 'from functools import partial\n'), ((2085, 2132), 'functools.partial', 'partial', (['numberToScale'], {'scale': 'Scales.whole_note'}), '(numberToScale, scale=Scales.whole_note)\n', (2092, 2132), False, 'from functools import partial\n'), ((2162, 2215), 'functools.partial', 'partial', (['numberToScale'], {'scale': 'Scales.major_pentatonic'}), '(numberToScale, scale=Scales.major_pentatonic)\n', (2169, 2215), False, 'from functools import partial\n'), ((2245, 2294), 'functools.partial', 'partial', (['numberToScale'], {'scale': 'Scales.miyako_bushi'}), '(numberToScale, scale=Scales.miyako_bushi)\n', (2252, 2294), False, 'from functools import partial\n')]
|
"""
This module implements the intermediates computation for plot(df) function.
""" # pylint: disable=too-many-lines
from collections import defaultdict
from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Union, cast
import dask
import dask.array as da
import dask.dataframe as dd
import numpy as np
import pandas as pd
from dask.array.stats import kurtosis, skew
from nltk.stem import PorterStemmer, WordNetLemmatizer
from scipy.stats import gaussian_kde
from ...assets.english_stopwords import english_stopwords
from ...errors import UnreachableError
from ..dtypes import (
Continuous,
DateTime,
DType,
DTypeDef,
Nominal,
detect_dtype,
drop_null,
is_dtype,
)
from ..intermediate import Intermediate
from ..utils import to_dask
__all__ = ["compute"]
# Dictionary for mapping the time unit to its formatting. Each entry is of the
# form unit:(unit code for pd.Grouper freq parameter, pandas to_period strftime
# formatting for line charts, pandas to_period strftime formatting for box plot,
# label format).
DTMAP = {
"year": ("Y", "%Y", "%Y", "Year"),
"quarter": ("Q", "Q%q %Y", "Q%q %Y", "Quarter"),
"month": ("M", "%B %Y", "%b %Y", "Month"),
"week": ("W-SAT", "%d %B, %Y", "%d %b, %Y", "Week of"),
"day": ("D", "%d %B, %Y", "%d %b, %Y", "Date"),
"hour": ("H", "%d %B, %Y, %I %p", "%d %b, %Y, %I %p", "Hour"),
"minute": ("T", "%d %B, %Y, %I:%M %p", "%d %b, %Y, %I:%M %p", "Minute"),
"second": ("S", "%d %B, %Y, %I:%M:%S %p", "%d %b, %Y, %I:%M:%S %p", "Second"),
}
def compute(
df: Union[pd.DataFrame, dd.DataFrame],
x: Optional[str] = None,
y: Optional[str] = None,
z: Optional[str] = None,
*,
bins: int = 10,
ngroups: int = 10,
largest: bool = True,
nsubgroups: int = 5,
timeunit: str = "auto",
agg: str = "mean",
sample_size: int = 1000,
top_words: int = 30,
stopword: bool = True,
lemmatize: bool = False,
stem: bool = False,
value_range: Optional[Tuple[float, float]] = None,
dtype: Optional[DTypeDef] = None,
) -> Intermediate:
"""
Parameters
----------
df
Dataframe from which plots are to be generated
x: Optional[str], default None
A valid column name from the dataframe
y: Optional[str], default None
A valid column name from the dataframe
z: Optional[str], default None
A valid column name from the dataframe
bins: int, default 10
For a histogram or box plot with numerical x axis, it defines
the number of equal-width bins to use when grouping.
ngroups: int, default 10
When grouping over a categorical column, it defines the
number of groups to show in the plot. Ie, the number of
bars to show in a bar chart.
largest: bool, default True
If true, when grouping over a categorical column, the groups
with the largest count will be output. If false, the groups
with the smallest count will be output.
nsubgroups: int, default 5
If x and y are categorical columns, ngroups refers to
how many groups to show from column x, and nsubgroups refers to
how many subgroups to show from column y in each group in column x.
timeunit: str, default "auto"
Defines the time unit to group values over for a datetime column.
It can be "year", "quarter", "month", "week", "day", "hour",
"minute", "second". With default value "auto", it will use the
time unit such that the resulting number of groups is closest to 15.
agg: str, default "mean"
Specify the aggregate to use when aggregating over a numeric column
sample_size: int, default 1000
Sample size for the scatter plot
top_words: int, default 30
Specify the amount of words to show in the wordcloud and
word frequency bar chart
stopword: bool, default True
Eliminate the stopwords in the text data for plotting wordcloud and
word frequency bar chart
lemmatize: bool, default False
Lemmatize the words in the text data for plotting wordcloud and
word frequency bar chart
stem: bool, default False
Apply Potter Stem on the text data for plotting wordcloud and
word frequency bar chart
value_range: Optional[Tuple[float, float]], default None
The lower and upper bounds on the range of a numerical column.
Applies when column x is specified and column y is unspecified.
dtype: str or DType or dict of str or dict of DType, default None
Specify Data Types for designated column or all columns.
E.g. dtype = {"a": Continuous, "b": "Nominal"} or
dtype = {"a": Continuous(), "b": "nominal"}
or dtype = Continuous() or dtype = "Continuous" or dtype = Continuous()
""" # pylint: disable=too-many-locals
df = to_dask(df)
if not any((x, y, z)):
return compute_overview(df, bins, ngroups, largest, timeunit, dtype)
if sum(v is None for v in (x, y, z)) == 2:
col: str = cast(str, x or y or z)
return compute_univariate(
df,
col,
bins,
ngroups,
largest,
timeunit,
top_words,
stopword,
lemmatize,
stem,
value_range,
dtype,
)
if sum(v is None for v in (x, y, z)) == 1:
x, y = (v for v in (x, y, z) if v is not None)
return compute_bivariate(
df,
x,
y,
bins,
ngroups,
largest,
nsubgroups,
timeunit,
agg,
sample_size,
dtype,
)
if x is not None and y is not None and z is not None:
return compute_trivariate(df, x, y, z, ngroups, largest, timeunit, agg, dtype)
return Intermediate()
def compute_overview(
df: dd.DataFrame,
bins: int,
ngroups: int,
largest: bool,
timeunit: str,
dtype: Optional[DTypeDef] = None,
) -> Intermediate:
# pylint: disable=too-many-arguments,too-many-locals
"""
Compute functions for plot(df)
Parameters
----------
df
Dataframe from which plots are to be generated
bins
For a histogram or box plot with numerical x axis, it defines
the number of equal-width bins to use when grouping.
ngroups
When grouping over a categorical column, it defines the
number of groups to show in the plot. Ie, the number of
bars to show in a bar chart.
largest
If true, when grouping over a categorical column, the groups
with the largest count will be output. If false, the groups
with the smallest count will be output.
timeunit
Defines the time unit to group values over for a datetime column.
It can be "year", "quarter", "month", "week", "day", "hour",
"minute", "second". With default value "auto", it will use the
time unit such that the resulting number of groups is closest to 15.
dtype: str or DType or dict of str or dict of DType, default None
Specify Data Types for designated column or all columns.
E.g. dtype = {"a": Continuous, "b": "Nominal"} or
dtype = {"a": Continuous(), "b": "nominal"}
or dtype = Continuous() or dtype = "Continuous" or dtype = Continuous()
"""
# extract the first rows for checking if a column contains a mutable type
first_rows: pd.DataFrame = df.head() # dd.DataFrame.head triggers a (small) data read
datas: List[Any] = []
dtype_cnts: DefaultDict[str, int] = defaultdict(int)
col_names_dtypes: List[Tuple[str, DType]] = []
for column in df.columns:
srs = df[column]
column_dtype = detect_dtype(srs, dtype)
if is_dtype(column_dtype, Nominal()):
# cast the column as string type if it contains a mutable type
try:
first_rows[column].apply(hash)
except TypeError:
srs = df[column] = srs.dropna().astype(str)
# bar chart
datas.append(calc_bar(srs, ngroups, largest))
col_names_dtypes.append((column, Nominal()))
dtype_cnts["Categorical"] += 1
elif is_dtype(column_dtype, Continuous()):
# histogram
hist = da.histogram(drop_null(srs), bins=bins, range=[srs.min(), srs.max()])
datas.append(hist)
col_names_dtypes.append((column, Continuous()))
dtype_cnts["Numerical"] += 1
elif is_dtype(column_dtype, DateTime()):
datas.append(dask.delayed(calc_line_dt)(df[[column]], timeunit))
col_names_dtypes.append((column, DateTime()))
dtype_cnts["DateTime"] += 1
else:
raise UnreachableError
stats = calc_stats(df, dtype_cnts)
datas, stats = dask.compute(datas, stats)
data = [(col, dtp, dat) for (col, dtp), dat in zip(col_names_dtypes, datas)]
return Intermediate(data=data, stats=stats, visual_type="distribution_grid",)
def compute_univariate(
df: dd.DataFrame,
x: str,
bins: int,
ngroups: int,
largest: bool,
timeunit: str,
top_words: int,
stopword: bool = True,
lemmatize: bool = False,
stem: bool = False,
value_range: Optional[Tuple[float, float]] = None,
dtype: Optional[DTypeDef] = None,
) -> Intermediate:
"""
Compute functions for plot(df, x)
Parameters
----------
df
Dataframe from which plots are to be generated
x
A valid column name from the dataframe
bins
For a histogram or box plot with numerical x axis, it defines
the number of equal-width bins to use when grouping.
ngroups
When grouping over a categorical column, it defines the
number of groups to show in the plot. Ie, the number of
bars to show in a bar chart.
largest
If true, when grouping over a categorical column, the groups
with the largest count will be output. If false, the groups
with the smallest count will be output.
timeunit
Defines the time unit to group values over for a datetime column.
It can be "year", "quarter", "month", "week", "day", "hour",
"minute", "second". With default value "auto", it will use the
time unit such that the resulting number of groups is closest to 15.
top_words: int, default 30
Specify the amount of words to show in the wordcloud and
word frequency bar chart
stopword: bool, default True
Eliminate the stopwords in the text data for plotting wordcloud and
word frequency bar chart
lemmatize: bool, default False
Lemmatize the words in the text data for plotting wordcloud and
word frequency bar chart
stem: bool, default False
Apply Potter Stem on the text data for plotting wordcloud and
word frequency bar chart
value_range
The lower and upper bounds on the range of a numerical column.
Applies when column x is specified and column y is unspecified.
dtype: str or DType or dict of str or dict of DType, default None
Specify Data Types for designated column or all columns.
E.g. dtype = {"a": Continuous, "b": "Nominal"} or
dtype = {"a": Continuous(), "b": "nominal"}
or dtype = Continuous() or dtype = "Continuous" or dtype = Continuous()
"""
# pylint: disable=too-many-locals, too-many-arguments
col_dtype = detect_dtype(df[x], dtype)
if is_dtype(col_dtype, Nominal()):
# extract the column
df_x = df[x]
# calculate the total rows
nrows = df_x.shape[0]
# cast the column as string type if it contains a mutable type
if df_x.head().apply(lambda x: hasattr(x, "__hash__")).any():
# drop_null() will not work if the column conatains a mutable type
df_x = df_x.dropna().astype(str)
# drop null values
df_x = drop_null(df_x)
# calc_word_freq() returns the frequency of words (for the word cloud and word
# frequency bar chart) and the total number of words
word_data = calc_word_freq(df_x, top_words, stopword, lemmatize, stem)
# calc_cat_stats() computes all the categorical stats including the length
# histogram. calc_bar_pie() does the calculations for the bar and pie charts
# NOTE this dictionary could be returned to create_report without
# calling the subsequent compute
cat_data = {
"stats": calc_cat_stats(df_x, nrows, bins),
"bar_pie": calc_bar_pie(df_x, ngroups, largest),
"word_data": word_data,
}
cat_data = dask.compute(cat_data)[0]
return Intermediate(
col=x,
stats=cat_data["stats"],
bar_pie=cat_data["bar_pie"],
word_data=cat_data["word_data"],
visual_type="categorical_column",
)
elif is_dtype(col_dtype, Continuous()):
# calculate the total number of rows then drop the missing values
nrows = df.shape[0]
df_x = drop_null(df[x])
if value_range is not None:
df_x = df_x[df_x.between(*value_range)]
# TODO perhaps we should not use to_dask() on the entire
# initial dataframe and instead only use the column of data
# df_x = df_x.repartition(partition_size="100MB")
# calculate numerical statistics and extract the min and max
num_stats = calc_num_stats(df_x, nrows)
minv, maxv = num_stats["min"], num_stats["max"]
# NOTE this dictionary could be returned to create_report without
# calling the subsequent compute
num_data = {
"hist": da.histogram(df_x, bins=bins, range=[minv, maxv]),
"kde": calc_kde(df_x, bins, minv, maxv),
"box_data": calc_box_new(df_x, num_stats["qntls"]),
"stats": num_stats,
}
num_data = dask.compute(num_data)[0]
return Intermediate(
col=x,
hist=num_data["hist"],
kde=num_data["kde"],
box_data=num_data["box_data"],
stats=num_data["stats"],
visual_type="numerical_column",
)
elif is_dtype(col_dtype, DateTime()):
data_dt: List[Any] = []
# line chart
data_dt.append(dask.delayed(calc_line_dt)(df[[x]], timeunit))
# stats
data_dt.append(dask.delayed(calc_stats_dt)(df[x]))
data, statsdata_dt = dask.compute(*data_dt)
return Intermediate(
col=x, data=data, stats=statsdata_dt, visual_type="datetime_column",
)
else:
raise UnreachableError
def compute_bivariate(
df: dd.DataFrame,
x: str,
y: str,
bins: int,
ngroups: int,
largest: bool,
nsubgroups: int,
timeunit: str,
agg: str,
sample_size: int,
dtype: Optional[DTypeDef] = None,
) -> Intermediate:
"""
Compute functions for plot(df, x, y)
Parameters
----------
df
Dataframe from which plots are to be generated
x
A valid column name from the dataframe
y
A valid column name from the dataframe
bins
For a histogram or box plot with numerical x axis, it defines
the number of equal-width bins to use when grouping.
ngroups
When grouping over a categorical column, it defines the
number of groups to show in the plot. Ie, the number of
bars to show in a bar chart.
largest
If true, when grouping over a categorical column, the groups
with the largest count will be output. If false, the groups
with the smallest count will be output.
nsubgroups
If x and y are categorical columns, ngroups refers to
how many groups to show from column x, and nsubgroups refers to
how many subgroups to show from column y in each group in column x.
timeunit
Defines the time unit to group values over for a datetime column.
It can be "year", "quarter", "month", "week", "day", "hour",
"minute", "second". With default value "auto", it will use the
time unit such that the resulting number of groups is closest to 15.
agg
Specify the aggregate to use when aggregating over a numeric column
sample_size
Sample size for the scatter plot
dtype: str or DType or dict of str or dict of DType, default None
Specify Data Types for designated column or all columns.
E.g. dtype = {"a": Continuous, "b": "Nominal"} or
dtype = {"a": Continuous(), "b": "nominal"}
or dtype = Continuous() or dtype = "Continuous" or dtype = Continuous()
"""
# pylint: disable=too-many-arguments,too-many-locals
xtype = detect_dtype(df[x], dtype)
ytype = detect_dtype(df[y], dtype)
if (
is_dtype(xtype, Nominal())
and is_dtype(ytype, Continuous())
or is_dtype(xtype, Continuous())
and is_dtype(ytype, Nominal())
):
x, y = (x, y) if is_dtype(xtype, Nominal()) else (y, x)
df = drop_null(df[[x, y]])
df[x] = df[x].apply(str, meta=(x, str))
# box plot per group
boxdata = calc_box(df, bins, ngroups, largest, dtype)
# histogram per group
hisdata = calc_hist_by_group(df, bins, ngroups, largest)
return Intermediate(
x=x, y=y, boxdata=boxdata, histdata=hisdata, visual_type="cat_and_num_cols",
)
elif (
is_dtype(xtype, DateTime())
and is_dtype(ytype, Continuous())
or is_dtype(xtype, Continuous())
and is_dtype(ytype, DateTime())
):
x, y = (x, y) if is_dtype(xtype, DateTime()) else (y, x)
df = drop_null(df[[x, y]])
dtnum: List[Any] = []
# line chart
dtnum.append(dask.delayed(calc_line_dt)(df, timeunit, agg))
# box plot
dtnum.append(dask.delayed(calc_box_dt)(df, timeunit))
dtnum = dask.compute(*dtnum)
return Intermediate(
x=x,
y=y,
linedata=dtnum[0],
boxdata=dtnum[1],
visual_type="dt_and_num_cols",
)
elif (
is_dtype(xtype, DateTime())
and is_dtype(ytype, Nominal())
or is_dtype(xtype, Nominal())
and is_dtype(ytype, DateTime())
):
x, y = (x, y) if is_dtype(xtype, DateTime()) else (y, x)
df = drop_null(df[[x, y]])
df[y] = df[y].apply(str, meta=(y, str))
dtcat: List[Any] = []
# line chart
dtcat.append(
dask.delayed(calc_line_dt)(df, timeunit, ngroups=ngroups, largest=largest)
)
# stacked bar chart
dtcat.append(dask.delayed(calc_stacked_dt)(df, timeunit, ngroups, largest))
dtcat = dask.compute(*dtcat)
return Intermediate(
x=x,
y=y,
linedata=dtcat[0],
stackdata=dtcat[1],
visual_type="dt_and_cat_cols",
)
elif is_dtype(xtype, Nominal()) and is_dtype(ytype, Nominal()):
df = drop_null(df[[x, y]])
df[x] = df[x].apply(str, meta=(x, str))
df[y] = df[y].apply(str, meta=(y, str))
# nested bar chart
nesteddata = calc_nested(df, ngroups, nsubgroups)
# stacked bar chart
stackdata = calc_stacked(df, ngroups, nsubgroups)
# heat map
heatmapdata = calc_heatmap(df, ngroups, nsubgroups)
return Intermediate(
x=x,
y=y,
nesteddata=nesteddata,
stackdata=stackdata,
heatmapdata=heatmapdata,
visual_type="two_cat_cols",
)
elif is_dtype(xtype, Continuous()) and is_dtype(ytype, Continuous()):
df = drop_null(df[[x, y]])
# scatter plot
scatdata = calc_scatter(df, sample_size)
# hexbin plot
hexbindata = df.compute()
# box plot
boxdata = calc_box(df, bins)
return Intermediate(
x=x,
y=y,
scatdata=scatdata,
boxdata=boxdata,
hexbindata=hexbindata,
spl_sz=sample_size,
visual_type="two_num_cols",
)
else:
raise UnreachableError
def compute_trivariate(
df: dd.DataFrame,
x: str,
y: str,
z: str,
ngroups: int,
largest: bool,
timeunit: str,
agg: str,
dtype: Optional[DTypeDef] = None,
) -> Intermediate:
"""
Compute functions for plot(df, x, y, z)
Parameters
----------
df
Dataframe from which plots are to be generated
x
A valid column name from the dataframe
y
A valid column name from the dataframe
z
A valid column name from the dataframe
bins
For a histogram or box plot with numerical x axis, it defines
the number of equal-width bins to use when grouping.
ngroups
When grouping over a categorical column, it defines the
number of groups to show in the plot. Ie, the number of
bars to show in a bar chart.
largest
If true, when grouping over a categorical column, the groups
with the largest count will be output. If false, the groups
with the smallest count will be output.
timeunit
Defines the time unit to group values over for a datetime column.
It can be "year", "quarter", "month", "week", "day", "hour",
"minute", "second". With default value "auto", it will use the
time unit such that the resulting number of groups is closest to 15.
agg
Specify the aggregate to use when aggregating over a numeric column
dtype: str or DType or dict of str or dict of DType, default None
Specify Data Types for designated column or all columns.
E.g. dtype = {"a": Continuous, "b": "Nominal"} or
dtype = {"a": Continuous(), "b": "nominal"}
or dtype = Continuous() or dtype = "Continuous" or dtype = Continuous()
"""
# pylint: disable=too-many-arguments
xtype = detect_dtype(df[x], dtype)
ytype = detect_dtype(df[y], dtype)
ztype = detect_dtype(df[z], dtype)
if (
is_dtype(xtype, DateTime())
and is_dtype(ytype, Nominal())
and is_dtype(ztype, Continuous())
):
y, z = z, y
elif (
is_dtype(xtype, Continuous())
and is_dtype(ytype, DateTime())
and is_dtype(ztype, Nominal())
):
x, y = y, x
elif (
is_dtype(xtype, Continuous())
and is_dtype(ytype, Nominal())
and is_dtype(ztype, DateTime())
):
x, y, z = z, x, y
elif (
is_dtype(xtype, Nominal())
and is_dtype(ytype, DateTime())
and is_dtype(ztype, Continuous())
):
x, y, z = y, z, x
elif (
is_dtype(xtype, Nominal())
and is_dtype(ytype, Continuous())
and is_dtype(ztype, DateTime())
):
x, z = z, x
assert (
is_dtype(xtype, DateTime())
and is_dtype(ytype, Continuous())
and is_dtype(ztype, Nominal())
), "x, y, and z must be one each of type datetime, numerical, and categorical"
df = drop_null(df[[x, y, z]])
df[z] = df[z].apply(str, meta=(z, str))
# line chart
data = dask.compute(dask.delayed(calc_line_dt)(df, timeunit, agg, ngroups, largest))
return Intermediate(
x=x, y=y, z=z, agg=agg, data=data[0], visual_type="dt_cat_num_cols",
)
def calc_line_dt(
df: dd.DataFrame,
unit: str,
agg: Optional[str] = None,
ngroups: Optional[int] = None,
largest: Optional[bool] = None,
) -> Union[
Tuple[pd.DataFrame, Dict[str, int], str],
Tuple[pd.DataFrame, str, float],
Tuple[pd.DataFrame, str],
]:
"""
Calculate a line or multiline chart with date on the x axis. If df contains
one datetime column, it will make a line chart of the frequency of values. If
df contains a datetime and categorical column, it will compute the frequency
of each categorical value in each time group. If df contains a datetime and
numerical column, it will compute the aggregate of the numerical column grouped
by the time groups. If df contains a datetime, categorical, and numerical column,
it will compute the aggregate of the numerical column for values in the categorical
column grouped by time.
Parameters
----------
df
A dataframe
unit
The unit of time over which to group the values
agg
Aggregate to use for the numerical column
ngroups
Number of groups for the categorical column
largest
Use the largest or smallest groups in the categorical column
"""
# pylint: disable=too-many-locals
x = df.columns[0] # time column
unit = _get_timeunit(df[x].min(), df[x].max(), 100) if unit == "auto" else unit
if unit not in DTMAP.keys():
raise ValueError
grouper = pd.Grouper(key=x, freq=DTMAP[unit][0]) # for grouping the time values
# multiline charts
if ngroups and largest:
hist_dict: Dict[str, Tuple[np.ndarray, np.ndarray, List[str]]] = dict()
hist_lst: List[Tuple[np.ndarray, np.ndarray, List[str]]] = list()
agg = (
"freq" if agg is None else agg
) # default agg if unspecified for notational concision
# categorical column for grouping over, each resulting group is a line in the chart
grpby_col = df.columns[1] if len(df.columns) == 2 else df.columns[2]
df, grp_cnt_stats, largest_grps = _calc_groups(df, grpby_col, ngroups, largest)
groups = df.groupby([grpby_col])
for grp in largest_grps:
srs = groups.get_group(grp)
# calculate the frequencies or aggregate value in each time group
if len(df.columns) == 3:
dfr = srs.groupby(grouper)[df.columns[1]].agg(agg).reset_index()
else:
dfr = srs[x].to_frame().groupby(grouper).size().reset_index()
dfr.columns = [x, agg]
# if grouping by week, make the label for the week the beginning Sunday
dfr[x] = dfr[x] - pd.to_timedelta(6, unit="d") if unit == "week" else dfr[x]
# format the label
dfr["lbl"] = dfr[x].dt.to_period("S").dt.strftime(DTMAP[unit][1])
hist_lst.append((list(dfr[agg]), list(dfr[x]), list(dfr["lbl"])))
hist_lst = dask.compute(*hist_lst)
for elem in zip(largest_grps, hist_lst):
hist_dict[elem[0]] = elem[1]
return hist_dict, grp_cnt_stats, DTMAP[unit][3]
# single line charts
if agg is None: # frequency of datetime column
miss_pct = round(df[x].isna().sum() / len(df) * 100, 1)
dfr = drop_null(df).groupby(grouper).size().reset_index()
dfr.columns = [x, "freq"]
dfr["pct"] = dfr["freq"] / len(df) * 100
else: # aggregate over a second column
dfr = df.groupby(grouper)[df.columns[1]].agg(agg).reset_index()
dfr.columns = [x, agg]
dfr[x] = dfr[x] - pd.to_timedelta(6, unit="d") if unit == "week" else dfr[x]
dfr["lbl"] = dfr[x].dt.to_period("S").dt.strftime(DTMAP[unit][1])
return (dfr, DTMAP[unit][3], miss_pct) if agg is None else (dfr, DTMAP[unit][3])
def calc_box_dt(
df: dd.DataFrame, unit: str
) -> Tuple[pd.DataFrame, List[str], List[float], str]:
"""
Calculate a box plot with date on the x axis.
Parameters
----------
df
A dataframe with one datetime and one numerical column
unit
The unit of time over which to group the values
"""
x, y = df.columns[0], df.columns[1] # time column
unit = _get_timeunit(df[x].min(), df[x].max(), 10) if unit == "auto" else unit
if unit not in DTMAP.keys():
raise ValueError
grps = df.groupby(pd.Grouper(key=x, freq=DTMAP[unit][0])) # time groups
# box plot for the values in each time group
df = pd.concat([_calc_box_stats(g[1][y], g[0], True) for g in grps], axis=1,)
df = df.append(pd.Series({c: i + 1 for i, c in enumerate(df.columns)}, name="x",)).T
# If grouping by week, make the label for the week the beginning Sunday
df.index = df.index - pd.to_timedelta(6, unit="d") if unit == "week" else df.index
df.index.name = "grp"
df = df.reset_index()
df["grp"] = df["grp"].dt.to_period("S").dt.strftime(DTMAP[unit][2])
df["x0"], df["x1"] = df["x"] - 0.8, df["x"] - 0.2 # width of whiskers for plotting
outx, outy = _calc_box_otlrs(df)
return df, outx, outy, DTMAP[unit][3]
def calc_stacked_dt(
df: dd.DataFrame, unit: str, ngroups: int, largest: bool,
) -> Tuple[pd.DataFrame, Dict[str, int], str]:
"""
Calculate a stacked bar chart with date on the x axis
Parameters
----------
df
A dataframe with one datetime and one categorical column
unit
The unit of time over which to group the values
ngroups
Number of groups for the categorical column
largest
Use the largest or smallest groups in the categorical column
"""
# pylint: disable=too-many-locals
x, y = df.columns[0], df.columns[1] # time column
unit = _get_timeunit(df[x].min(), df[x].max(), 10) if unit == "auto" else unit
if unit not in DTMAP.keys():
raise ValueError
# get the largest groups
df_grps, grp_cnt_stats, _ = _calc_groups(df, y, ngroups, largest)
grouper = (pd.Grouper(key=x, freq=DTMAP[unit][0]),) # time grouper
# pivot table of counts with date groups as index and categorical values as column names
dfr = pd.pivot_table(
df_grps, index=grouper, columns=y, aggfunc=len, fill_value=0,
).rename_axis(None)
# if more than ngroups categorical values, aggregate the smallest groups into "Others"
if grp_cnt_stats[f"{y}_ttl"] > grp_cnt_stats[f"{y}_shw"]:
grp_cnts = df.groupby(pd.Grouper(key=x, freq=DTMAP[unit][0])).size()
dfr["Others"] = grp_cnts - dfr.sum(axis=1)
dfr.index = ( # If grouping by week, make the label for the week the beginning Sunday
dfr.index - pd.to_timedelta(6, unit="d") if unit == "week" else dfr.index
)
dfr.index = dfr.index.to_period("S").strftime(DTMAP[unit][2]) # format labels
return dfr, grp_cnt_stats, DTMAP[unit][3]
def calc_bar(
srs: dd.Series, ngroups: int, largest: bool
) -> Tuple[dd.DataFrame, dd.core.Scalar, dd.core.Scalar]:
"""
Calculates the counts of categorical values, the total number of
categorical values, and the number of non-null cells required
for a bar chart in plot(df).
Parameters
----------
srs
One categorical column
ngroups
Number of groups to return
largest
If true, show the groups with the largest count,
else show the groups with the smallest count
"""
# drop null values
srs_present = drop_null(srs)
# number of present (not null) values
npresent = srs_present.shape[0]
# counts of unique values in the series
grps = srs_present.value_counts(sort=False)
# total number of groups
ttl_grps = grps.shape[0]
# select the largest or smallest groups
fnl_grp_cnts = grps.nlargest(ngroups) if largest else grps.nsmallest(ngroups)
return fnl_grp_cnts.to_frame(), ttl_grps, npresent
def calc_bar_pie(
srs: dd.Series, ngroups: int, largest: bool
) -> Tuple[dd.DataFrame, dd.core.Scalar]:
"""
Calculates the counts of categorical values and the total number of
categorical values required for the bar and pie charts in plot(df, x).
Parameters
----------
srs
One categorical column
ngroups
Number of groups to return
largest
If true, show the groups with the largest count,
else show the groups with the smallest count
"""
# counts of unique values in the series
grps = srs.value_counts(sort=False)
# total number of groups
ttl_grps = grps.shape[0]
# select the largest or smallest groups
fnl_grp_cnts = grps.nlargest(ngroups) if largest else grps.nsmallest(ngroups)
return fnl_grp_cnts.to_frame(), ttl_grps
def calc_word_freq(
srs: dd.Series,
top_words: int = 30,
stopword: bool = True,
lemmatize: bool = False,
stem: bool = False,
) -> Tuple[dd.Series, dd.core.Scalar]:
"""
Parse a categorical column of text data into words, and then
compute the frequency distribution of words and the total
number of words.
Parameters
----------
srs
One categorical column
top_words
Number of highest frequency words to show in the
wordcloud and word frequency bar chart
stopword
If True, remove stop words, else keep them
lemmatize
If True, lemmatize the words before computing
the word frequencies, else don't
stem
If True, extract the stem of the words before
computing the word frequencies, else don't
"""
# pylint: disable=unnecessary-lambda
if stopword:
# use a regex to replace stop words with empty string
srs = srs.str.replace(r"\b(?:{})\b".format("|".join(english_stopwords)), "")
# replace all non-alphanumeric characters with an empty string, and convert to lowercase
srs = srs.str.replace(r"[^\w+ ]", "").str.lower()
# split each string on whitespace into words then apply "explode()" to "stack" all
# the words into a series
# NOTE this is slow. One possibly better solution: after .split(), count the words
# immediately rather than create a new series with .explode() and apply
# .value_counts()
srs = srs.str.split().explode()
# lemmatize and stem
if lemmatize or stem:
srs = srs.dropna()
if lemmatize:
lem = WordNetLemmatizer()
srs = srs.apply(lambda x: lem.lemmatize(x), meta=(srs.name, "object"))
if stem:
porter = PorterStemmer()
srs = srs.apply(lambda x: porter.stem(x), meta=(srs.name, "object"))
# counts of words, excludes null values
word_cnts = srs.value_counts(sort=False)
# total number of words
nwords = word_cnts.sum()
# words with the highest frequency
fnl_word_cnts = word_cnts.nlargest(n=top_words)
return fnl_word_cnts, nwords
def calc_kde(
srs: dd.Series, bins: int, minv: float, maxv: float,
) -> Tuple[Tuple[da.core.Array, da.core.Array], np.ndarray]:
"""
Calculate a density histogram and its corresponding kernel density
estimate over a given series. The kernel is Gaussian.
Parameters
----------
data
One numerical column over which to compute the histogram and kde
bins
Number of bins to use in the histogram
"""
# compute the density histogram
hist = da.histogram(srs, bins=bins, range=[minv, maxv], density=True)
# probability density function for the series
# NOTE gaussian_kde triggers a .compute()
try:
kde = gaussian_kde(
srs.map_partitions(lambda x: x.sample(min(1000, x.shape[0])), meta=srs)
)
except np.linalg.LinAlgError:
kde = None
return hist, kde
def calc_box_new(srs: dd.Series, qntls: dd.Series) -> Dict[str, Any]:
"""
Calculate the data required for a box plot
Parameters
----------
srs
One numerical column from which to compute the box plot data
qntls
Quantiles from the normal Q-Q plot
"""
# box plot stats
# inter-quartile range
# TODO figure out how to extract a scalar from a Dask series without using a function like sum()
qrtl1 = qntls.loc[0.25].sum()
qrtl3 = qntls.loc[0.75].sum()
iqr = qrtl3 - qrtl1
srs_iqr = srs[srs.between(qrtl1 - 1.5 * iqr, qrtl3 + 1.5 * iqr)]
# outliers
otlrs = srs[~srs.between(qrtl1 - 1.5 * iqr, qrtl3 + 1.5 * iqr)]
# randomly sample at most 100 outliers from each partition without replacement
otlrs = otlrs.map_partitions(lambda x: x.sample(min(100, x.shape[0])), meta=otlrs)
box_data = {
"grp": srs.name,
"q1": qrtl1,
"q2": qntls.loc[0.5].sum(),
"q3": qrtl3,
"lw": srs_iqr.min(),
"uw": srs_iqr.max(),
"otlrs": otlrs.values,
"x": 1, # x, x0, and x1 are for plotting the box plot with bokeh
"x0": 0.2,
"x1": 0.8,
}
return box_data
def calc_stats(
df: dd.DataFrame, dtype_cnts: Dict[str, int]
) -> Dict[str, Union[int, dd.core.Scalar, Dict[str, int]]]:
"""
Calculate the statistics for plot(df) from a DataFrame
Parameters
----------
df
a DataFrame
dtype_cnts
a dictionary that contains the count for each type
"""
stats = {
"nrows": df.shape[0],
"ncols": df.shape[1],
"npresent_cells": df.count().sum(),
"nrows_wo_dups": df.drop_duplicates().shape[0],
"mem_use": df.memory_usage(deep=True).sum(),
"dtype_cnts": dtype_cnts,
}
return stats
def calc_num_stats(srs: dd.Series, nrows: dd.core.Scalar,) -> Dict[str, Any]:
"""
Calculate statistics for a numerical column
Parameters
----------
srs
a numerical column
nrows
number of rows in the column before dropping null values
"""
stats = {
"nrows": nrows,
"npresent": srs.shape[0],
"nunique": srs.nunique(),
"ninfinite": ((srs == np.inf) | (srs == -np.inf)).sum(),
"nzero": (srs == 0).sum(),
"min": srs.min(),
"max": srs.max(),
"qntls": srs.quantile(np.linspace(0.01, 0.99, 99)),
"mean": srs.mean(),
"std": srs.std(),
"skew": skew(srs),
"kurt": kurtosis(srs),
"mem_use": srs.memory_usage(),
}
return stats
def calc_cat_stats(
srs: dd.Series, nrows: int, bins: int,
) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
"""
Calculate stats for a categorical column
Parameters
----------
srs
a categorical column
nrows
number of rows before dropping null values
bins
number of bins for the category length frequency histogram
"""
# overview stats
stats = {
"nrows": nrows,
"npresent": srs.shape[0],
"nunique": srs.nunique(),
"mem_use": srs.memory_usage(),
"first_rows": srs.loc[:4],
}
# length stats
lengths = srs.str.len()
minv, maxv = lengths.min(), lengths.max()
hist = da.histogram(lengths.values, bins=bins, range=[minv, maxv])
length_stats = {
"Mean": lengths.mean(),
"Median": lengths.quantile(0.5),
"Minimum": minv,
"Maximum": maxv,
"hist": hist,
}
# letter stats
letter_stats = {
"Count": srs.str.count(r"[a-zA-Z]").sum(),
"Lowercase Letter": srs.str.count(r"[a-z]").sum(),
"Space Separator": srs.str.count(r"[ ]").sum(),
"Uppercase Letter": srs.str.count(r"[A-Z]").sum(),
"Dash Punctuation": srs.str.count(r"[-]").sum(),
"Decimal Number": srs.str.count(r"[0-9]").sum(),
}
return stats, length_stats, letter_stats
def calc_box(
df: dd.DataFrame,
bins: int,
ngroups: int = 10,
largest: bool = True,
dtype: Optional[DTypeDef] = None,
) -> Tuple[pd.DataFrame, List[str], List[float], Optional[Dict[str, int]]]:
"""
Compute a box plot over either
1) the values in one column
2) the values corresponding to groups in another column
3) the values corresponding to binning another column
Parameters
----------
df
Dataframe with one or two columns
bins
Number of bins to use if df has two numerical columns
ngroups
Number of groups to show if df has a categorical and numerical column
largest
When calculating a box plot per group, select the largest or smallest groups
dtype: str or DType or dict of str or dict of DType, default None
Specify Data Types for designated column or all columns.
E.g. dtype = {"a": Continuous, "b": "Nominal"} or
dtype = {"a": Continuous(), "b": "nominal"}
or dtype = Continuous() or dtype = "Continuous" or dtype = Continuous()
Returns
-------
Tuple[pd.DataFrame, List[str], List[float], Dict[str, int]]
The box plot statistics in a dataframe, a list of the outlier
groups and another list of the outlier values, a dictionary
logging the sampled group output
"""
# pylint: disable=too-many-locals
grp_cnt_stats = None # to inform the user of sampled output
x = df.columns[0]
if len(df.columns) == 1:
df = _calc_box_stats(df[x], x)
else:
y = df.columns[1]
if is_dtype(detect_dtype(df[x], dtype), Continuous()) and is_dtype(
detect_dtype(df[y], dtype), Continuous()
):
minv, maxv, cnt = dask.compute(df[x].min(), df[x].max(), df[x].nunique())
bins = cnt if cnt < bins else bins
endpts = np.linspace(minv, maxv, num=bins + 1)
# calculate a box plot over each bin
df = dd.concat(
[
_calc_box_stats(
df[(df[x] >= endpts[i]) & (df[x] < endpts[i + 1])][y],
f"[{endpts[i]},{endpts[i + 1]})",
)
if i != len(endpts) - 2
else _calc_box_stats(
df[(df[x] >= endpts[i]) & (df[x] <= endpts[i + 1])][y],
f"[{endpts[i]},{endpts[i + 1]}]",
)
for i in range(len(endpts) - 1)
],
axis=1,
).compute()
endpts_df = pd.DataFrame(
[endpts[:-1], endpts[1:]], ["lb", "ub"], df.columns
)
df = pd.concat([df, endpts_df], axis=0)
else:
df, grp_cnt_stats, largest_grps = _calc_groups(df, x, ngroups, largest)
# calculate a box plot over each group
df = dd.concat(
[_calc_box_stats(df[df[x] == grp][y], grp) for grp in largest_grps],
axis=1,
).compute()
df = df.append(pd.Series({c: i + 1 for i, c in enumerate(df.columns)}, name="x",)).T
df.index.name = "grp"
df = df.reset_index()
df["x0"], df["x1"] = df["x"] - 0.8, df["x"] - 0.2 # width of whiskers for plotting
outx, outy = _calc_box_otlrs(df)
return df, outx, outy, grp_cnt_stats
def calc_hist_by_group(
df: dd.DataFrame, bins: int, ngroups: int, largest: bool
) -> Tuple[pd.DataFrame, Dict[str, int]]:
"""
Compute a histogram over the values corresponding to the groups in another column
Parameters
----------
df
Dataframe with one categorical and one numerical column
bins
Number of bins to use in the histogram
ngroups
Number of groups to show from the categorical column
largest
Select the largest or smallest groups
Returns
-------
Tuple[pd.DataFrame, Dict[str, int]]
The histograms in a dataframe and a dictionary
logging the sampled group output
"""
# pylint: disable=too-many-locals
hist_dict: Dict[str, Tuple[np.ndarray, np.ndarray, List[str]]] = dict()
hist_lst: List[Tuple[np.ndarray, np.ndarray, List[str]]] = list()
df, grp_cnt_stats, largest_grps = _calc_groups(df, df.columns[0], ngroups, largest)
# create a histogram for each group
groups = df.groupby([df.columns[0]])
minv, maxv = dask.compute(df[df.columns[1]].min(), df[df.columns[1]].max())
for grp in largest_grps:
grp_srs = groups.get_group(grp)[df.columns[1]]
hist_arr, bins_arr = da.histogram(grp_srs, range=[minv, maxv], bins=bins)
intervals = _format_bin_intervals(bins_arr)
hist_lst.append((hist_arr, bins_arr, intervals))
hist_lst = dask.compute(*hist_lst)
for elem in zip(largest_grps, hist_lst):
hist_dict[elem[0]] = elem[1]
return hist_dict, grp_cnt_stats
def calc_scatter(df: dd.DataFrame, sample_size: int) -> pd.DataFrame:
"""
Extracts the points to use in a scatter plot
Parameters
----------
df
Dataframe with two numerical columns
sample_size
the number of points to randomly sample in the scatter plot
Returns
-------
pd.DataFrame
A dataframe containing the scatter points
"""
if len(df) > sample_size:
df = df.sample(frac=sample_size / len(df))
return df.compute()
def calc_nested(
df: dd.DataFrame, ngroups: int, nsubgroups: int,
) -> Tuple[pd.DataFrame, Dict[str, int]]:
"""
Calculate a nested bar chart of the counts of two columns
Parameters
----------
df
Dataframe with two categorical columns
ngroups
Number of groups to show from the first column
nsubgroups
Number of subgroups (from the second column) to show in each group
Returns
-------
Tuple[pd.DataFrame, Dict[str, int]]
The bar chart counts in a dataframe and a dictionary
logging the sampled group output
"""
x, y = df.columns[0], df.columns[1]
df, grp_cnt_stats, _ = _calc_groups(df, x, ngroups)
df2 = df.groupby([x, y]).size().reset_index()
max_subcol_cnt = df2.groupby(x).size().max().compute()
df2.columns = [x, y, "cnt"]
df_res = (
df2.groupby(x)[[y, "cnt"]]
.apply(
lambda x: x.nlargest(n=nsubgroups, columns="cnt"),
meta=({y: "f8", "cnt": "i8"}),
)
.reset_index()
.compute()
)
df_res["grp_names"] = list(zip(df_res[x], df_res[y]))
df_res = df_res.drop([x, "level_1", y], axis=1)
grp_cnt_stats[f"{y}_ttl"] = max_subcol_cnt
grp_cnt_stats[f"{y}_shw"] = min(max_subcol_cnt, nsubgroups)
return df_res, grp_cnt_stats
def calc_stacked(
df: dd.DataFrame, ngroups: int, nsubgroups: int,
) -> Tuple[pd.DataFrame, Dict[str, int]]:
"""
Calculate a stacked bar chart of the counts of two columns
Parameters
----------
df
two categorical columns
ngroups
number of groups to show from the first column
nsubgroups
number of subgroups (from the second column) to show in each group
Returns
-------
Tuple[pd.DataFrame, Dict[str, int]]
The bar chart counts in a dataframe and a dictionary
logging the sampled group output
"""
x, y = df.columns[0], df.columns[1]
df, grp_cnt_stats, largest_grps = _calc_groups(df, x, ngroups)
fin_df = pd.DataFrame()
for grp in largest_grps:
df_grp = df[df[x] == grp]
df_res = df_grp.groupby(y).size().nlargest(n=nsubgroups) / len(df_grp) * 100
df_res = df_res.to_frame().compute().T
df_res.columns = list(df_res.columns)
df_res["Others"] = 100 - df_res.sum(axis=1)
fin_df = fin_df.append(df_res, sort=False)
fin_df = fin_df.fillna(value=0)
others = fin_df.pop("Others")
if others.sum() > 1e-4:
fin_df["Others"] = others
fin_df.index = list(largest_grps)
return fin_df, grp_cnt_stats
def calc_heatmap(
df: dd.DataFrame, ngroups: int, nsubgroups: int,
) -> Tuple[pd.DataFrame, Dict[str, int]]:
"""
Calculate a heatmap of the counts of two columns
Parameters
----------
df
Dataframe with two categorical columns
ngroups
Number of groups to show from the first column
nsubgroups
Number of subgroups (from the second column) to show in each group
Returns
-------
Tuple[pd.DataFrame, Dict[str, int]]
The heatmap counts in a dataframe and a dictionary
logging the sampled group output
"""
x, y = df.columns[0], df.columns[1]
df, grp_cnt_stats, _ = _calc_groups(df, x, ngroups)
srs = df.groupby(y).size()
srs_lrgst = srs.nlargest(n=nsubgroups)
largest_subgrps = list(srs_lrgst.index.compute())
df = df[df[y].isin(largest_subgrps)]
df_res = df.groupby([x, y]).size().reset_index().compute()
df_res.columns = ["x", "y", "cnt"]
df_res = pd.pivot_table(
df_res, index=["x", "y"], values="cnt", fill_value=0, aggfunc=np.sum,
).reset_index()
grp_cnt_stats[f"{y}_ttl"] = len(srs.index.compute())
grp_cnt_stats[f"{y}_shw"] = len(largest_subgrps)
return df_res, grp_cnt_stats
def calc_stats_dt(srs: dd.Series) -> Dict[str, str]:
"""
Calculate stats from a datetime column
Parameters
----------
srs
a datetime column
Returns
-------
Dict[str, str]
Dictionary that contains Overview
"""
size = len(srs) # include nan
count = srs.count() # exclude nan
uniq_count = srs.nunique()
overview_dict = {
"Distinct Count": uniq_count,
"Unique (%)": uniq_count / count,
"Missing": size - count,
"Missing (%)": 1 - (count / size),
"Memory Size": srs.memory_usage(),
"Minimum": srs.min(),
"Maximum": srs.max(),
}
return overview_dict
def _calc_box_stats(grp_srs: dd.Series, grp: str, dlyd: bool = False) -> pd.DataFrame:
"""
Auxiliary function to calculate the Tukey box plot statistics
dlyd is for if this function is called when dask is computing in parallel (dask.delayed)
"""
stats: Dict[str, Any] = dict()
try: # this is a bad fix for the problem of when there is no data passed to this function
if dlyd:
qntls = np.round(grp_srs.quantile([0.25, 0.50, 0.75]), 3)
else:
qntls = np.round(grp_srs.quantile([0.25, 0.50, 0.75]).compute(), 3)
stats["q1"], stats["q2"], stats["q3"] = qntls[0.25], qntls[0.50], qntls[0.75]
except ValueError:
stats["q1"], stats["q2"], stats["q3"] = np.nan, np.nan, np.nan
iqr = stats["q3"] - stats["q1"]
stats["lw"] = grp_srs[grp_srs >= stats["q1"] - 1.5 * iqr].min()
stats["uw"] = grp_srs[grp_srs <= stats["q3"] + 1.5 * iqr].max()
if not dlyd:
stats["lw"], stats["uw"] = dask.compute(stats["lw"], stats["uw"])
otlrs = grp_srs[(grp_srs < stats["lw"]) | (grp_srs > stats["uw"])]
if len(otlrs) > 100: # sample 100 outliers
otlrs = otlrs.sample(frac=100 / len(otlrs))
stats["otlrs"] = list(otlrs) if dlyd else list(otlrs.compute())
return pd.DataFrame({grp: stats})
def _calc_box_otlrs(df: dd.DataFrame) -> Tuple[List[str], List[float]]:
"""
Calculate the outliers for a box plot
"""
outx: List[str] = [] # list for the outlier groups
outy: List[float] = [] # list for the outlier values
for ind in df.index:
otlrs = df.loc[ind]["otlrs"]
outx = outx + [df.loc[ind]["grp"]] * len(otlrs)
outy = outy + otlrs
return outx, outy
def _calc_groups(
df: dd.DataFrame, x: str, ngroups: int, largest: bool = True
) -> Tuple[dd.DataFrame, Dict[str, int], List[str]]:
"""
Auxillary function to parse the dataframe to consist of only the
groups with the largest counts
"""
# group count statistics to inform the user of the sampled output
grp_cnt_stats: Dict[str, int] = dict()
srs = df.groupby(x).size()
srs_lrgst = srs.nlargest(n=ngroups) if largest else srs.nsmallest(n=ngroups)
try:
largest_grps = list(srs_lrgst.index.compute())
grp_cnt_stats[f"{x}_ttl"] = len(srs.index.compute())
except AttributeError:
largest_grps = list(srs_lrgst.index)
grp_cnt_stats[f"{x}_ttl"] = len(srs.index)
df = df[df[x].isin(largest_grps)]
grp_cnt_stats[f"{x}_shw"] = len(largest_grps)
return df, grp_cnt_stats, largest_grps
def _format_bin_intervals(bins_arr: np.ndarray) -> List[str]:
"""
Auxillary function to format bin intervals in a histogram
"""
bins_arr = np.round(bins_arr, 3)
bins_arr = [int(val) if float(val).is_integer() else val for val in bins_arr]
intervals = [
f"[{bins_arr[i]}, {bins_arr[i + 1]})" for i in range(len(bins_arr) - 2)
]
intervals.append(f"[{bins_arr[-2]},{bins_arr[-1]}]")
return intervals
def _get_timeunit(min_time: pd.Timestamp, max_time: pd.Timestamp, dflt: int) -> str:
"""
Auxillary function to find an appropriate time unit. Will find the
time unit such that the number of time units are closest to dflt.
"""
dt_secs = {
"year": 60 * 60 * 24 * 365,
"quarter": 60 * 60 * 24 * 91,
"month": 60 * 60 * 24 * 30,
"week": 60 * 60 * 24 * 7,
"day": 60 * 60 * 24,
"hour": 60 * 60,
"minute": 60,
"second": 1,
}
time_rng_secs = (max_time - min_time).total_seconds()
prev_bin_cnt, prev_unit = 0, "year"
for unit, secs_in_unit in dt_secs.items():
cur_bin_cnt = time_rng_secs / secs_in_unit
if abs(prev_bin_cnt - dflt) < abs(cur_bin_cnt - dflt):
return prev_unit
prev_bin_cnt = cur_bin_cnt
prev_unit = unit
return prev_unit
|
[
"pandas.DataFrame",
"dask.array.stats.skew",
"dask.delayed",
"nltk.stem.PorterStemmer",
"nltk.stem.WordNetLemmatizer",
"dask.array.histogram",
"typing.cast",
"dask.array.stats.kurtosis",
"pandas.pivot_table",
"collections.defaultdict",
"pandas.to_timedelta",
"pandas.Grouper",
"numpy.linspace",
"dask.compute",
"numpy.round",
"pandas.concat"
] |
[((7664, 7680), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (7675, 7680), False, 'from collections import defaultdict\n'), ((8921, 8947), 'dask.compute', 'dask.compute', (['datas', 'stats'], {}), '(datas, stats)\n', (8933, 8947), False, 'import dask\n'), ((25009, 25047), 'pandas.Grouper', 'pd.Grouper', ([], {'key': 'x', 'freq': 'DTMAP[unit][0]'}), '(key=x, freq=DTMAP[unit][0])\n', (25019, 25047), True, 'import pandas as pd\n'), ((34802, 34864), 'dask.array.histogram', 'da.histogram', (['srs'], {'bins': 'bins', 'range': '[minv, maxv]', 'density': '(True)'}), '(srs, bins=bins, range=[minv, maxv], density=True)\n', (34814, 34864), True, 'import dask.array as da\n'), ((38471, 38530), 'dask.array.histogram', 'da.histogram', (['lengths.values'], {'bins': 'bins', 'range': '[minv, maxv]'}), '(lengths.values, bins=bins, range=[minv, maxv])\n', (38483, 38530), True, 'import dask.array as da\n'), ((43907, 43930), 'dask.compute', 'dask.compute', (['*hist_lst'], {}), '(*hist_lst)\n', (43919, 43930), False, 'import dask\n'), ((46579, 46593), 'pandas.DataFrame', 'pd.DataFrame', ([], {}), '()\n', (46591, 46593), True, 'import pandas as pd\n'), ((50325, 50351), 'pandas.DataFrame', 'pd.DataFrame', (['{grp: stats}'], {}), '({grp: stats})\n', (50337, 50351), True, 'import pandas as pd\n'), ((51790, 51811), 'numpy.round', 'np.round', (['bins_arr', '(3)'], {}), '(bins_arr, 3)\n', (51798, 51811), True, 'import numpy as np\n'), ((5064, 5086), 'typing.cast', 'cast', (['str', '(x or y or z)'], {}), '(str, x or y or z)\n', (5068, 5086), False, 'from typing import Any, DefaultDict, Dict, List, Optional, Tuple, Union, cast\n'), ((26489, 26512), 'dask.compute', 'dask.compute', (['*hist_lst'], {}), '(*hist_lst)\n', (26501, 26512), False, 'import dask\n'), ((27890, 27928), 'pandas.Grouper', 'pd.Grouper', ([], {'key': 'x', 'freq': 'DTMAP[unit][0]'}), '(key=x, freq=DTMAP[unit][0])\n', (27900, 27928), True, 'import pandas as pd\n'), ((29488, 29526), 'pandas.Grouper', 'pd.Grouper', ([], {'key': 'x', 'freq': 'DTMAP[unit][0]'}), '(key=x, freq=DTMAP[unit][0])\n', (29498, 29526), True, 'import pandas as pd\n'), ((33814, 33833), 'nltk.stem.WordNetLemmatizer', 'WordNetLemmatizer', ([], {}), '()\n', (33831, 33833), False, 'from nltk.stem import PorterStemmer, WordNetLemmatizer\n'), ((33943, 33958), 'nltk.stem.PorterStemmer', 'PorterStemmer', ([], {}), '()\n', (33956, 33958), False, 'from nltk.stem import PorterStemmer, WordNetLemmatizer\n'), ((37665, 37674), 'dask.array.stats.skew', 'skew', (['srs'], {}), '(srs)\n', (37669, 37674), False, 'from dask.array.stats import kurtosis, skew\n'), ((37692, 37705), 'dask.array.stats.kurtosis', 'kurtosis', (['srs'], {}), '(srs)\n', (37700, 37705), False, 'from dask.array.stats import kurtosis, skew\n'), ((43729, 43781), 'dask.array.histogram', 'da.histogram', (['grp_srs'], {'range': '[minv, maxv]', 'bins': 'bins'}), '(grp_srs, range=[minv, maxv], bins=bins)\n', (43741, 43781), True, 'import dask.array as da\n'), ((50034, 50072), 'dask.compute', 'dask.compute', (["stats['lw']", "stats['uw']"], {}), "(stats['lw'], stats['uw'])\n", (50046, 50072), False, 'import dask\n'), ((12795, 12817), 'dask.compute', 'dask.compute', (['cat_data'], {}), '(cat_data)\n', (12807, 12817), False, 'import dask\n'), ((18083, 18103), 'dask.compute', 'dask.compute', (['*dtnum'], {}), '(*dtnum)\n', (18095, 18103), False, 'import dask\n'), ((23367, 23393), 'dask.delayed', 'dask.delayed', (['calc_line_dt'], {}), '(calc_line_dt)\n', (23379, 23393), False, 'import dask\n'), ((27119, 27147), 'pandas.to_timedelta', 'pd.to_timedelta', (['(6)'], {'unit': '"""d"""'}), "(6, unit='d')\n", (27134, 27147), True, 'import pandas as pd\n'), ((28267, 28295), 'pandas.to_timedelta', 'pd.to_timedelta', (['(6)'], {'unit': '"""d"""'}), "(6, unit='d')\n", (28282, 28295), True, 'import pandas as pd\n'), ((29648, 29724), 'pandas.pivot_table', 'pd.pivot_table', (['df_grps'], {'index': 'grouper', 'columns': 'y', 'aggfunc': 'len', 'fill_value': '(0)'}), '(df_grps, index=grouper, columns=y, aggfunc=len, fill_value=0)\n', (29662, 29724), True, 'import pandas as pd\n'), ((30152, 30180), 'pandas.to_timedelta', 'pd.to_timedelta', (['(6)'], {'unit': '"""d"""'}), "(6, unit='d')\n", (30167, 30180), True, 'import pandas as pd\n'), ((37565, 37592), 'numpy.linspace', 'np.linspace', (['(0.01)', '(0.99)', '(99)'], {}), '(0.01, 0.99, 99)\n', (37576, 37592), True, 'import numpy as np\n'), ((41017, 41054), 'numpy.linspace', 'np.linspace', (['minv', 'maxv'], {'num': '(bins + 1)'}), '(minv, maxv, num=bins + 1)\n', (41028, 41054), True, 'import numpy as np\n'), ((41735, 41800), 'pandas.DataFrame', 'pd.DataFrame', (['[endpts[:-1], endpts[1:]]', "['lb', 'ub']", 'df.columns'], {}), "([endpts[:-1], endpts[1:]], ['lb', 'ub'], df.columns)\n", (41747, 41800), True, 'import pandas as pd\n'), ((41848, 41882), 'pandas.concat', 'pd.concat', (['[df, endpts_df]'], {'axis': '(0)'}), '([df, endpts_df], axis=0)\n', (41857, 41882), True, 'import pandas as pd\n'), ((48113, 48201), 'pandas.pivot_table', 'pd.pivot_table', (['df_res'], {'index': "['x', 'y']", 'values': '"""cnt"""', 'fill_value': '(0)', 'aggfunc': 'np.sum'}), "(df_res, index=['x', 'y'], values='cnt', fill_value=0,\n aggfunc=np.sum)\n", (48127, 48201), True, 'import pandas as pd\n'), ((13840, 13889), 'dask.array.histogram', 'da.histogram', (['df_x'], {'bins': 'bins', 'range': '[minv, maxv]'}), '(df_x, bins=bins, range=[minv, maxv])\n', (13852, 13889), True, 'import dask.array as da\n'), ((14069, 14091), 'dask.compute', 'dask.compute', (['num_data'], {}), '(num_data)\n', (14081, 14091), False, 'import dask\n'), ((14615, 14637), 'dask.compute', 'dask.compute', (['*data_dt'], {}), '(*data_dt)\n', (14627, 14637), False, 'import dask\n'), ((18898, 18918), 'dask.compute', 'dask.compute', (['*dtcat'], {}), '(*dtcat)\n', (18910, 18918), False, 'import dask\n'), ((17939, 17965), 'dask.delayed', 'dask.delayed', (['calc_line_dt'], {}), '(calc_line_dt)\n', (17951, 17965), False, 'import dask\n'), ((18026, 18051), 'dask.delayed', 'dask.delayed', (['calc_box_dt'], {}), '(calc_box_dt)\n', (18038, 18051), False, 'import dask\n'), ((26224, 26252), 'pandas.to_timedelta', 'pd.to_timedelta', (['(6)'], {'unit': '"""d"""'}), "(6, unit='d')\n", (26239, 26252), True, 'import pandas as pd\n'), ((29942, 29980), 'pandas.Grouper', 'pd.Grouper', ([], {'key': 'x', 'freq': 'DTMAP[unit][0]'}), '(key=x, freq=DTMAP[unit][0])\n', (29952, 29980), True, 'import pandas as pd\n'), ((14464, 14490), 'dask.delayed', 'dask.delayed', (['calc_line_dt'], {}), '(calc_line_dt)\n', (14476, 14490), False, 'import dask\n'), ((14550, 14577), 'dask.delayed', 'dask.delayed', (['calc_stats_dt'], {}), '(calc_stats_dt)\n', (14562, 14577), False, 'import dask\n'), ((18685, 18711), 'dask.delayed', 'dask.delayed', (['calc_line_dt'], {}), '(calc_line_dt)\n', (18697, 18711), False, 'import dask\n'), ((18819, 18848), 'dask.delayed', 'dask.delayed', (['calc_stacked_dt'], {}), '(calc_stacked_dt)\n', (18831, 18848), False, 'import dask\n'), ((8663, 8689), 'dask.delayed', 'dask.delayed', (['calc_line_dt'], {}), '(calc_line_dt)\n', (8675, 8689), False, 'import dask\n')]
|
################################################################################
# Numba-DPPY
#
# Copyright 2020-2021 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
################################################################################
import dpctl
import numpy as np
import pytest
from numba import njit
import numba_dppy as dppy
from numba_dppy.tests._helper import (
assert_auto_offloading,
filter_strings,
is_gen12,
)
list_of_filter_strs = [
"opencl:gpu:0",
"level_zero:gpu:0",
"opencl:cpu:0",
]
@pytest.fixture(params=list_of_filter_strs)
def filter_str(request):
return request.param
list_of_trig_ops = [
"sin",
"cos",
"tan",
"arcsin",
"arccos",
"arctan",
"arctan2",
"sinh",
"cosh",
"tanh",
"arcsinh",
"arccosh",
"arctanh",
"deg2rad",
"rad2deg",
"degrees",
"radians",
]
@pytest.fixture(params=list_of_trig_ops)
def trig_op(request):
return request.param
list_of_dtypes = [
np.float32,
np.float64,
]
@pytest.fixture(params=list_of_trig_ops)
def dtype(request):
return request.param
@pytest.fixture(params=list_of_dtypes)
def input_arrays(request):
# The size of input and out arrays to be used
N = 2048
# Note: These inputs do not work for all of the functions and
# can result in warnings. E.g. arccosh needs the range of values
# to be greater than 0, while arccos needs them to be [-1,1].
# These warnings are relatively benign as NumPy will return "nan"
# for such cases.
a = np.array(np.random.random(N), request.param)
b = np.array(np.random.random(N), request.param)
return a, b
@pytest.mark.parametrize("filter_str", filter_strings)
def test_trigonometric_fn(filter_str, trig_op, input_arrays):
# FIXME: Why does archcosh fail on Gen12 discrete graphics card?
if trig_op == "arccosh" and is_gen12(filter_str):
pytest.skip()
a, b = input_arrays
trig_fn = getattr(np, trig_op)
actual = np.empty(shape=a.shape, dtype=a.dtype)
expected = np.empty(shape=a.shape, dtype=a.dtype)
if trig_op == "arctan2":
@njit
def f(a, b):
return trig_fn(a, b)
device = dpctl.SyclDevice(filter_str)
with dpctl.device_context(device), assert_auto_offloading():
actual = f(a, b)
expected = trig_fn(a, b)
else:
@njit
def f(a):
return trig_fn(a)
device = dpctl.SyclDevice(filter_str)
with dpctl.device_context(device), assert_auto_offloading():
actual = f(a)
expected = trig_fn(a)
np.testing.assert_allclose(actual, expected, rtol=1e-5, atol=0)
|
[
"dpctl.SyclDevice",
"numba_dppy.tests._helper.assert_auto_offloading",
"numpy.empty",
"dpctl.device_context",
"numpy.testing.assert_allclose",
"pytest.fixture",
"pytest.skip",
"numpy.random.random",
"numba_dppy.tests._helper.is_gen12",
"pytest.mark.parametrize"
] |
[((1088, 1130), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'list_of_filter_strs'}), '(params=list_of_filter_strs)\n', (1102, 1130), False, 'import pytest\n'), ((1440, 1479), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'list_of_trig_ops'}), '(params=list_of_trig_ops)\n', (1454, 1479), False, 'import pytest\n'), ((1585, 1624), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'list_of_trig_ops'}), '(params=list_of_trig_ops)\n', (1599, 1624), False, 'import pytest\n'), ((1673, 1710), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'list_of_dtypes'}), '(params=list_of_dtypes)\n', (1687, 1710), False, 'import pytest\n'), ((2219, 2272), 'pytest.mark.parametrize', 'pytest.mark.parametrize', (['"""filter_str"""', 'filter_strings'], {}), "('filter_str', filter_strings)\n", (2242, 2272), False, 'import pytest\n'), ((2553, 2591), 'numpy.empty', 'np.empty', ([], {'shape': 'a.shape', 'dtype': 'a.dtype'}), '(shape=a.shape, dtype=a.dtype)\n', (2561, 2591), True, 'import numpy as np\n'), ((2607, 2645), 'numpy.empty', 'np.empty', ([], {'shape': 'a.shape', 'dtype': 'a.dtype'}), '(shape=a.shape, dtype=a.dtype)\n', (2615, 2645), True, 'import numpy as np\n'), ((3173, 3237), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['actual', 'expected'], {'rtol': '(1e-05)', 'atol': '(0)'}), '(actual, expected, rtol=1e-05, atol=0)\n', (3199, 3237), True, 'import numpy as np\n'), ((2111, 2130), 'numpy.random.random', 'np.random.random', (['N'], {}), '(N)\n', (2127, 2130), True, 'import numpy as np\n'), ((2164, 2183), 'numpy.random.random', 'np.random.random', (['N'], {}), '(N)\n', (2180, 2183), True, 'import numpy as np\n'), ((2436, 2456), 'numba_dppy.tests._helper.is_gen12', 'is_gen12', (['filter_str'], {}), '(filter_str)\n', (2444, 2456), False, 'from numba_dppy.tests._helper import assert_auto_offloading, filter_strings, is_gen12\n'), ((2466, 2479), 'pytest.skip', 'pytest.skip', ([], {}), '()\n', (2477, 2479), False, 'import pytest\n'), ((2763, 2791), 'dpctl.SyclDevice', 'dpctl.SyclDevice', (['filter_str'], {}), '(filter_str)\n', (2779, 2791), False, 'import dpctl\n'), ((3014, 3042), 'dpctl.SyclDevice', 'dpctl.SyclDevice', (['filter_str'], {}), '(filter_str)\n', (3030, 3042), False, 'import dpctl\n'), ((2805, 2833), 'dpctl.device_context', 'dpctl.device_context', (['device'], {}), '(device)\n', (2825, 2833), False, 'import dpctl\n'), ((2835, 2859), 'numba_dppy.tests._helper.assert_auto_offloading', 'assert_auto_offloading', ([], {}), '()\n', (2857, 2859), False, 'from numba_dppy.tests._helper import assert_auto_offloading, filter_strings, is_gen12\n'), ((3056, 3084), 'dpctl.device_context', 'dpctl.device_context', (['device'], {}), '(device)\n', (3076, 3084), False, 'import dpctl\n'), ((3086, 3110), 'numba_dppy.tests._helper.assert_auto_offloading', 'assert_auto_offloading', ([], {}), '()\n', (3108, 3110), False, 'from numba_dppy.tests._helper import assert_auto_offloading, filter_strings, is_gen12\n')]
|
import tkinter
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import requests
from scipy.signal import medfilt
from copy import deepcopy
from json import loads
import numpy as np
with open('endomondo.config', 'r') as conf:
username = conf.readline()[:-1]
password = conf.readline()
class Requester:
def __init__(self, email, password):
self.email = email
self.password = password
self.session = requests.session()
self.cookies = {}
self.headers = {
'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:72.0) Gecko/20100101 Firefox/72.0',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'en-US,en;q=0.5',
'Referer': 'https://www.endomondo.com/home',
'Connection': 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'max-age=0',
'TE': 'Trailers',
}
self.data = '{"email":"' + self.email + '","password":"' + self.password + '","remember":true}'
def login(self):
# getting csrf token, jsessionid and awselb
response = self.session.get('https://www.endomondo.com/', headers=self.headers, cookies=self.cookies)
self.headers["X-CSRF-TOKEN"] = response.cookies["CSRF_TOKEN"]
self.headers["Referer"] = "https://www.endomondo.com/login"
self.headers["Origin"] = "https://www.endomondo.com"
self.headers["Content-Type"] = "application/json;charset=utf-8"
response2 = self.session.post('https://www.endomondo.com/rest/session', headers=self.headers,
cookies=self.cookies, data=self.data)
def get_workout(self, url):
self.headers["Referer"] = url
response = self.session.get("https://www.endomondo.com/rest/v1/" + url[26:], headers=self.headers,
cookies=self.cookies)
return response.content.decode('utf-8')
class Training:
class Plot:
def __init__(self, data, y_label, line_color):
self.raw_data = data
self.data = data
self.y_label = y_label
self.line_color = line_color
self.visible = True
self.inherited = None
def set_visible(self, boolean):
self.visible = boolean
def average(self, _i):
self.data = medfilt(self.raw_data, _i)
def __init__(self, json, line_type):
self.decoded = loads(json)
self.line_type = line_type
self.name = self.decoded['id']
# creating all plots
heart_rate = []
for i in range(len(self.decoded['points']['points'])):
if "heart_rate" in self.decoded['points']['points'][i]['sensor_data']:
heart_rate.append(self.decoded['points']['points'][i]['sensor_data']['heart_rate'])
else:
if heart_rate:
heart_rate.append(heart_rate[-1])
else:
heart_rate.append(0)
self.plot_heart_rate = self.Plot(heart_rate, "[heart rate] = bpm", 'tab:red')
self.distance = [self.decoded["points"]["points"][i]["distance"]
for i in range(len(self. decoded['points']['points']))]
speed = []
for i in range(len(self.decoded['points']['points'])):
if "speed" in self.decoded['points']['points'][i]['sensor_data']:
speed.append(self.decoded['points']['points'][i]['sensor_data']['speed'])
else:
if speed:
speed.append(speed[-1])
else:
speed.append(0)
avg = np.average(speed)
for j, i in enumerate(speed):
try:
speed[j] = 60 / i
except ZeroDivisionError:
speed[j] = 60 / avg
self.plot_speed = self.Plot(speed, "[speed] = minpkm", 'tab:blue')
alt = []
for i in range(len(self.decoded['points']['points'])):
if "altitude" in self.decoded['points']['points'][i]:
alt.append(self.decoded['points']['points'][i]['altitude'])
else:
if alt:
alt.append(alt[-1])
else:
alt.append(None)
for j, i in enumerate(alt):
if i is None:
for el in alt[j:]:
if el:
alt[j] = el
self.plot_altitude = self.Plot(alt, "[altitude] = m", 'tab:green')
self.plot_speed.inherited = [self.distance, self.line_type, self.name]
self.plot_altitude.inherited = [self.distance, self.line_type, self.name]
self.plot_heart_rate.inherited = [self.distance, self.line_type, self.name]
self.date = self.decoded["local_start_time"]
self.empty_plot = self.Plot([0 for _ in range(len(self.decoded['points']['points']))], "", "tab:blue")
self.empty_plot.set_visible(False)
self.empty_plot.inherited = [self.distance, self.line_type, self.name]
def txt_changed_0(txt):
if len(txt) >= 50:
Trainings[0] = Training(user.get_workout(txt), '-')
plot(states)
def txt_changed_1(txt):
if not txt:
Trainings.pop(1)
if len(txt) >= 50:
if len(Trainings) >= 2:
Trainings[1] = Training(user.get_workout(txt), '--')
else:
Trainings.append(Training(user.get_workout(txt), '--'))
plot(states)
def txt_changed_2(txt):
if not txt:
Trainings.pop(2)
if len(txt) >= 50:
if len(Trainings) >= 3:
Trainings[2] = Training(user.get_workout(txt), ':')
else:
Trainings.append(Training(user.get_workout(txt), ':'))
plot(states)
def txt_changed_3(txt):
if not txt:
Trainings.pop(3)
if len(txt) >= 50:
if len(Trainings) >= 4:
Trainings[3] = Training(user.get_workout(txt), '-.')
else:
Trainings.append(Training(user.get_workout(txt), '-.'))
plot(states)
def slide(numb):
numb = int(numb)
for training in Trainings:
training.plot_speed.average(numb)
training.plot_heart_rate.average(numb)
plot(states)
def slide_change(n):
n = int(n)
if not n % 2:
slider.set(n + 1)
def btn_slide():
slide(int(slider.get()))
def check_box():
global states
states['plot_speed'] = varSpeed.get()
states['plot_altitude'] = varAltitude.get()
states['plot_heart_rate'] = varHeart.get()
plot(states)
def submit():
global txtBoxes
temp = [txtBox0.get(), txtBox1.get(), txtBox2.get(), txtBox3.get()]
for i, element in enumerate(temp):
if not element == txtBoxes[i]:
if i == 0:
txt_changed_0(element)
if i == 1:
txt_changed_1(element)
if i == 2:
txt_changed_2(element)
if i == 3:
txt_changed_3(element)
txtBoxes[i] = element
user = Requester(username, password)
user.login()
Trainings = [Training(user.get_workout("https://www.endomondo.com/users/19154541/workouts/1458780940"), '-')]
states = {'plot_speed': True, 'plot_altitude': True, 'plot_heart_rate': False}
txtBoxes = ['', '', '', '']
root = tkinter.Tk()
root.wm_title("Endomondo Analyzer")
fig = Figure(figsize=(5, 4), dpi=100)
fig.add_subplot(111)
ax1 = fig.subplots()
ax2 = ax1.twinx()
canvas = FigureCanvasTkAgg(fig, master=root) # A tk.DrawingArea.
canvas.draw()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
toolbar = NavigationToolbar2Tk(canvas, root)
toolbar.update()
canvas.get_tk_widget().pack(side=tkinter.TOP, fill=tkinter.BOTH, expand=1)
txtBox0 = tkinter.Entry(root)
txtBox0.place(x=20, y=40)
lbl0 = tkinter.Label(root, text="durchgezogen")
lbl0.place(x=150, y=40)
lbl1 = tkinter.Label(root, text="gestrichelt")
lbl1.place(x=150, y=80)
lbl0 = tkinter.Label(root, text="gepunktet")
lbl0.place(x=150, y=120)
lbl1 = tkinter.Label(root, text="gestrichpunktet")
lbl1.place(x=150, y=160)
txtBox1 = tkinter.Entry(root)
txtBox1.place(x=20, y=80)
txtBox2 = tkinter.Entry(root)
txtBox2.place(x=20, y=120)
txtBox3 = tkinter.Entry(root)
txtBox3.place(x=20, y=160)
slider = tkinter.Scale(root, from_=1, to=35, orient=tkinter.HORIZONTAL, length=300, command=slide_change)
slider.place(x=20, y=580)
varSpeed = tkinter.BooleanVar()
chckSpeed = tkinter.Checkbutton(root, text="Speed", command=check_box, variable=varSpeed)
chckSpeed.place(x=20, y=410)
chckSpeed.select()
varAltitude = tkinter.BooleanVar()
chckAltitude = tkinter.Checkbutton(root, text="Altitude", command=check_box, variable=varAltitude)
chckAltitude.place(x=20, y=450)
chckAltitude.select()
varHeart = tkinter.BooleanVar()
chckHeart = tkinter.Checkbutton(root, text="Heart Rate", command=check_box, variable=varHeart)
chckHeart.place(x=20, y=490)
btnSubmit = tkinter.Button(root, command=submit, text="Submit")
btnSubmit.place(x=20, y=200)
btnChangeScale = tkinter.Button(root, command=btn_slide, text="Change Average")
btnChangeScale.place(x=20, y=540)
Dates = tkinter.StringVar(root)
lblDates = tkinter.Label(root, textvariable=Dates)
lblDates.place(x=20, y=250)
def _quit():
root.quit() # stops mainloop
root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
def plot(_dict):
# choosing which plots to show on which axis
plot1 = None
plot2 = None
dictionary = deepcopy(_dict)
for element in dictionary:
if dictionary[element]:
plot1 = element
dictionary[element] = 0
break
for element in dictionary:
if dictionary[element]:
plot2 = element
dictionary[element] = 0
break
global ax1
global ax2
color = ""
ax1.clear()
ax2.clear()
# defining lists of plots
if plot1 == "plot_speed":
plots1 = [i.plot_speed for i in Trainings]
elif plot1 == "plot_altitude":
plots1 = [i.plot_altitude for i in Trainings]
elif plot1 == "plot_heart_rate":
plots1 = [i.plot_heart_rate for i in Trainings]
if plot2 == "plot_altitude":
plots2 = [i.plot_altitude for i in Trainings]
elif plot2 == "plot_heart_rate":
plots2 = [i.plot_heart_rate for i in Trainings]
if plot1 is None:
plots1 = [Trainings[0].empty_plot]
if plot2 is None:
plots2 = [Trainings[0].empty_plot]
color = plots1[0].line_color
ax1.set_xlabel('[distance] = km')
ax1.set_ylabel(plots1[0].y_label, color=color)
dates = "Dates:\n"
for training in Trainings:
dates = dates + training.date[:10] + "\n"
Dates.set(dates)
for pl in plots1:
ax1.plot(pl.inherited[0], pl.data, color=color, visible=pl.visible, linestyle=pl.inherited[1])
ax1.tick_params(axis='y', labelcolor=color)
color = plots2[0].line_color
ax2.set_xlabel('[distance] = km')
ax2.set_ylabel(plots2[0].y_label, color=color)
for pl in plots2:
ax2.plot(pl.inherited[0], pl.data, color=color, visible=pl.visible, linestyle=pl.inherited[1])
ax2.tick_params(axis='y', labelcolor=color)
fig.subplots_adjust(left=0.2)
fig.canvas.draw_idle()
plot(states)
fig.canvas.draw_idle()
button = tkinter.Button(master=root, text="Quit", command=_quit)
button.pack(side=tkinter.BOTTOM)
tkinter.mainloop()
|
[
"matplotlib.backends.backend_tkagg.NavigationToolbar2Tk",
"tkinter.Checkbutton",
"tkinter.StringVar",
"copy.deepcopy",
"requests.session",
"json.loads",
"numpy.average",
"tkinter.mainloop",
"tkinter.Button",
"tkinter.Entry",
"scipy.signal.medfilt",
"matplotlib.figure.Figure",
"tkinter.Scale",
"tkinter.BooleanVar",
"tkinter.Label",
"tkinter.Tk",
"matplotlib.backends.backend_tkagg.FigureCanvasTkAgg"
] |
[((7376, 7388), 'tkinter.Tk', 'tkinter.Tk', ([], {}), '()\n', (7386, 7388), False, 'import tkinter\n'), ((7432, 7463), 'matplotlib.figure.Figure', 'Figure', ([], {'figsize': '(5, 4)', 'dpi': '(100)'}), '(figsize=(5, 4), dpi=100)\n', (7438, 7463), False, 'from matplotlib.figure import Figure\n'), ((7534, 7569), 'matplotlib.backends.backend_tkagg.FigureCanvasTkAgg', 'FigureCanvasTkAgg', (['fig'], {'master': 'root'}), '(fig, master=root)\n', (7551, 7569), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n'), ((7691, 7725), 'matplotlib.backends.backend_tkagg.NavigationToolbar2Tk', 'NavigationToolbar2Tk', (['canvas', 'root'], {}), '(canvas, root)\n', (7711, 7725), False, 'from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk\n'), ((7829, 7848), 'tkinter.Entry', 'tkinter.Entry', (['root'], {}), '(root)\n', (7842, 7848), False, 'import tkinter\n'), ((7882, 7922), 'tkinter.Label', 'tkinter.Label', (['root'], {'text': '"""durchgezogen"""'}), "(root, text='durchgezogen')\n", (7895, 7922), False, 'import tkinter\n'), ((7954, 7993), 'tkinter.Label', 'tkinter.Label', (['root'], {'text': '"""gestrichelt"""'}), "(root, text='gestrichelt')\n", (7967, 7993), False, 'import tkinter\n'), ((8025, 8062), 'tkinter.Label', 'tkinter.Label', (['root'], {'text': '"""gepunktet"""'}), "(root, text='gepunktet')\n", (8038, 8062), False, 'import tkinter\n'), ((8095, 8138), 'tkinter.Label', 'tkinter.Label', (['root'], {'text': '"""gestrichpunktet"""'}), "(root, text='gestrichpunktet')\n", (8108, 8138), False, 'import tkinter\n'), ((8174, 8193), 'tkinter.Entry', 'tkinter.Entry', (['root'], {}), '(root)\n', (8187, 8193), False, 'import tkinter\n'), ((8230, 8249), 'tkinter.Entry', 'tkinter.Entry', (['root'], {}), '(root)\n', (8243, 8249), False, 'import tkinter\n'), ((8287, 8306), 'tkinter.Entry', 'tkinter.Entry', (['root'], {}), '(root)\n', (8300, 8306), False, 'import tkinter\n'), ((8345, 8445), 'tkinter.Scale', 'tkinter.Scale', (['root'], {'from_': '(1)', 'to': '(35)', 'orient': 'tkinter.HORIZONTAL', 'length': '(300)', 'command': 'slide_change'}), '(root, from_=1, to=35, orient=tkinter.HORIZONTAL, length=300,\n command=slide_change)\n', (8358, 8445), False, 'import tkinter\n'), ((8480, 8500), 'tkinter.BooleanVar', 'tkinter.BooleanVar', ([], {}), '()\n', (8498, 8500), False, 'import tkinter\n'), ((8513, 8590), 'tkinter.Checkbutton', 'tkinter.Checkbutton', (['root'], {'text': '"""Speed"""', 'command': 'check_box', 'variable': 'varSpeed'}), "(root, text='Speed', command=check_box, variable=varSpeed)\n", (8532, 8590), False, 'import tkinter\n'), ((8653, 8673), 'tkinter.BooleanVar', 'tkinter.BooleanVar', ([], {}), '()\n', (8671, 8673), False, 'import tkinter\n'), ((8689, 8777), 'tkinter.Checkbutton', 'tkinter.Checkbutton', (['root'], {'text': '"""Altitude"""', 'command': 'check_box', 'variable': 'varAltitude'}), "(root, text='Altitude', command=check_box, variable=\n varAltitude)\n", (8708, 8777), False, 'import tkinter\n'), ((8838, 8858), 'tkinter.BooleanVar', 'tkinter.BooleanVar', ([], {}), '()\n', (8856, 8858), False, 'import tkinter\n'), ((8871, 8958), 'tkinter.Checkbutton', 'tkinter.Checkbutton', (['root'], {'text': '"""Heart Rate"""', 'command': 'check_box', 'variable': 'varHeart'}), "(root, text='Heart Rate', command=check_box, variable=\n varHeart)\n", (8890, 8958), False, 'import tkinter\n'), ((8996, 9047), 'tkinter.Button', 'tkinter.Button', (['root'], {'command': 'submit', 'text': '"""Submit"""'}), "(root, command=submit, text='Submit')\n", (9010, 9047), False, 'import tkinter\n'), ((9096, 9158), 'tkinter.Button', 'tkinter.Button', (['root'], {'command': 'btn_slide', 'text': '"""Change Average"""'}), "(root, command=btn_slide, text='Change Average')\n", (9110, 9158), False, 'import tkinter\n'), ((9202, 9225), 'tkinter.StringVar', 'tkinter.StringVar', (['root'], {}), '(root)\n', (9219, 9225), False, 'import tkinter\n'), ((9237, 9276), 'tkinter.Label', 'tkinter.Label', (['root'], {'textvariable': 'Dates'}), '(root, textvariable=Dates)\n', (9250, 9276), False, 'import tkinter\n'), ((11425, 11480), 'tkinter.Button', 'tkinter.Button', ([], {'master': 'root', 'text': '"""Quit"""', 'command': '_quit'}), "(master=root, text='Quit', command=_quit)\n", (11439, 11480), False, 'import tkinter\n'), ((11515, 11533), 'tkinter.mainloop', 'tkinter.mainloop', ([], {}), '()\n', (11531, 11533), False, 'import tkinter\n'), ((9614, 9629), 'copy.deepcopy', 'deepcopy', (['_dict'], {}), '(_dict)\n', (9622, 9629), False, 'from copy import deepcopy\n'), ((511, 529), 'requests.session', 'requests.session', ([], {}), '()\n', (527, 529), False, 'import requests\n'), ((2558, 2569), 'json.loads', 'loads', (['json'], {}), '(json)\n', (2563, 2569), False, 'from json import loads\n'), ((3762, 3779), 'numpy.average', 'np.average', (['speed'], {}), '(speed)\n', (3772, 3779), True, 'import numpy as np\n'), ((2466, 2492), 'scipy.signal.medfilt', 'medfilt', (['self.raw_data', '_i'], {}), '(self.raw_data, _i)\n', (2473, 2492), False, 'from scipy.signal import medfilt\n')]
|
#!/usr/bin/env python
###############################################################################
# $Id$
#
# Project: GDAL/OGR Test Suite
# Purpose: Test basic integration with Numeric Python.
# Author: <NAME>, <EMAIL>
#
###############################################################################
# Copyright (c) 2003, <NAME> <<EMAIL>>
# Copyright (c) 2009-2010, <NAME> <even dot rouault at mines-paris dot org>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without limitation
# the rights to use, copy, modify, merge, publish, distribute, sublicense,
# and/or sell copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
# DEALINGS IN THE SOFTWARE.
###############################################################################
import sys
sys.path.append( '../pymod' )
import gdaltest
from osgeo import gdal
###############################################################################
# verify that we can load Numeric python, and find the Numpy driver.
def numpy_rw_1():
gdaltest.numpy_drv = None
try:
from osgeo import gdalnumeric
gdalnumeric.zeros
except:
return 'skip'
try:
import _gdal
_gdal.GDALRegister_NUMPY() # only needed for old style bindings.
gdal.AllRegister()
except:
pass
gdaltest.numpy_drv = gdal.GetDriverByName( 'NUMPY' )
if gdaltest.numpy_drv is None:
gdaltest.post_reason( 'NUMPY driver not found!' )
return 'fail'
return 'success'
###############################################################################
# Load a test file into a memory Numpy array, and verify the checksum.
def numpy_rw_2():
if gdaltest.numpy_drv is None:
return 'skip'
from osgeo import gdalnumeric
array = gdalnumeric.LoadFile( 'data/utmsmall.tif' )
if array is None:
gdaltest.post_reason( 'Failed to load utmsmall.tif into array')
return 'fail'
ds = gdalnumeric.OpenArray( array )
if ds is None:
gdaltest.post_reason( 'Failed to open memory array as dataset.' )
return 'fail'
bnd = ds.GetRasterBand(1)
if bnd.Checksum() != 50054:
gdaltest.post_reason( 'Didnt get expected checksum on reopened file')
return 'fail'
ds = None
return 'success'
###############################################################################
# Test loading complex data.
def numpy_rw_3():
if gdaltest.numpy_drv is None:
return 'skip'
ds = gdal.Open( 'data/cint_sar.tif' )
array = ds.ReadAsArray()
if array[2][3] != 116-16j:
print(array[0][2][3])
gdaltest.post_reason( 'complex value read improperly.' )
return 'fail'
return 'success'
###############################################################################
# Test a band read with downsampling.
def numpy_rw_4():
if gdaltest.numpy_drv is None:
return 'skip'
ds = gdal.Open( 'data/byte.tif' )
array = ds.GetRasterBand(1).ReadAsArray(0,0,20,20,5,5)
if array[2][3] != 123:
print(array[2][3])
gdaltest.post_reason( 'Read wrong value - perhaps downsampling algorithm has changed subtly?' )
return 'fail'
return 'success'
###############################################################################
# Test reading a multi-band file.
def numpy_rw_5():
if gdaltest.numpy_drv is None:
return 'skip'
from osgeo import gdalnumeric
array = gdalnumeric.LoadFile('data/rgbsmall.tif',35,21,1,1)
if array[0][0][0] != 78:
print(array)
gdaltest.post_reason( 'value read improperly.' )
return 'fail'
if array[1][0][0] != 117:
print(array)
gdaltest.post_reason( 'value read improperly.' )
return 'fail'
if array[2][0][0] != 24:
print(array)
gdaltest.post_reason( 'value read improperly.' )
return 'fail'
array = gdalnumeric.LoadFile('data/rgbsmall.tif', buf_xsize=1, buf_ysize=1, resample_alg = gdal.GRIORA_Bilinear)
if array.shape[0] != 3 or array.shape[1] != 1 or array.shape[2] != 1:
print(array.shape)
gdaltest.post_reason( 'wrong array shape.' )
return 'fail'
if array[0][0][0] != 70 or array[1][0][0] != 97 or array[2][0][0] != 29:
print(array)
gdaltest.post_reason( 'value read improperly.' )
return 'fail'
import numpy
array = numpy.zeros([3, 1, 1], dtype = numpy.uint8)
ds = gdal.Open('data/rgbsmall.tif')
ds.ReadAsArray( buf_obj = array, resample_alg = gdal.GRIORA_Bilinear )
if array[0][0][0] != 70 or array[1][0][0] != 97 or array[2][0][0] != 29:
print(array)
gdaltest.post_reason( 'value read improperly.' )
return 'fail'
return 'success'
###############################################################################
# Check that Band.ReadAsArray() can accept an already allocated array (#2658, #3028)
def numpy_rw_6():
if gdaltest.numpy_drv is None:
return 'skip'
import numpy
from osgeo import gdalnumeric
ds = gdal.Open( 'data/byte.tif' )
array = numpy.zeros( [ds.RasterYSize, ds.RasterXSize], numpy.uint8 )
array_res = ds.GetRasterBand(1).ReadAsArray(buf_obj = array)
if array is not array_res:
return 'fail'
ds2 = gdalnumeric.OpenArray( array )
if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum():
return 'fail'
return 'success'
###############################################################################
# Check that Dataset.ReadAsArray() can accept an already allocated array (#2658, #3028)
def numpy_rw_7():
if gdaltest.numpy_drv is None:
return 'skip'
import numpy
from osgeo import gdalnumeric
ds = gdal.Open( 'data/byte.tif' )
array = numpy.zeros( [1, ds.RasterYSize, ds.RasterXSize], numpy.uint8 )
array_res = ds.ReadAsArray(buf_obj = array)
if array is not array_res:
return 'fail'
ds2 = gdalnumeric.OpenArray( array )
if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum():
return 'fail'
# Try again with a 2D array
array = numpy.zeros( [ds.RasterYSize, ds.RasterXSize], numpy.uint8 )
array_res = ds.ReadAsArray(buf_obj = array)
if array is not array_res:
return 'fail'
ds2 = gdalnumeric.OpenArray( array )
if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum():
return 'fail'
# With a multi band file
ds = gdal.Open( 'data/rgbsmall.tif' )
array = numpy.zeros( [ds.RasterCount, ds.RasterYSize, ds.RasterXSize], numpy.uint8 )
array_res = ds.ReadAsArray(buf_obj = array)
if array is not array_res:
return 'fail'
ds2 = gdalnumeric.OpenArray( array )
if ds2.GetRasterBand(1).Checksum() != ds.GetRasterBand(1).Checksum():
return 'fail'
return 'success'
###############################################################################
# Check that Dataset.ReadAsArray() with multi-band data
def numpy_rw_8():
if gdaltest.numpy_drv is None:
return 'skip'
import numpy
from osgeo import gdalnumeric
ds = gdal.Open( 'data/rgbsmall.tif' )
array = numpy.zeros( [ds.RasterCount,ds.RasterYSize, ds.RasterXSize], numpy.uint8 )
ds.ReadAsArray(buf_obj = array)
ds2 = gdalnumeric.OpenArray( array )
for i in range(1, ds.RasterCount):
if ds2.GetRasterBand(i).Checksum() != ds.GetRasterBand(i).Checksum():
return 'fail'
return 'success'
###############################################################################
# Test Band.WriteArray()
def numpy_rw_9():
if gdaltest.numpy_drv is None:
return 'skip'
ds = gdal.Open( 'data/byte.tif' )
array = ds.ReadAsArray()
out_ds = gdal.GetDriverByName('MEM').Create('', ds.RasterYSize, ds.RasterXSize)
out_ds.GetRasterBand(1).WriteArray(array)
cs = out_ds.GetRasterBand(1).Checksum()
out_ds = None
ds = None
if cs != 4672:
gdaltest.post_reason('did not get expected checksum')
print(cs)
return 'fail'
return 'success'
###############################################################################
# Test signed byte handling
def numpy_rw_10():
if gdaltest.numpy_drv is None:
return 'skip'
import numpy
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/signed8.tif', 2, 1, options = ['PIXELTYPE=SIGNEDBYTE'])
ar = numpy.empty([1, 2], dtype = numpy.int8)
ar[0][0] = -128
ar[0][1] = 127
ds.GetRasterBand(1).WriteArray(ar)
ds = None
ds = gdal.Open('/vsimem/signed8.tif')
ar2 = ds.ReadAsArray()
ar3 = numpy.empty_like(ar2)
ds.GetRasterBand(1).ReadAsArray(buf_obj = ar3)
ds = None
gdal.Unlink('/vsimem/signed8.tif')
if ar2[0][0] != -128 or ar2[0][1] != 127:
gdaltest.post_reason('did not get expected result (1)')
print(ar2)
return 'fail'
if ar3[0][0] != -128 or ar3[0][1] != 127:
gdaltest.post_reason('did not get expected result (2)')
print(ar3)
return 'fail'
return 'success'
###############################################################################
# Test all datatypes
def numpy_rw_11():
if gdaltest.numpy_drv is None:
return 'skip'
import numpy
type_tuples = [ ( 'uint8', gdal.GDT_Byte, numpy.uint8, 255 ),
( 'uint16', gdal.GDT_UInt16, numpy.uint16, 65535 ),
( 'int16', gdal.GDT_Int16, numpy.int16, -32767 ),
( 'uint32', gdal.GDT_UInt32, numpy.uint32, 4294967295 ),
( 'int32', gdal.GDT_Int32, numpy.int32, -2147483648 ),
( 'float32', gdal.GDT_Float32, numpy.float32, 1.23 ),
( 'float64', gdal.GDT_Float64, numpy.float64, 1.23456789 ),
( 'cint16', gdal.GDT_CInt16, numpy.complex64, -32768 + 32767j ),
( 'cint32', gdal.GDT_CInt32, numpy.complex64, -32769 + 32768j ),
( 'cfloat32', gdal.GDT_CFloat32, numpy.complex64, -32768.5 + 32767.5j ),
( 'cfloat64', gdal.GDT_CFloat64, numpy.complex128, -32768.123456 + 32767.123456j ) ]
for type_tuple in type_tuples:
ds = gdal.GetDriverByName('GTiff').Create('/vsimem/' + type_tuple[0], 1, 1, 1, type_tuple[1])
tmp = ds.ReadAsArray()
if tmp.dtype != type_tuple[2]:
gdaltest.post_reason('did not get expected numpy type')
print(type_tuple)
return 'fail'
ar = numpy.empty([1, 1], dtype = type_tuple[2])
ar[0][0] = type_tuple[3]
ds.GetRasterBand(1).WriteArray(ar)
ds = None
ds = gdal.Open('/vsimem/' + type_tuple[0])
ar2 = ds.ReadAsArray()
ar3 = numpy.empty_like(ar2)
ds.GetRasterBand(1).ReadAsArray(buf_obj = ar3)
ds = None
gdal.Unlink('/vsimem/' + type_tuple[0])
if (type_tuple[0] == 'float32' and abs(ar2[0][0] - type_tuple[3]) > 1e-6) or \
(type_tuple[0] != 'float32' and ar2[0][0] != type_tuple[3]):
gdaltest.post_reason('did not get expected result (1)')
print(ar2)
print(type_tuple)
return 'fail'
if (type_tuple[0] == 'float32' and abs(ar3[0][0] - type_tuple[3]) > 1e-6) or \
(type_tuple[0] != 'float32' and ar3[0][0] != type_tuple[3]):
gdaltest.post_reason('did not get expected result (2)')
print(ar3)
print(type_tuple)
return 'fail'
return 'success'
###############################################################################
# Test array with slices (#3542)
def numpy_rw_12():
if gdaltest.numpy_drv is None:
return 'skip'
import numpy
ar = numpy.empty([2, 2], dtype = numpy.uint8)
ar[0][0] = 0
ar[0][1] = 1
ar[1][0] = 2
ar[1][1] = 3
drv = gdal.GetDriverByName( 'MEM' )
ds = drv.Create( '', 1, 2, 1, gdal.GDT_Byte )
slice = ar[:,1:]
ds.GetRasterBand(1).WriteArray( slice )
ar_read = numpy.zeros_like(ar)
slice_read = ar_read[:,1:]
ds.GetRasterBand(1).ReadAsArray( buf_obj = slice_read )
ds = None
if slice_read[0][0] != 1 or slice_read[1][0] != 3:
print(slice_read)
return 'fail'
return 'success'
###############################################################################
# Test expected errors
def numpy_rw_13():
if gdaltest.numpy_drv is None:
return 'skip'
import numpy
drv = gdal.GetDriverByName( 'MEM' )
ds = drv.Create( '', 2, 1, 1, gdal.GDT_Byte )
ar = numpy.empty([1, 2], dtype = numpy.uint8)
ar[0][0] = 100
ar[0][1] = 200
ds.GetRasterBand(1).WriteArray( ar )
# Try reading into unsupported array type
ar = numpy.empty([1, 2], dtype = numpy.int64)
try:
ds.GetRasterBand(1).ReadAsArray( buf_obj = ar )
gdaltest.post_reason('expected "ValueError: array does not have corresponding GDAL data type"')
return 'fail'
except:
pass
# Try call with inconsistant parameters
ar = numpy.empty([1, 2], dtype = numpy.uint8)
try:
ds.GetRasterBand(1).ReadAsArray( buf_obj = ar, buf_xsize = 2, buf_ysize = 2 )
gdaltest.post_reason('expected "Specified buf_ysize not consistant with buffer shape"')
return 'fail'
except:
pass
# Same with 3 dimensions
ar = numpy.empty([1, 1, 2], dtype = numpy.uint8)
try:
ds.GetRasterBand(1).ReadAsArray( buf_obj = ar, buf_xsize = 2, buf_ysize = 2 )
gdaltest.post_reason('expected "Specified buf_ysize not consistant with buffer shape"')
return 'fail'
except:
pass
# Try call with inconsistant parameters
ar = numpy.empty([1, 2], dtype = numpy.uint8)
try:
ds.GetRasterBand(1).ReadAsArray( buf_obj = ar, buf_xsize = 1, buf_ysize = 1 )
gdaltest.post_reason('expected "Specified buf_xsize not consistant with buffer shape"')
return 'fail'
except:
pass
# Inconsistent data type
ar = numpy.empty([1, 2], dtype = numpy.uint8)
try:
ds.GetRasterBand(1).ReadAsArray( buf_obj = ar, buf_type = gdal.GDT_Int16 )
gdaltest.post_reason('expected "Specified buf_type not consistant with array type"')
return 'fail'
except:
pass
# This one should be OK !
ar = numpy.zeros([1, 2], dtype = numpy.uint8)
ds.GetRasterBand(1).ReadAsArray( buf_obj = ar, buf_xsize = 2, buf_ysize = 1 )
if ar[0][0] != 100 or ar[0][1] != 200:
gdaltest.post_reason('did not get expected values')
print(ar)
return 'fail'
# This one too
ar = numpy.zeros([1, 1, 2], dtype = numpy.uint8)
ds.GetRasterBand(1).ReadAsArray( buf_obj = ar )
if ar[0][0][0] != 100 or ar[0][0][1] != 200:
gdaltest.post_reason('did not get expected values')
print(ar)
return 'fail'
# This one too
ar = numpy.zeros([1, 1, 2], dtype = numpy.uint8)
ds.ReadAsArray( buf_obj = ar )
if ar[0][0][0] != 100 or ar[0][0][1] != 200:
gdaltest.post_reason('did not get expected values')
print(ar)
return 'fail'
# This one too
ar = ds.ReadAsArray()
if ar[0][0] != 100 or ar[0][1] != 200:
gdaltest.post_reason('did not get expected values')
print(ar)
return 'fail'
ds = None
# With a multiband file
drv = gdal.GetDriverByName( 'MEM' )
ds = drv.Create( '', 2, 1, 3, gdal.GDT_Byte )
ar = numpy.empty([3, 1, 2], dtype = numpy.uint8)
ar[0][0][0] = 100
ar[0][0][1] = 200
ar[1][0][0] = 101
ar[1][0][1] = 201
ar[2][0][0] = 102
ar[2][0][1] = 202
for i in range(3):
ds.GetRasterBand(i+1).WriteArray( ar[i] )
ar = numpy.empty([3, 1, 2], dtype = numpy.int64)
try:
ds.ReadAsArray( buf_obj = ar )
gdaltest.post_reason('expected "ValueError: array does not have corresponding GDAL data type"')
return 'fail'
except:
pass
# Try call with inconsistant parameters
ar = numpy.empty([3, 1, 2], dtype = numpy.uint8)
try:
ds.ReadAsArray( buf_obj = ar, buf_xsize = 2, buf_ysize = 2 )
gdaltest.post_reason('expected "Specified buf_ysize not consistant with buffer shape"')
return 'fail'
except:
pass
# With 2 dimensions
ar = numpy.empty([1, 2], dtype = numpy.uint8)
try:
ds.ReadAsArray( buf_obj = ar )
gdaltest.post_reason('expected "ValueError: Array should have 3 dimensions"')
return 'fail'
except:
pass
# Try call with inconsistant parameters
ar = numpy.empty([3, 1, 2], dtype = numpy.uint8)
try:
ds.ReadAsArray( buf_obj = ar, buf_xsize = 1, buf_ysize = 1 )
gdaltest.post_reason('expected "Specified buf_xsize not consistant with buffer shape"')
return 'fail'
except:
pass
# Inconsistent data type
ar = numpy.empty([3, 1, 2], dtype = numpy.uint8)
try:
ds.ReadAsArray( buf_obj = ar, buf_type = gdal.GDT_Int16 )
gdaltest.post_reason('expected "Specified buf_type not consistant with array type"')
return 'fail'
except:
pass
# Not enough space in first dimension
ar = numpy.empty([2, 1, 2], dtype = numpy.uint8)
try:
ds.ReadAsArray( buf_obj = ar )
gdaltest.post_reason('expected "Array should have space for 3 bands"')
return 'fail'
except:
pass
# This one should be OK !
ar = numpy.zeros([3, 1, 2], dtype = numpy.uint8)
ds.ReadAsArray( buf_obj = ar, buf_xsize = 2, buf_ysize = 1, buf_type = gdal.GDT_Byte )
if ar[0][0][0] != 100 or ar[0][0][1] != 200 or ar[1][0][0] != 101 or ar[1][0][1] != 201 or ar[2][0][0] != 102 or ar[2][0][1] != 202:
gdaltest.post_reason('did not get expected values')
print(ar)
return 'fail'
# This one too
ar = numpy.zeros([3, 1, 2], dtype = numpy.uint8)
ds.ReadAsArray( buf_obj = ar )
if ar[0][0][0] != 100 or ar[0][0][1] != 200 or ar[1][0][0] != 101 or ar[1][0][1] != 201 or ar[2][0][0] != 102 or ar[2][0][1] != 202:
gdaltest.post_reason('did not get expected values')
print(ar)
return 'fail'
# This one too
ar = ds.ReadAsArray()
if ar[0][0][0] != 100 or ar[0][0][1] != 200 or ar[1][0][0] != 101 or ar[1][0][1] != 201 or ar[2][0][0] != 102 or ar[2][0][1] != 202:
gdaltest.post_reason('did not get expected values')
print(ar)
return 'fail'
ds = None
return 'success'
###############################################################################
# Test callback of ReadAsArray()
def numpy_rw_14_progress_callback(pct, message, user_data):
if abs(pct - user_data[0]) > 1e-5:
print('Expected %f, got %f' % (user_data[0], pct))
user_data[1] = False
user_data[0] = user_data[0] + 0.05
return 1 # 1 to continue, 0 to stop
def numpy_rw_14_progress_interrupt_callback(pct, message, user_data):
user_data[0] = pct
if pct >= 0.5:
return 0
return 1 # 1 to continue, 0 to stop
def numpy_rw_14_progress_callback_2(pct, message, user_data):
if pct < user_data[0]:
print('Got %f, last pct was %f' % (pct, user_data[0]))
return 0
user_data[0] = pct
return 1 # 1 to continue, 0 to stop
def numpy_rw_14():
if gdaltest.numpy_drv is None:
return 'skip'
# Progress not implemented yet
if gdal.GetConfigOption('GTIFF_DIRECT_IO') == 'YES' or \
gdal.GetConfigOption('GTIFF_VIRTUAL_MEM_IO') == 'YES':
return 'skip'
import numpy
ds = gdal.Open('data/byte.tif')
# Test RasterBand.ReadAsArray
tab = [ 0.05, True ]
data = ds.GetRasterBand(1).ReadAsArray(resample_alg = gdal.GRIORA_NearestNeighbour,
callback = numpy_rw_14_progress_callback,
callback_data = tab)
if data is None:
gdaltest.post_reason('failure')
return 'fail'
if abs(tab[0] - 1.05) > 1e-5 or not tab[1]:
gdaltest.post_reason('failure')
return 'fail'
# Test interruption
tab = [ 0 ]
data = ds.GetRasterBand(1).ReadAsArray(callback = numpy_rw_14_progress_interrupt_callback,
callback_data = tab)
if data is not None:
gdaltest.post_reason('failure')
return 'fail'
if tab[0] < 0.50:
gdaltest.post_reason('failure')
return 'fail'
# Test Dataset.ReadAsArray
tab = [ 0.05, True ]
data = ds.ReadAsArray(resample_alg = gdal.GRIORA_NearestNeighbour,
callback = numpy_rw_14_progress_callback,
callback_data = tab)
if data is None:
gdaltest.post_reason('failure')
return 'fail'
if abs(tab[0] - 1.05) > 1e-5 or not tab[1]:
gdaltest.post_reason('failure')
return 'fail'
# Same with interruption
tab = [ 0 ]
data = ds.ReadAsArray(callback = numpy_rw_14_progress_interrupt_callback,
callback_data = tab)
if data is not None or tab[0] < 0.50:
gdaltest.post_reason('failure')
return 'fail'
# Test Dataset.ReadAsArray on a multi band file
ds = None
ds = gdal.Open('data/rgbsmall.tif')
last_pct = [ 0 ]
data = ds.ReadAsArray(callback = numpy_rw_14_progress_callback_2,
callback_data = last_pct)
if data is None or abs(last_pct[0] - 1.0) > 1e-5:
gdaltest.post_reason('failure')
return 'fail'
last_pct = [ 0 ]
# Same but with a provided array
array = numpy.empty( [ds.RasterCount, ds.RasterYSize, ds.RasterXSize], numpy.uint8 )
data = ds.ReadAsArray(buf_obj = array,
callback = numpy_rw_14_progress_callback_2,
callback_data = last_pct)
if data is None or abs(last_pct[0] - 1.0) > 1e-5:
gdaltest.post_reason('failure')
return 'fail'
return 'success'
###############################################################################
# Test NumPy GetGeoTransform/SetGeoTransform
def numpy_rw_15():
if gdaltest.numpy_drv is None:
return 'skip'
import numpy
from osgeo import gdal_array
array = numpy.empty( [1,1,1], numpy.uint8 )
ds = gdal_array.OpenArray( array )
gt = ds.GetGeoTransform(can_return_null = True)
if gt is not None:
gdaltest.post_reason('failure')
return 'fail'
ds.SetGeoTransform([1,2,3,4,5,-6])
gt = ds.GetGeoTransform()
if gt != (1,2,3,4,5,-6):
gdaltest.post_reason('failure')
return 'fail'
return 'success'
def numpy_rw_cleanup():
gdaltest.numpy_drv = None
return 'success'
gdaltest_list = [
numpy_rw_1,
numpy_rw_2,
numpy_rw_3,
numpy_rw_4,
numpy_rw_5,
numpy_rw_6,
numpy_rw_7,
numpy_rw_8,
numpy_rw_9,
numpy_rw_10,
numpy_rw_11,
numpy_rw_12,
numpy_rw_13,
numpy_rw_14,
numpy_rw_15,
numpy_rw_cleanup ]
if __name__ == '__main__':
gdaltest.setup_run( 'numpy_rw' )
gdaltest.run_tests( gdaltest_list )
gdaltest.summarize()
|
[
"sys.path.append",
"numpy.zeros_like",
"osgeo.gdal_array.OpenArray",
"_gdal.GDALRegister_NUMPY",
"gdaltest.post_reason",
"osgeo.gdal.Unlink",
"numpy.empty",
"numpy.zeros",
"numpy.empty_like",
"osgeo.gdalnumeric.OpenArray",
"gdaltest.run_tests",
"gdaltest.setup_run",
"gdaltest.summarize",
"osgeo.gdalnumeric.LoadFile",
"osgeo.gdal.GetConfigOption",
"osgeo.gdal.Open",
"osgeo.gdal.GetDriverByName",
"osgeo.gdal.AllRegister"
] |
[((1577, 1604), 'sys.path.append', 'sys.path.append', (['"""../pymod"""'], {}), "('../pymod')\n", (1592, 1604), False, 'import sys\n'), ((2138, 2167), 'osgeo.gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""NUMPY"""'], {}), "('NUMPY')\n", (2158, 2167), False, 'from osgeo import gdal\n'), ((2588, 2629), 'osgeo.gdalnumeric.LoadFile', 'gdalnumeric.LoadFile', (['"""data/utmsmall.tif"""'], {}), "('data/utmsmall.tif')\n", (2608, 2629), False, 'from osgeo import gdalnumeric\n'), ((2758, 2786), 'osgeo.gdalnumeric.OpenArray', 'gdalnumeric.OpenArray', (['array'], {}), '(array)\n', (2779, 2786), False, 'from osgeo import gdalnumeric\n'), ((3300, 3330), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/cint_sar.tif"""'], {}), "('data/cint_sar.tif')\n", (3309, 3330), False, 'from osgeo import gdal\n'), ((3739, 3765), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/byte.tif"""'], {}), "('data/byte.tif')\n", (3748, 3765), False, 'from osgeo import gdal\n'), ((4270, 4325), 'osgeo.gdalnumeric.LoadFile', 'gdalnumeric.LoadFile', (['"""data/rgbsmall.tif"""', '(35)', '(21)', '(1)', '(1)'], {}), "('data/rgbsmall.tif', 35, 21, 1, 1)\n", (4290, 4325), False, 'from osgeo import gdalnumeric\n'), ((4726, 4832), 'osgeo.gdalnumeric.LoadFile', 'gdalnumeric.LoadFile', (['"""data/rgbsmall.tif"""'], {'buf_xsize': '(1)', 'buf_ysize': '(1)', 'resample_alg': 'gdal.GRIORA_Bilinear'}), "('data/rgbsmall.tif', buf_xsize=1, buf_ysize=1,\n resample_alg=gdal.GRIORA_Bilinear)\n", (4746, 4832), False, 'from osgeo import gdalnumeric\n'), ((5214, 5255), 'numpy.zeros', 'numpy.zeros', (['[3, 1, 1]'], {'dtype': 'numpy.uint8'}), '([3, 1, 1], dtype=numpy.uint8)\n', (5225, 5255), False, 'import numpy\n'), ((5267, 5297), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/rgbsmall.tif"""'], {}), "('data/rgbsmall.tif')\n", (5276, 5297), False, 'from osgeo import gdal\n'), ((5885, 5911), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/byte.tif"""'], {}), "('data/byte.tif')\n", (5894, 5911), False, 'from osgeo import gdal\n'), ((5926, 5984), 'numpy.zeros', 'numpy.zeros', (['[ds.RasterYSize, ds.RasterXSize]', 'numpy.uint8'], {}), '([ds.RasterYSize, ds.RasterXSize], numpy.uint8)\n', (5937, 5984), False, 'import numpy\n'), ((6121, 6149), 'osgeo.gdalnumeric.OpenArray', 'gdalnumeric.OpenArray', (['array'], {}), '(array)\n', (6142, 6149), False, 'from osgeo import gdalnumeric\n'), ((6586, 6612), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/byte.tif"""'], {}), "('data/byte.tif')\n", (6595, 6612), False, 'from osgeo import gdal\n'), ((6627, 6688), 'numpy.zeros', 'numpy.zeros', (['[1, ds.RasterYSize, ds.RasterXSize]', 'numpy.uint8'], {}), '([1, ds.RasterYSize, ds.RasterXSize], numpy.uint8)\n', (6638, 6688), False, 'import numpy\n'), ((6808, 6836), 'osgeo.gdalnumeric.OpenArray', 'gdalnumeric.OpenArray', (['array'], {}), '(array)\n', (6829, 6836), False, 'from osgeo import gdalnumeric\n'), ((6988, 7046), 'numpy.zeros', 'numpy.zeros', (['[ds.RasterYSize, ds.RasterXSize]', 'numpy.uint8'], {}), '([ds.RasterYSize, ds.RasterXSize], numpy.uint8)\n', (6999, 7046), False, 'import numpy\n'), ((7166, 7194), 'osgeo.gdalnumeric.OpenArray', 'gdalnumeric.OpenArray', (['array'], {}), '(array)\n', (7187, 7194), False, 'from osgeo import gdalnumeric\n'), ((7332, 7362), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/rgbsmall.tif"""'], {}), "('data/rgbsmall.tif')\n", (7341, 7362), False, 'from osgeo import gdal\n'), ((7377, 7451), 'numpy.zeros', 'numpy.zeros', (['[ds.RasterCount, ds.RasterYSize, ds.RasterXSize]', 'numpy.uint8'], {}), '([ds.RasterCount, ds.RasterYSize, ds.RasterXSize], numpy.uint8)\n', (7388, 7451), False, 'import numpy\n'), ((7571, 7599), 'osgeo.gdalnumeric.OpenArray', 'gdalnumeric.OpenArray', (['array'], {}), '(array)\n', (7592, 7599), False, 'from osgeo import gdalnumeric\n'), ((8008, 8038), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/rgbsmall.tif"""'], {}), "('data/rgbsmall.tif')\n", (8017, 8038), False, 'from osgeo import gdal\n'), ((8053, 8127), 'numpy.zeros', 'numpy.zeros', (['[ds.RasterCount, ds.RasterYSize, ds.RasterXSize]', 'numpy.uint8'], {}), '([ds.RasterCount, ds.RasterYSize, ds.RasterXSize], numpy.uint8)\n', (8064, 8127), False, 'import numpy\n'), ((8176, 8204), 'osgeo.gdalnumeric.OpenArray', 'gdalnumeric.OpenArray', (['array'], {}), '(array)\n', (8197, 8204), False, 'from osgeo import gdalnumeric\n'), ((8577, 8603), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/byte.tif"""'], {}), "('data/byte.tif')\n", (8586, 8603), False, 'from osgeo import gdal\n'), ((9316, 9353), 'numpy.empty', 'numpy.empty', (['[1, 2]'], {'dtype': 'numpy.int8'}), '([1, 2], dtype=numpy.int8)\n', (9327, 9353), False, 'import numpy\n'), ((9458, 9490), 'osgeo.gdal.Open', 'gdal.Open', (['"""/vsimem/signed8.tif"""'], {}), "('/vsimem/signed8.tif')\n", (9467, 9490), False, 'from osgeo import gdal\n'), ((9528, 9549), 'numpy.empty_like', 'numpy.empty_like', (['ar2'], {}), '(ar2)\n', (9544, 9549), False, 'import numpy\n'), ((9620, 9654), 'osgeo.gdal.Unlink', 'gdal.Unlink', (['"""/vsimem/signed8.tif"""'], {}), "('/vsimem/signed8.tif')\n", (9631, 9654), False, 'from osgeo import gdal\n'), ((12642, 12680), 'numpy.empty', 'numpy.empty', (['[2, 2]'], {'dtype': 'numpy.uint8'}), '([2, 2], dtype=numpy.uint8)\n', (12653, 12680), False, 'import numpy\n'), ((12762, 12789), 'osgeo.gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""MEM"""'], {}), "('MEM')\n", (12782, 12789), False, 'from osgeo import gdal\n'), ((12923, 12943), 'numpy.zeros_like', 'numpy.zeros_like', (['ar'], {}), '(ar)\n', (12939, 12943), False, 'import numpy\n'), ((13386, 13413), 'osgeo.gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""MEM"""'], {}), "('MEM')\n", (13406, 13413), False, 'from osgeo import gdal\n'), ((13475, 13513), 'numpy.empty', 'numpy.empty', (['[1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 2], dtype=numpy.uint8)\n', (13486, 13513), False, 'import numpy\n'), ((13651, 13689), 'numpy.empty', 'numpy.empty', (['[1, 2]'], {'dtype': 'numpy.int64'}), '([1, 2], dtype=numpy.int64)\n', (13662, 13689), False, 'import numpy\n'), ((13962, 14000), 'numpy.empty', 'numpy.empty', (['[1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 2], dtype=numpy.uint8)\n', (13973, 14000), False, 'import numpy\n'), ((14280, 14321), 'numpy.empty', 'numpy.empty', (['[1, 1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 1, 2], dtype=numpy.uint8)\n', (14291, 14321), False, 'import numpy\n'), ((14616, 14654), 'numpy.empty', 'numpy.empty', (['[1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 2], dtype=numpy.uint8)\n', (14627, 14654), False, 'import numpy\n'), ((14938, 14976), 'numpy.empty', 'numpy.empty', (['[1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 2], dtype=numpy.uint8)\n', (14949, 14976), False, 'import numpy\n'), ((15251, 15289), 'numpy.zeros', 'numpy.zeros', (['[1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 2], dtype=numpy.uint8)\n', (15262, 15289), False, 'import numpy\n'), ((15546, 15587), 'numpy.zeros', 'numpy.zeros', (['[1, 1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 1, 2], dtype=numpy.uint8)\n', (15557, 15587), False, 'import numpy\n'), ((15820, 15861), 'numpy.zeros', 'numpy.zeros', (['[1, 1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 1, 2], dtype=numpy.uint8)\n', (15831, 15861), False, 'import numpy\n'), ((16291, 16318), 'osgeo.gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""MEM"""'], {}), "('MEM')\n", (16311, 16318), False, 'from osgeo import gdal\n'), ((16380, 16421), 'numpy.empty', 'numpy.empty', (['[3, 1, 2]'], {'dtype': 'numpy.uint8'}), '([3, 1, 2], dtype=numpy.uint8)\n', (16391, 16421), False, 'import numpy\n'), ((16639, 16680), 'numpy.empty', 'numpy.empty', (['[3, 1, 2]'], {'dtype': 'numpy.int64'}), '([3, 1, 2], dtype=numpy.int64)\n', (16650, 16680), False, 'import numpy\n'), ((16936, 16977), 'numpy.empty', 'numpy.empty', (['[3, 1, 2]'], {'dtype': 'numpy.uint8'}), '([3, 1, 2], dtype=numpy.uint8)\n', (16947, 16977), False, 'import numpy\n'), ((17235, 17273), 'numpy.empty', 'numpy.empty', (['[1, 2]'], {'dtype': 'numpy.uint8'}), '([1, 2], dtype=numpy.uint8)\n', (17246, 17273), False, 'import numpy\n'), ((17511, 17552), 'numpy.empty', 'numpy.empty', (['[3, 1, 2]'], {'dtype': 'numpy.uint8'}), '([3, 1, 2], dtype=numpy.uint8)\n', (17522, 17552), False, 'import numpy\n'), ((17819, 17860), 'numpy.empty', 'numpy.empty', (['[3, 1, 2]'], {'dtype': 'numpy.uint8'}), '([3, 1, 2], dtype=numpy.uint8)\n', (17830, 17860), False, 'import numpy\n'), ((18130, 18171), 'numpy.empty', 'numpy.empty', (['[2, 1, 2]'], {'dtype': 'numpy.uint8'}), '([2, 1, 2], dtype=numpy.uint8)\n', (18141, 18171), False, 'import numpy\n'), ((18392, 18433), 'numpy.zeros', 'numpy.zeros', (['[3, 1, 2]'], {'dtype': 'numpy.uint8'}), '([3, 1, 2], dtype=numpy.uint8)\n', (18403, 18433), False, 'import numpy\n'), ((18793, 18834), 'numpy.zeros', 'numpy.zeros', (['[3, 1, 2]'], {'dtype': 'numpy.uint8'}), '([3, 1, 2], dtype=numpy.uint8)\n', (18804, 18834), False, 'import numpy\n'), ((20500, 20526), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/byte.tif"""'], {}), "('data/byte.tif')\n", (20509, 20526), False, 'from osgeo import gdal\n'), ((22174, 22204), 'osgeo.gdal.Open', 'gdal.Open', (['"""data/rgbsmall.tif"""'], {}), "('data/rgbsmall.tif')\n", (22183, 22204), False, 'from osgeo import gdal\n'), ((22536, 22610), 'numpy.empty', 'numpy.empty', (['[ds.RasterCount, ds.RasterYSize, ds.RasterXSize]', 'numpy.uint8'], {}), '([ds.RasterCount, ds.RasterYSize, ds.RasterXSize], numpy.uint8)\n', (22547, 22610), False, 'import numpy\n'), ((23184, 23219), 'numpy.empty', 'numpy.empty', (['[1, 1, 1]', 'numpy.uint8'], {}), '([1, 1, 1], numpy.uint8)\n', (23195, 23219), False, 'import numpy\n'), ((23229, 23256), 'osgeo.gdal_array.OpenArray', 'gdal_array.OpenArray', (['array'], {}), '(array)\n', (23249, 23256), False, 'from osgeo import gdal_array\n'), ((23976, 24006), 'gdaltest.setup_run', 'gdaltest.setup_run', (['"""numpy_rw"""'], {}), "('numpy_rw')\n", (23994, 24006), False, 'import gdaltest\n'), ((24014, 24047), 'gdaltest.run_tests', 'gdaltest.run_tests', (['gdaltest_list'], {}), '(gdaltest_list)\n', (24032, 24047), False, 'import gdaltest\n'), ((24055, 24075), 'gdaltest.summarize', 'gdaltest.summarize', ([], {}), '()\n', (24073, 24075), False, 'import gdaltest\n'), ((1994, 2020), '_gdal.GDALRegister_NUMPY', '_gdal.GDALRegister_NUMPY', ([], {}), '()\n', (2018, 2020), False, 'import _gdal\n'), ((2068, 2086), 'osgeo.gdal.AllRegister', 'gdal.AllRegister', ([], {}), '()\n', (2084, 2086), False, 'from osgeo import gdal\n'), ((2213, 2260), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""NUMPY driver not found!"""'], {}), "('NUMPY driver not found!')\n", (2233, 2260), False, 'import gdaltest\n'), ((2662, 2724), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""Failed to load utmsmall.tif into array"""'], {}), "('Failed to load utmsmall.tif into array')\n", (2682, 2724), False, 'import gdaltest\n'), ((2816, 2879), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""Failed to open memory array as dataset."""'], {}), "('Failed to open memory array as dataset.')\n", (2836, 2879), False, 'import gdaltest\n'), ((2975, 3043), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""Didnt get expected checksum on reopened file"""'], {}), "('Didnt get expected checksum on reopened file')\n", (2995, 3043), False, 'import gdaltest\n'), ((3432, 3486), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""complex value read improperly."""'], {}), "('complex value read improperly.')\n", (3452, 3486), False, 'import gdaltest\n'), ((3890, 3988), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""Read wrong value - perhaps downsampling algorithm has changed subtly?"""'], {}), "(\n 'Read wrong value - perhaps downsampling algorithm has changed subtly?')\n", (3910, 3988), False, 'import gdaltest\n'), ((4381, 4427), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""value read improperly."""'], {}), "('value read improperly.')\n", (4401, 4427), False, 'import gdaltest\n'), ((4512, 4558), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""value read improperly."""'], {}), "('value read improperly.')\n", (4532, 4558), False, 'import gdaltest\n'), ((4642, 4688), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""value read improperly."""'], {}), "('value read improperly.')\n", (4662, 4688), False, 'import gdaltest\n'), ((4940, 4982), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""wrong array shape."""'], {}), "('wrong array shape.')\n", (4960, 4982), False, 'import gdaltest\n'), ((5113, 5159), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""value read improperly."""'], {}), "('value read improperly.')\n", (5133, 5159), False, 'import gdaltest\n'), ((5479, 5525), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""value read improperly."""'], {}), "('value read improperly.')\n", (5499, 5525), False, 'import gdaltest\n'), ((8870, 8923), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected checksum"""'], {}), "('did not get expected checksum')\n", (8890, 8923), False, 'import gdaltest\n'), ((9710, 9765), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected result (1)"""'], {}), "('did not get expected result (1)')\n", (9730, 9765), False, 'import gdaltest\n'), ((9862, 9917), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected result (2)"""'], {}), "('did not get expected result (2)')\n", (9882, 9917), False, 'import gdaltest\n'), ((11408, 11448), 'numpy.empty', 'numpy.empty', (['[1, 1]'], {'dtype': 'type_tuple[2]'}), '([1, 1], dtype=type_tuple[2])\n', (11419, 11448), False, 'import numpy\n'), ((11559, 11596), 'osgeo.gdal.Open', 'gdal.Open', (["('/vsimem/' + type_tuple[0])"], {}), "('/vsimem/' + type_tuple[0])\n", (11568, 11596), False, 'from osgeo import gdal\n'), ((11642, 11663), 'numpy.empty_like', 'numpy.empty_like', (['ar2'], {}), '(ar2)\n', (11658, 11663), False, 'import numpy\n'), ((11746, 11785), 'osgeo.gdal.Unlink', 'gdal.Unlink', (["('/vsimem/' + type_tuple[0])"], {}), "('/vsimem/' + type_tuple[0])\n", (11757, 11785), False, 'from osgeo import gdal\n'), ((13765, 13865), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "ValueError: array does not have corresponding GDAL data type\\""""'], {}), '(\n \'expected "ValueError: array does not have corresponding GDAL data type"\')\n', (13785, 13865), False, 'import gdaltest\n'), ((14106, 14198), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "Specified buf_ysize not consistant with buffer shape\\""""'], {}), '(\n \'expected "Specified buf_ysize not consistant with buffer shape"\')\n', (14126, 14198), False, 'import gdaltest\n'), ((14427, 14519), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "Specified buf_ysize not consistant with buffer shape\\""""'], {}), '(\n \'expected "Specified buf_ysize not consistant with buffer shape"\')\n', (14447, 14519), False, 'import gdaltest\n'), ((14760, 14852), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "Specified buf_xsize not consistant with buffer shape\\""""'], {}), '(\n \'expected "Specified buf_xsize not consistant with buffer shape"\')\n', (14780, 14852), False, 'import gdaltest\n'), ((15079, 15168), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "Specified buf_type not consistant with array type\\""""'], {}), '(\n \'expected "Specified buf_type not consistant with array type"\')\n', (15099, 15168), False, 'import gdaltest\n'), ((15425, 15476), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected values"""'], {}), "('did not get expected values')\n", (15445, 15476), False, 'import gdaltest\n'), ((15699, 15750), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected values"""'], {}), "('did not get expected values')\n", (15719, 15750), False, 'import gdaltest\n'), ((15956, 16007), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected values"""'], {}), "('did not get expected values')\n", (15976, 16007), False, 'import gdaltest\n'), ((16145, 16196), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected values"""'], {}), "('did not get expected values')\n", (16165, 16196), False, 'import gdaltest\n'), ((16739, 16839), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "ValueError: array does not have corresponding GDAL data type\\""""'], {}), '(\n \'expected "ValueError: array does not have corresponding GDAL data type"\')\n', (16759, 16839), False, 'import gdaltest\n'), ((17066, 17158), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "Specified buf_ysize not consistant with buffer shape\\""""'], {}), '(\n \'expected "Specified buf_ysize not consistant with buffer shape"\')\n', (17086, 17158), False, 'import gdaltest\n'), ((17332, 17409), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "ValueError: Array should have 3 dimensions\\""""'], {}), '(\'expected "ValueError: Array should have 3 dimensions"\')\n', (17352, 17409), False, 'import gdaltest\n'), ((17641, 17733), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "Specified buf_xsize not consistant with buffer shape\\""""'], {}), '(\n \'expected "Specified buf_xsize not consistant with buffer shape"\')\n', (17661, 17733), False, 'import gdaltest\n'), ((17946, 18035), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "Specified buf_type not consistant with array type\\""""'], {}), '(\n \'expected "Specified buf_type not consistant with array type"\')\n', (17966, 18035), False, 'import gdaltest\n'), ((18230, 18300), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""expected "Array should have space for 3 bands\\""""'], {}), '(\'expected "Array should have space for 3 bands"\')\n', (18250, 18300), False, 'import gdaltest\n'), ((18672, 18723), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected values"""'], {}), "('did not get expected values')\n", (18692, 18723), False, 'import gdaltest\n'), ((19017, 19068), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected values"""'], {}), "('did not get expected values')\n", (19037, 19068), False, 'import gdaltest\n'), ((19300, 19351), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected values"""'], {}), "('did not get expected values')\n", (19320, 19351), False, 'import gdaltest\n'), ((20855, 20886), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (20875, 20886), False, 'import gdaltest\n'), ((20965, 20996), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (20985, 20996), False, 'import gdaltest\n'), ((21252, 21283), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (21272, 21283), False, 'import gdaltest\n'), ((21336, 21367), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (21356, 21367), False, 'import gdaltest\n'), ((21660, 21691), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (21680, 21691), False, 'import gdaltest\n'), ((21770, 21801), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (21790, 21801), False, 'import gdaltest\n'), ((22044, 22075), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (22064, 22075), False, 'import gdaltest\n'), ((22410, 22441), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (22430, 22441), False, 'import gdaltest\n'), ((22840, 22871), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (22860, 22871), False, 'import gdaltest\n'), ((23342, 23373), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (23362, 23373), False, 'import gdaltest\n'), ((23502, 23533), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""failure"""'], {}), "('failure')\n", (23522, 23533), False, 'import gdaltest\n'), ((8649, 8676), 'osgeo.gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""MEM"""'], {}), "('MEM')\n", (8669, 8676), False, 'from osgeo import gdal\n'), ((9205, 9234), 'osgeo.gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""GTiff"""'], {}), "('GTiff')\n", (9225, 9234), False, 'from osgeo import gdal\n'), ((11282, 11337), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected numpy type"""'], {}), "('did not get expected numpy type')\n", (11302, 11337), False, 'import gdaltest\n'), ((11958, 12013), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected result (1)"""'], {}), "('did not get expected result (1)')\n", (11978, 12013), False, 'import gdaltest\n'), ((12265, 12320), 'gdaltest.post_reason', 'gdaltest.post_reason', (['"""did not get expected result (2)"""'], {}), "('did not get expected result (2)')\n", (12285, 12320), False, 'import gdaltest\n'), ((20334, 20373), 'osgeo.gdal.GetConfigOption', 'gdal.GetConfigOption', (['"""GTIFF_DIRECT_IO"""'], {}), "('GTIFF_DIRECT_IO')\n", (20354, 20373), False, 'from osgeo import gdal\n'), ((20395, 20439), 'osgeo.gdal.GetConfigOption', 'gdal.GetConfigOption', (['"""GTIFF_VIRTUAL_MEM_IO"""'], {}), "('GTIFF_VIRTUAL_MEM_IO')\n", (20415, 20439), False, 'from osgeo import gdal\n'), ((11111, 11140), 'osgeo.gdal.GetDriverByName', 'gdal.GetDriverByName', (['"""GTiff"""'], {}), "('GTiff')\n", (11131, 11140), False, 'from osgeo import gdal\n')]
|
from sklearn.model_selection import KFold
from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef
from sklearn import svm
from feature import Feature
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import ExtraTreesClassifier
import numpy as np
def random_data(file_name):
seqs_blosum62, label, work2vec, train_seqs, seqs_dde, seqs_z, seqs_aac, seqs_dpc, seqs_ctdd, seqs_ctrial, seqs_ksctriad, seqs_gtpc, seqs_cksaagp, seqs_gaac, seqs_gdpc, seqs_ctdt, seqs_geary, seqs_cksaap, seqs_aaindex, seqs_paac = Feature(
file_name)
# , seqs_dde, seqs_z, seqs_aac, seqs_dpc, seqs_ctdd
seqs_dde = np.array(seqs_dde)
train_seqs = np.array(train_seqs)
seqs_ksctriad = np.array(seqs_ksctriad)
#work2vec = np.array(work2vec)
seqs_blosum62 = np.array(seqs_blosum62)
print(seqs_blosum62.shape)
seqs_ctrial = np.array(seqs_ctrial)
seqs_gtpc = np.array(seqs_gtpc)
seqs_cksaagp = np.array(seqs_cksaagp)
seqs_gaac = np.array(seqs_gaac)
seqs_cksaap = np.array(seqs_cksaap)
seqs_aaindex = np.array(seqs_aaindex, dtype=float)
seqs_paac = np.array(seqs_paac)
seqs_gdpc = np.array(seqs_gdpc)
# print(seqs_gtpc.shape)
seqs_ctdt = np.array(seqs_ctdt)
seqs_ctdt = seqs_ctdt.reshape(seqs_ctdt.shape[0], -1)
seqs_ctdd = np.array(seqs_ctdd)
seqs_ctdd = seqs_ctdd.reshape(seqs_ctdd.shape[0], -1)
seqs_dpc = np.array(seqs_dpc)
seqs_dpc = seqs_dpc.reshape(seqs_dpc.shape[0], -1)
seqs_aac = np.array(seqs_aac)
seqs_aac = seqs_aac.reshape(seqs_aac.shape[0], -1)
seqs_z = np.array(seqs_z)
seqs_z = seqs_z.reshape(seqs_z.shape[0], -1)
seqs_geary = np.array(seqs_geary)
seqs_geary = seqs_geary.reshape(seqs_geary.shape[0], -1)
seqs_dde = np.array(seqs_dde)
seqs_dde = seqs_dde.reshape(seqs_dde.shape[0], -1)
#work2vec = work2vec.reshape(work2vec.shape[0], -1)
seqs_ctrial = seqs_ctrial.reshape(seqs_ctrial.shape[0], -1)
seqs_ksctriad = seqs_ksctriad.reshape(seqs_ksctriad.shape[0], -1)
seqs_blosum62 = seqs_blosum62.reshape(seqs_blosum62.shape[0], -1)
seqs_gtpc = seqs_gtpc.reshape(seqs_gtpc.shape[0], -1)
seqs_cksaagp = seqs_cksaagp.reshape(seqs_cksaagp.shape[0], -1)
seqs_gaac = seqs_gaac.reshape(seqs_gaac.shape[0], -1)
seqs_cksaap = seqs_cksaap.reshape(seqs_cksaap.shape[0], -1)
seqs_aaindex = seqs_aaindex.reshape(seqs_aaindex.shape[0], -1)
seqs_dpc = seqs_dpc.reshape(seqs_dpc.shape[0], -1)
seqs_paac = seqs_paac.reshape(seqs_paac.shape[0], -1)
seqs_gdpc = seqs_gdpc.reshape(seqs_gdpc.shape[0], -1)
#data_features = np.concatenate((seqs_blosum62, seqs_ksctriad, seqs_cksaap, seqs_aaindex), 1)
#0.93
data_features1 = np.concatenate((seqs_aac,seqs_dde,seqs_paac,seqs_gaac), 1)
data_features2 = np.concatenate((seqs_aac,seqs_dde,seqs_paac,seqs_gdpc), 1)
# 0.929
data_features3 = np.concatenate((seqs_aac,seqs_dde,seqs_paac,seqs_ctdt), 1)
data_features4 = np.concatenate((seqs_dde,seqs_paac,seqs_gaac,seqs_gdpc), 1)
data_features5 = np.concatenate((seqs_dde,seqs_paac,seqs_ctdt,train_seqs), 1)
data_features6 = np.concatenate((seqs_cksaap,seqs_aac,seqs_dde,seqs_gtpc, seqs_ctdt), 1)
data_features7 = np.concatenate((seqs_cksaap,seqs_aac,seqs_dde,seqs_gdpc,seqs_aaindex), 1)
data_features8 = np.concatenate((seqs_aac,seqs_dde,seqs_paac,seqs_gaac,train_seqs), 1)
# 0.928
data_features9 = np.concatenate((seqs_aac,seqs_dde,seqs_gaac,seqs_geary,train_seqs), 1)
data_features10 = np.concatenate((seqs_dde,seqs_paac,seqs_gtpc,seqs_gdpc,seqs_ctdt), 1)
data_features11 = np.concatenate((seqs_cksaap,seqs_aac,seqs_dde,seqs_gtpc,seqs_gaac,seqs_aaindex,train_seqs), 1)
data_features12 = np.concatenate((seqs_aac,seqs_dde,seqs_dpc,seqs_paac,seqs_gaac,seqs_aaindex), 1)
data_features13 = np.concatenate((seqs_aac,seqs_dde,seqs_gaac,seqs_ctdt,seqs_aaindex,seqs_ksctriad), 1)
data_features14 = np.concatenate((seqs_aac,seqs_dde,seqs_dpc,seqs_paac,seqs_gdpc,seqs_aaindex,seqs_ctrial,train_seqs), 1)
data_features15 = np.concatenate((seqs_aac,seqs_dde,seqs_gtpc,seqs_ksctriad,seqs_cksaap), 1)
#seqs_aac', 'seqs_cksaagp', 'seqs_gaac', 'seqs_gdpc
# seqs_blosum62, label, work2vec, train_seqs, seqs_dde, seqs_z, seqs_aac, seqs_dpc, seqs_ctdd = Feature(file_name)
# train_seqs = np.array(train_seqs)
# seqs_dde = np.array(seqs_dde)
# seqs_dde = seqs_dde.reshape(seqs_dde.shape[0], -1)
# data_features = np.concatenate((train_seqs, seqs_dde), 1)
# if num > 1:
# data_features = np.array(eval(data_feature[0]))
# if data_features.ndim > 2:
# data_features = data_features.reshape(data_features.shape[0], -1)
# for i in range(num - 1):
# temp = eval(data_feature[i + 1])
# temp = np.array(temp)
# if temp.ndim > 2:
# temp = temp.reshape(temp.shape[0], -1)
# data_features = np.concatenate((data_features, temp), 1)
# else:
# data_feature = eval(data_feature)
# data_features = np.array(data_feature)
# if data_features.ndim > 2:
# data_features = data_features.reshape(data_features.shape[0], -1)
label = np.array(label)
label = label.reshape(label.shape[0], )
# indx = np.arange(data_features.shape[0])
#
# np.random.shuffle(indx)
#
# label = ((label[indx]))
#
# data_features = (data_features[indx])
return data_features1, data_features2, data_features3, data_features4, data_features5, data_features6, data_features7, data_features8, data_features9, data_features10, data_features11, data_features12, data_features13, data_features14, data_features15, label
# data_features1, data_features2, data_features3, data_features4, data_features5, data_features6, data_features7, data_features8, data_features9, data_features10, data_features11, data_features12, data_features13, data_features14, data_features15, label = random_data(
# "D:\E下载\\ACP20AltTrain (1).fasta")
#
# te_data_features1, te_data_features2, te_data_features3, te_data_features4, te_data_features5, te_data_features6, te_data_features7, te_data_features8, te_data_features9, te_data_features10, te_data_features11, te_data_features12, te_data_features13, te_data_features14, te_data_features15, te_label = random_data(
# "D:\E下载\\ACP20AltTest (1).fasta")
#ml_model = XGBClassifier(use_label_encoder=False)
ml_model1 = ExtraTreesClassifier(random_state= 0)
ml_model2 = ExtraTreesClassifier(random_state= 0)
ml_model3 = ExtraTreesClassifier(random_state= 0)
ml_model4 = ExtraTreesClassifier(random_state= 0)
ml_model5 = ExtraTreesClassifier(random_state= 0)
ml_model6 = ExtraTreesClassifier(random_state= 0)
ml_model7 = ExtraTreesClassifier(random_state= 0)
ml_model8 = ExtraTreesClassifier(random_state= 0)
ml_model9 = ExtraTreesClassifier(random_state= 0)
ml_model10 = ExtraTreesClassifier(random_state= 0)
estimatorf = VotingClassifier(estimators=[
('log_clf', LogisticRegression()),
('svm_clf', svm.SVC(probability=True)),
], voting='soft')
data_features1x, data_features2x, data_features3x, data_features4x, data_features5x, data_features6x, data_features7x, data_features8x, data_features9x, data_features10x, data_features11x, data_features12x, data_features13x, data_features14x, data_features15x, labelx = random_data("D:\E下载\\CPP.txt")
skf = KFold(n_splits= 10, shuffle= True,random_state= 999)
k_re_list1 = []
MCC1 = []
SP1 = []
SN1 = []
k_re_list2 = []
MCC2 = []
SP2 = []
SN2 = []
k_re_list3 = []
MCC3 = []
SP3 = []
SN3 = []
k_re_list4 = []
MCC4 = []
SP4 = []
SN4 = []
k_re_list5 = []
MCC5 = []
SP5 = []
SN5 = []
k_re_list6 = []
MCC6 = []
SP6 = []
SN6 = []
k_re_list7 = []
MCC7 = []
SP7 = []
SN7 = []
k_re_list8 = []
MCC8 = []
SP8 = []
SN8 = []
k_re_list9 = []
MCC9 = []
SP9 = []
SN9 = []
k_re_list10 = []
MCC10 = []
SP10 = []
SN10 = []
k_re_list1x = []
MCC1x = []
SP1x = []
SN1x = []
for K, (train_idx, val_idx) in enumerate(skf.split(data_features1x, labelx)):
print("{}K-fold\n".format(K))
# data_features1 = data_features1x[train_idx]
# te_data_features1 = data_features1x[val_idx]
# data_features2 = data_features2x[train_idx]
# te_data_features2 = data_features2x[val_idx]
# data_features3 = data_features3x[train_idx]
# te_data_features3 = data_features3x[val_idx]
# data_features4 = data_features4x[train_idx]
# te_data_features4 = data_features4x[val_idx]
data_features5 = data_features5x[train_idx]
te_data_features5 = data_features5x[val_idx]
data_features6 = data_features6x[train_idx]
te_data_features6 = data_features6x[val_idx]
data_features7 = data_features7x[train_idx]
te_data_features7 = data_features7x[val_idx]
# data_features8 = data_features8x[train_idx]
# te_data_features8 = data_features8x[val_idx]
# data_features9 = data_features9x[train_idx]
# te_data_features9 = data_features9x[val_idx]
# data_features10 = data_features10x[train_idx]
# te_data_features10 = data_features10x[val_idx]
#
label = labelx[train_idx]
te_label = labelx[val_idx]
# print("1")
# ml_model1.fit(data_features1, label)
# print("1")
# ml_model2.fit(data_features2, label)
# print("2")
# ml_model3.fit(data_features3, label)
# print("3")
# ml_model4.fit(data_features4, label)
# print("4")
ml_model5.fit(data_features5, label)
print("5")
ml_model6.fit(data_features6, label)
print("6")
ml_model7.fit(data_features7, label)
print("7")
#ml_model8.fit(data_features8, label)
# print("8")
# ml_model9.fit(data_features9, label)
# print("9")
# ml_model10.fit(data_features10, label)
# print("10")
#
# y_pred1 = ml_model1.predict(te_data_features1)
# k_re_list1.append(accuracy_score(te_label, y_pred1))
# MCC1.append(matthews_corrcoef(te_label, y_pred1))
# SP1.append(float((str(classification_report((y_pred1), te_label, digits=4)).split())[6]))
# SN1.append(float((str(classification_report((y_pred1), te_label, digits=4)).split())[11]))
# print(classification_report((y_pred1), te_label, digits=4))
# print("=========1===========")
# y_pred2 = ml_model2.predict(te_data_features2)
# MCC2.append(matthews_corrcoef(te_label, y_pred2))
# SP2.append(float((str(classification_report((y_pred2), te_label, digits=4)).split())[6]))
# SN2.append(float((str(classification_report((y_pred2), te_label, digits=4)).split())[11]))
# k_re_list2.append(accuracy_score(te_label, y_pred2))
# print(classification_report((y_pred2), te_label, digits=4))
# print("=========2===========")
# y_pred3 = ml_model3.predict(te_data_features3)
# k_re_list3.append(accuracy_score(te_label, y_pred3))
# MCC3.append(matthews_corrcoef(te_label, y_pred3))
# SP3.append(float((str(classification_report((y_pred3), te_label, digits=4)).split())[6]))
# SN3.append(float((str(classification_report((y_pred3), te_label, digits=4)).split())[11]))
# print(classification_report((y_pred3), te_label, digits=4))
# print("=========3===========")
# y_pred4 = ml_model4.predict(te_data_features4)
# k_re_list4.append(accuracy_score(te_label, y_pred4))
# MCC4.append(matthews_corrcoef(te_label, y_pred4))
# SP4.append(float((str(classification_report((y_pred4), te_label, digits=4)).split())[6]))
# SN4.append(float((str(classification_report((y_pred4), te_label, digits=4)).split())[11]))
# print(classification_report((y_pred4), te_label, digits=4))
# print("=========4===========")
y_pred5 = ml_model5.predict(te_data_features5)
k_re_list5.append(accuracy_score(te_label, y_pred5))
MCC5.append(matthews_corrcoef(te_label, y_pred5))
SP5.append(float((str(classification_report((y_pred5), te_label, digits=4)).split())[6]))
SN5.append(float((str(classification_report((y_pred5), te_label, digits=4)).split())[11]))
print(classification_report((y_pred5), te_label, digits=4))
print("=========5===========")
y_pred6 = ml_model6.predict(te_data_features6)
k_re_list6.append(accuracy_score(te_label, y_pred6))
MCC6.append(matthews_corrcoef(te_label, y_pred6))
SP6.append(float((str(classification_report((y_pred6), te_label, digits=4)).split())[6]))
SN6.append(float((str(classification_report((y_pred6), te_label, digits=4)).split())[11]))
print(classification_report((y_pred6), te_label, digits=4))
print("=========6===========")
y_pred7 = ml_model7.predict(te_data_features7)
k_re_list7.append(accuracy_score(te_label, y_pred7))
MCC7.append(matthews_corrcoef(te_label, y_pred7))
SP7.append(float((str(classification_report((y_pred7), te_label, digits=4)).split())[6]))
SN7.append(float((str(classification_report((y_pred7), te_label, digits=4)).split())[11]))
print(classification_report((y_pred7), te_label, digits=4))
print("=========7===========")
# y_pred8 = ml_model8.predict(te_data_features8)
# k_re_list8.append(accuracy_score(te_label, y_pred8))
# MCC8.append(matthews_corrcoef(te_label, y_pred8))
# SP8.append(float((str(classification_report((y_pred8), te_label, digits=4)).split())[6]))
# SN8.append(float((str(classification_report((y_pred8), te_label, digits=4)).split())[11]))
# print(classification_report((y_pred8), te_label, digits=4))
# print("=========8===========")
# y_pred9 = ml_model9.predict(te_data_features9)
# k_re_list9.append(accuracy_score(te_label, y_pred9))
# MCC9.append(matthews_corrcoef(te_label, y_pred9))
# SP9.append(float((str(classification_report((y_pred9), te_label, digits=4)).split())[6]))
# SN9.append(float((str(classification_report((y_pred9), te_label, digits=4)).split())[11]))
# print(classification_report((y_pred9), te_label, digits=4))
# print("=========9===========")
# y_pred10 = ml_model10.predict(te_data_features10)
# k_re_list10.append(accuracy_score(te_label, y_pred10))
# MCC10.append(matthews_corrcoef(te_label, y_pred10))
# SP10.append(float((str(classification_report((y_pred10), te_label, digits=4)).split())[6]))
# SN10.append(float((str(classification_report((y_pred10), te_label, digits=4)).split())[11]))
# print(classification_report((y_pred10), te_label, digits=4))
# print("=========10===========")
# t_pred1 = ml_model1.predict(data_features1)
# t_pred2 = ml_model2.predict(data_features2)
# t_pred3 = ml_model3.predict(data_features3)
# t_pred4 = ml_model4.predict(data_features4)
t_pred5 = ml_model5.predict(data_features5)
t_pred6 = ml_model6.predict(data_features6)
t_pred7 = ml_model7.predict(data_features7)
# t_pred8 = ml_model8.predict(data_features8)
# t_pred9 = ml_model9.predict(data_features9)
# t_pred10 = ml_model10.predict(data_features10)
# y_pred1 = y_pred1.reshape(y_pred1.shape[0], 1)
# y_pred2 = y_pred2.reshape(y_pred2.shape[0], 1)
# y_pred3 = y_pred3.reshape(y_pred3.shape[0], 1)
# y_pred4 = y_pred4.reshape(y_pred4.shape[0], 1)
y_pred5 = y_pred5.reshape(y_pred5.shape[0], 1)
y_pred6 = y_pred6.reshape(y_pred6.shape[0], 1)
y_pred7 = y_pred7.reshape(y_pred7.shape[0], 1)
# y_pred8 = y_pred8.reshape(y_pred8.shape[0], 1)
# y_pred9 = y_pred9.reshape(y_pred9.shape[0], 1)
# y_pred10 = y_pred10.reshape(y_pred10.shape[0], 1)
# t_pred1 = t_pred1.reshape(t_pred1.shape[0], 1)
# t_pred2 = t_pred2.reshape(t_pred2.shape[0], 1)
# t_pred3 = t_pred3.reshape(t_pred3.shape[0], 1)
# t_pred4 = t_pred4.reshape(t_pred4.shape[0], 1)
t_pred5 = t_pred5.reshape(t_pred5.shape[0], 1)
t_pred6 = t_pred6.reshape(t_pred6.shape[0], 1)
t_pred7 = t_pred7.reshape(t_pred7.shape[0], 1)
# t_pred8 = t_pred8.reshape(t_pred8.shape[0], 1)
# t_pred9 = t_pred9.reshape(t_pred9.shape[0], 1)
# t_pred10 = t_pred10.reshape(t_pred10.shape[0], 1)
temf_y_predx = np.concatenate(
(y_pred6,y_pred5, y_pred7), 1) # ,y_pred6,y_pred7,y_pred8,y_pred9,y_pred10 y_pred1,,y_pred4,y_pred8,y_pred9,y_pred10
temf_t_predx = np.concatenate(
(t_pred6, t_pred5, t_pred7), 1) # , t_pred6, t_pred7, t_pred8, t_pred9, t_pred10t_pred1,, t_pred4, t_pred8, t_pred9, t_pred10
estimatorf.fit(temf_t_predx, label)
temf_y_predxf = estimatorf.predict(temf_y_predx)
temf_t_predxf = estimatorf.predict(temf_t_predx)
k_re_list1x.append(accuracy_score(te_label, temf_y_predxf))
MCC1x.append(matthews_corrcoef(te_label, temf_y_predxf))
SP1x.append(float((str(classification_report((temf_y_predxf), te_label, digits=4)).split())[6]))
SN1x.append(float((str(classification_report((temf_y_predxf), te_label, digits=4)).split())[11]))
print(classification_report(temf_y_predxf, te_label, digits=4))
print("=========f===========")
# print(1)
# print("SP: ", sum(SP1) / 10)
# print("SN: ", sum(SN1) / 10)
# print("MCC: ", sum(MCC1) / 10)
# print("ACC: ",sum(k_re_list1) / 10)
# print(2)
# print("SP: ", sum(SP2) / 10)
# print("SN: ", sum(SN2) / 10)
# print("MCC: ", sum(MCC2) / 10)
# print("ACC: ",sum(k_re_list2) / 10)
# print(3)
# print("SP: ", sum(SP3) / 10)
# print("SN: ", sum(SN3) / 10)
# print("MCC: ", sum(MCC3) / 10)
# print("ACC: ",sum(k_re_list3) / 10)
# print(4)
# print("SP: ", sum(SP4) / 10)
# print("SN: ", sum(SN4) / 10)
# print("MCC: ", sum(MCC4) / 10)
# print("ACC: ",sum(k_re_list4) / 10)
print(5)
print("SP: ", sum(SP5) / 10)
print("SN: ", sum(SN5) / 10)
print("MCC: ", sum(MCC5) / 10)
print("ACC: ",sum(k_re_list5) / 10)
print(6)
print("SP: ", sum(SP6) / 10)
print("SN: ", sum(SN6) / 10)
print("MCC: ", sum(MCC6) / 10)
print("ACC: ",sum(k_re_list6) / 10)
print(7)
print("SP: ", sum(SP7) / 10)
print("SN: ", sum(SN7) / 10)
print("MCC: ", sum(MCC7) / 10)
print("ACC: ",sum(k_re_list7) / 10)
# print(8)
# print("SP: ", sum(SP8) / 10)
# print("SN: ", sum(SN8) / 10)
# print("MCC: ", sum(MCC8) / 10)
# print("ACC: ",sum(k_re_list8) / 10)
# print(9)
# print("SP: ", sum(SP9) / 10)
# print("SN: ", sum(SN9) / 10)
# print("MCC: ", sum(MCC9) / 10)
# print("ACC: ",sum(k_re_list9) / 10)
# print(10)
# print("SP: ", sum(SP10) / 10)
# print("SN: ", sum(SN10) / 10)
# print("MCC: ", sum(MCC10) / 10)
# print("ACC: ",sum(k_re_list10) / 10)
print("f")
print("SP: ", sum(SP1x) / 10)
print("SN: ", sum(SN1x) / 10)
print("MCC: ", sum(MCC1x) / 10)
print("ACC: ",sum(k_re_list1x) / 10)
|
[
"sklearn.metrics.accuracy_score",
"sklearn.model_selection.KFold",
"sklearn.metrics.classification_report",
"sklearn.ensemble.ExtraTreesClassifier",
"sklearn.linear_model.LogisticRegression",
"sklearn.metrics.matthews_corrcoef",
"numpy.array",
"sklearn.svm.SVC",
"feature.Feature",
"numpy.concatenate"
] |
[((6598, 6634), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (6618, 6634), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((6649, 6685), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (6669, 6685), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((6700, 6736), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (6720, 6736), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((6751, 6787), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (6771, 6787), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((6802, 6838), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (6822, 6838), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((6853, 6889), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (6873, 6889), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((6904, 6940), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (6924, 6940), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((6955, 6991), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (6975, 6991), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((7006, 7042), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (7026, 7042), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((7058, 7094), 'sklearn.ensemble.ExtraTreesClassifier', 'ExtraTreesClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (7078, 7094), False, 'from sklearn.ensemble import ExtraTreesClassifier\n'), ((7567, 7617), 'sklearn.model_selection.KFold', 'KFold', ([], {'n_splits': '(10)', 'shuffle': '(True)', 'random_state': '(999)'}), '(n_splits=10, shuffle=True, random_state=999)\n', (7572, 7617), False, 'from sklearn.model_selection import KFold\n'), ((589, 607), 'feature.Feature', 'Feature', (['file_name'], {}), '(file_name)\n', (596, 607), False, 'from feature import Feature\n'), ((693, 711), 'numpy.array', 'np.array', (['seqs_dde'], {}), '(seqs_dde)\n', (701, 711), True, 'import numpy as np\n'), ((730, 750), 'numpy.array', 'np.array', (['train_seqs'], {}), '(train_seqs)\n', (738, 750), True, 'import numpy as np\n'), ((772, 795), 'numpy.array', 'np.array', (['seqs_ksctriad'], {}), '(seqs_ksctriad)\n', (780, 795), True, 'import numpy as np\n'), ((853, 876), 'numpy.array', 'np.array', (['seqs_blosum62'], {}), '(seqs_blosum62)\n', (861, 876), True, 'import numpy as np\n'), ((928, 949), 'numpy.array', 'np.array', (['seqs_ctrial'], {}), '(seqs_ctrial)\n', (936, 949), True, 'import numpy as np\n'), ((967, 986), 'numpy.array', 'np.array', (['seqs_gtpc'], {}), '(seqs_gtpc)\n', (975, 986), True, 'import numpy as np\n'), ((1007, 1029), 'numpy.array', 'np.array', (['seqs_cksaagp'], {}), '(seqs_cksaagp)\n', (1015, 1029), True, 'import numpy as np\n'), ((1047, 1066), 'numpy.array', 'np.array', (['seqs_gaac'], {}), '(seqs_gaac)\n', (1055, 1066), True, 'import numpy as np\n'), ((1086, 1107), 'numpy.array', 'np.array', (['seqs_cksaap'], {}), '(seqs_cksaap)\n', (1094, 1107), True, 'import numpy as np\n'), ((1128, 1163), 'numpy.array', 'np.array', (['seqs_aaindex'], {'dtype': 'float'}), '(seqs_aaindex, dtype=float)\n', (1136, 1163), True, 'import numpy as np\n'), ((1183, 1202), 'numpy.array', 'np.array', (['seqs_paac'], {}), '(seqs_paac)\n', (1191, 1202), True, 'import numpy as np\n'), ((1220, 1239), 'numpy.array', 'np.array', (['seqs_gdpc'], {}), '(seqs_gdpc)\n', (1228, 1239), True, 'import numpy as np\n'), ((1287, 1306), 'numpy.array', 'np.array', (['seqs_ctdt'], {}), '(seqs_ctdt)\n', (1295, 1306), True, 'import numpy as np\n'), ((1383, 1402), 'numpy.array', 'np.array', (['seqs_ctdd'], {}), '(seqs_ctdd)\n', (1391, 1402), True, 'import numpy as np\n'), ((1478, 1496), 'numpy.array', 'np.array', (['seqs_dpc'], {}), '(seqs_dpc)\n', (1486, 1496), True, 'import numpy as np\n'), ((1569, 1587), 'numpy.array', 'np.array', (['seqs_aac'], {}), '(seqs_aac)\n', (1577, 1587), True, 'import numpy as np\n'), ((1658, 1674), 'numpy.array', 'np.array', (['seqs_z'], {}), '(seqs_z)\n', (1666, 1674), True, 'import numpy as np\n'), ((1745, 1765), 'numpy.array', 'np.array', (['seqs_geary'], {}), '(seqs_geary)\n', (1753, 1765), True, 'import numpy as np\n'), ((1844, 1862), 'numpy.array', 'np.array', (['seqs_dde'], {}), '(seqs_dde)\n', (1852, 1862), True, 'import numpy as np\n'), ((2810, 2871), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_paac, seqs_gaac)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_paac, seqs_gaac), 1)\n', (2824, 2871), True, 'import numpy as np\n'), ((2891, 2952), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_paac, seqs_gdpc)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_paac, seqs_gdpc), 1)\n', (2905, 2952), True, 'import numpy as np\n'), ((2985, 3046), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_paac, seqs_ctdt)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_paac, seqs_ctdt), 1)\n', (2999, 3046), True, 'import numpy as np\n'), ((3066, 3128), 'numpy.concatenate', 'np.concatenate', (['(seqs_dde, seqs_paac, seqs_gaac, seqs_gdpc)', '(1)'], {}), '((seqs_dde, seqs_paac, seqs_gaac, seqs_gdpc), 1)\n', (3080, 3128), True, 'import numpy as np\n'), ((3148, 3211), 'numpy.concatenate', 'np.concatenate', (['(seqs_dde, seqs_paac, seqs_ctdt, train_seqs)', '(1)'], {}), '((seqs_dde, seqs_paac, seqs_ctdt, train_seqs), 1)\n', (3162, 3211), True, 'import numpy as np\n'), ((3231, 3305), 'numpy.concatenate', 'np.concatenate', (['(seqs_cksaap, seqs_aac, seqs_dde, seqs_gtpc, seqs_ctdt)', '(1)'], {}), '((seqs_cksaap, seqs_aac, seqs_dde, seqs_gtpc, seqs_ctdt), 1)\n', (3245, 3305), True, 'import numpy as np\n'), ((3325, 3402), 'numpy.concatenate', 'np.concatenate', (['(seqs_cksaap, seqs_aac, seqs_dde, seqs_gdpc, seqs_aaindex)', '(1)'], {}), '((seqs_cksaap, seqs_aac, seqs_dde, seqs_gdpc, seqs_aaindex), 1)\n', (3339, 3402), True, 'import numpy as np\n'), ((3421, 3494), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_paac, seqs_gaac, train_seqs)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_paac, seqs_gaac, train_seqs), 1)\n', (3435, 3494), True, 'import numpy as np\n'), ((3526, 3600), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_gaac, seqs_geary, train_seqs)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_gaac, seqs_geary, train_seqs), 1)\n', (3540, 3600), True, 'import numpy as np\n'), ((3620, 3693), 'numpy.concatenate', 'np.concatenate', (['(seqs_dde, seqs_paac, seqs_gtpc, seqs_gdpc, seqs_ctdt)', '(1)'], {}), '((seqs_dde, seqs_paac, seqs_gtpc, seqs_gdpc, seqs_ctdt), 1)\n', (3634, 3693), True, 'import numpy as np\n'), ((3713, 3817), 'numpy.concatenate', 'np.concatenate', (['(seqs_cksaap, seqs_aac, seqs_dde, seqs_gtpc, seqs_gaac, seqs_aaindex,\n train_seqs)', '(1)'], {}), '((seqs_cksaap, seqs_aac, seqs_dde, seqs_gtpc, seqs_gaac,\n seqs_aaindex, train_seqs), 1)\n', (3727, 3817), True, 'import numpy as np\n'), ((3831, 3920), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_dpc, seqs_paac, seqs_gaac, seqs_aaindex)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_dpc, seqs_paac, seqs_gaac,\n seqs_aaindex), 1)\n', (3845, 3920), True, 'import numpy as np\n'), ((3935, 4029), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_gaac, seqs_ctdt, seqs_aaindex, seqs_ksctriad)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_gaac, seqs_ctdt, seqs_aaindex,\n seqs_ksctriad), 1)\n', (3949, 4029), True, 'import numpy as np\n'), ((4044, 4158), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_dpc, seqs_paac, seqs_gdpc, seqs_aaindex,\n seqs_ctrial, train_seqs)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_dpc, seqs_paac, seqs_gdpc,\n seqs_aaindex, seqs_ctrial, train_seqs), 1)\n', (4058, 4158), True, 'import numpy as np\n'), ((4171, 4249), 'numpy.concatenate', 'np.concatenate', (['(seqs_aac, seqs_dde, seqs_gtpc, seqs_ksctriad, seqs_cksaap)', '(1)'], {}), '((seqs_aac, seqs_dde, seqs_gtpc, seqs_ksctriad, seqs_cksaap), 1)\n', (4185, 4249), True, 'import numpy as np\n'), ((5345, 5360), 'numpy.array', 'np.array', (['label'], {}), '(label)\n', (5353, 5360), True, 'import numpy as np\n'), ((16321, 16367), 'numpy.concatenate', 'np.concatenate', (['(y_pred6, y_pred5, y_pred7)', '(1)'], {}), '((y_pred6, y_pred5, y_pred7), 1)\n', (16335, 16367), True, 'import numpy as np\n'), ((16483, 16529), 'numpy.concatenate', 'np.concatenate', (['(t_pred6, t_pred5, t_pred7)', '(1)'], {}), '((t_pred6, t_pred5, t_pred7), 1)\n', (16497, 16529), True, 'import numpy as np\n'), ((11976, 12009), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['te_label', 'y_pred5'], {}), '(te_label, y_pred5)\n', (11990, 12009), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12028, 12064), 'sklearn.metrics.matthews_corrcoef', 'matthews_corrcoef', (['te_label', 'y_pred5'], {}), '(te_label, y_pred5)\n', (12045, 12064), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12268, 12318), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred5', 'te_label'], {'digits': '(4)'}), '(y_pred5, te_label, digits=4)\n', (12289, 12318), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12433, 12466), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['te_label', 'y_pred6'], {}), '(te_label, y_pred6)\n', (12447, 12466), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12485, 12521), 'sklearn.metrics.matthews_corrcoef', 'matthews_corrcoef', (['te_label', 'y_pred6'], {}), '(te_label, y_pred6)\n', (12502, 12521), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12725, 12775), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred6', 'te_label'], {'digits': '(4)'}), '(y_pred6, te_label, digits=4)\n', (12746, 12775), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12890, 12923), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['te_label', 'y_pred7'], {}), '(te_label, y_pred7)\n', (12904, 12923), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12942, 12978), 'sklearn.metrics.matthews_corrcoef', 'matthews_corrcoef', (['te_label', 'y_pred7'], {}), '(te_label, y_pred7)\n', (12959, 12978), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((13184, 13234), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred7', 'te_label'], {'digits': '(4)'}), '(y_pred7, te_label, digits=4)\n', (13205, 13234), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((16809, 16848), 'sklearn.metrics.accuracy_score', 'accuracy_score', (['te_label', 'temf_y_predxf'], {}), '(te_label, temf_y_predxf)\n', (16823, 16848), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((16868, 16910), 'sklearn.metrics.matthews_corrcoef', 'matthews_corrcoef', (['te_label', 'temf_y_predxf'], {}), '(te_label, temf_y_predxf)\n', (16885, 16910), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((17128, 17184), 'sklearn.metrics.classification_report', 'classification_report', (['temf_y_predxf', 'te_label'], {'digits': '(4)'}), '(temf_y_predxf, te_label, digits=4)\n', (17149, 17184), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((7163, 7183), 'sklearn.linear_model.LogisticRegression', 'LogisticRegression', ([], {}), '()\n', (7181, 7183), False, 'from sklearn.linear_model import LogisticRegression\n'), ((7203, 7228), 'sklearn.svm.SVC', 'svm.SVC', ([], {'probability': '(True)'}), '(probability=True)\n', (7210, 7228), False, 'from sklearn import svm\n'), ((12093, 12143), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred5', 'te_label'], {'digits': '(4)'}), '(y_pred5, te_label, digits=4)\n', (12114, 12143), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12188, 12238), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred5', 'te_label'], {'digits': '(4)'}), '(y_pred5, te_label, digits=4)\n', (12209, 12238), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12550, 12600), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred6', 'te_label'], {'digits': '(4)'}), '(y_pred6, te_label, digits=4)\n', (12571, 12600), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((12645, 12695), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred6', 'te_label'], {'digits': '(4)'}), '(y_pred6, te_label, digits=4)\n', (12666, 12695), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((13007, 13057), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred7', 'te_label'], {'digits': '(4)'}), '(y_pred7, te_label, digits=4)\n', (13028, 13057), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((13102, 13152), 'sklearn.metrics.classification_report', 'classification_report', (['y_pred7', 'te_label'], {'digits': '(4)'}), '(y_pred7, te_label, digits=4)\n', (13123, 13152), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((16940, 16996), 'sklearn.metrics.classification_report', 'classification_report', (['temf_y_predxf', 'te_label'], {'digits': '(4)'}), '(temf_y_predxf, te_label, digits=4)\n', (16961, 16996), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n'), ((17042, 17098), 'sklearn.metrics.classification_report', 'classification_report', (['temf_y_predxf', 'te_label'], {'digits': '(4)'}), '(temf_y_predxf, te_label, digits=4)\n', (17063, 17098), False, 'from sklearn.metrics import classification_report, accuracy_score, matthews_corrcoef\n')]
|
"""
Tensorflow implementation of DeepFM [1]
Reference:
[1] DeepFM: A Factorization-Machine based Neural Network for CTR Prediction,
<NAME>, <NAME>, <NAME>, <NAME>, <NAME>.
"""
import numpy as np
import tensorflow as tf
import os
import example.config as config
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.metrics import roc_auc_score
from time import time
from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm
# from yellowfin import YFOptimizer
class DeepFM(BaseEstimator, TransformerMixin):
def __init__(self, feature_size, field_size,
embedding_size=8, dropout_fm=[1.0, 1.0],
deep_layers=[32, 32], dropout_deep=[0.5, 0.5, 0.5],
deep_layers_activation=tf.nn.relu,
epoch=10, batch_size=256,
learning_rate=0.001, optimizer_type="adam",
batch_norm=0, batch_norm_decay=0.995,
verbose=False, random_seed=2016,
use_fm=True, use_deep=True,
loss_type="logloss", eval_metric=roc_auc_score,
l2_reg=0.0, greater_is_better=True, is_finetune=False):
assert (use_fm or use_deep)
assert loss_type in ["logloss", "mse"], \
"loss_type can be either 'logloss' for classification task or 'mse' for regression task"
self.feature_size = feature_size # denote as M, size of the feature dictionary
self.field_size = field_size # denote as F, size of the feature fields
self.embedding_size = embedding_size # denote as K, size of the feature embedding
self.dropout_fm = dropout_fm
self.deep_layers = deep_layers
self.dropout_deep = dropout_deep
self.deep_layers_activation = deep_layers_activation
self.use_fm = use_fm
self.use_deep = use_deep
self.l2_reg = l2_reg
self.epoch = epoch
self.batch_size = batch_size
self.learning_rate = learning_rate
self.optimizer_type = optimizer_type
self.batch_norm = batch_norm
self.batch_norm_decay = batch_norm_decay
self.verbose = verbose
self.random_seed = random_seed
self.loss_type = loss_type
self.eval_metric = eval_metric
self.greater_is_better = greater_is_better
self.train_result, self.valid_result = [], []
self.is_finetune = is_finetune
self._init_graph()
def _init_graph(self):
self.graph = tf.Graph()
with self.graph.as_default():
tf.set_random_seed(self.random_seed)
self.sess = self._init_session()
self.feat_index = tf.placeholder(tf.int32, shape=[None, None], name="feat_index") # None * F
self.feat_value = tf.placeholder(tf.float32, shape=[None, None], name="feat_value") # None * F
self.label = tf.placeholder(tf.float32, shape=[None, 1], name="label") # None * 1
self.dropout_keep_fm = tf.placeholder(tf.float32, shape=[None], name="dropout_keep_fm")
self.dropout_keep_deep = tf.placeholder(tf.float32, shape=[None], name="dropout_keep_deep")
self.train_phase = tf.placeholder(tf.bool, name="train_phase")
self.weights = self._initialize_weights()
# model
self.embeddings = tf.nn.embedding_lookup(self.weights["feature_embeddings"], self.feat_index) # None * F * K
feat_value = tf.reshape(self.feat_value, shape=[-1, self.field_size, 1])
self.embeddings = tf.multiply(self.embeddings, feat_value)
# ---------- first order term ----------
self.y_first_order = tf.nn.embedding_lookup(self.weights["feature_bias"], self.feat_index) # None * F * 1
self.y_first_order = tf.reduce_sum(tf.multiply(self.y_first_order, feat_value), 2) # None * F
self.y_first_order = tf.nn.dropout(self.y_first_order, self.dropout_keep_fm[0]) # None * F
# ---------- second order term ---------------
# sum_square part
self.summed_features_emb = tf.reduce_sum(self.embeddings, 1) # None * K
self.summed_features_emb_square = tf.square(self.summed_features_emb) # None * K
# square_sum part
self.squared_features_emb = tf.square(self.embeddings)
self.squared_sum_features_emb = tf.reduce_sum(self.squared_features_emb, 1) # None * K
# second order
self.y_second_order = 0.5 * tf.subtract(self.summed_features_emb_square, self.squared_sum_features_emb) # None * K
self.y_second_order = tf.nn.dropout(self.y_second_order, self.dropout_keep_fm[1]) # None * K
# ---------- Deep component ----------
self.y_deep = tf.reshape(self.embeddings, shape=[-1, self.field_size * self.embedding_size]) # None * (F*K)
self.y_deep = tf.nn.dropout(self.y_deep, self.dropout_keep_deep[0])
for i in range(0, len(self.deep_layers)):
self.y_deep = tf.add(tf.matmul(self.y_deep, self.weights["layer_%d" %i]), self.weights["bias_%d"%i]) # None * layer[i] * 1
if self.batch_norm:
self.y_deep = self.batch_norm_layer(self.y_deep, train_phase=self.train_phase, scope_bn="bn_%d" %i) # None * layer[i] * 1
self.y_deep = self.deep_layers_activation(self.y_deep)
self.y_deep = tf.nn.dropout(self.y_deep, self.dropout_keep_deep[1+i]) # dropout at each Deep layer
# ---------- DeepFM ----------
if self.use_fm and self.use_deep:
concat_input = tf.concat([self.y_first_order, self.y_second_order, self.y_deep], axis=1)
elif self.use_fm:
concat_input = tf.concat([self.y_first_order, self.y_second_order], axis=1)
elif self.use_deep:
concat_input = self.y_deep
self.out = tf.add(tf.matmul(concat_input, self.weights["concat_projection"]), self.weights["concat_bias"])
# loss
if self.loss_type == "logloss":
self.out = tf.nn.sigmoid(self.out)
self.loss = tf.losses.log_loss(self.label, self.out)
elif self.loss_type == "mse":
self.loss = tf.nn.l2_loss(tf.subtract(self.label, self.out))
# l2 regularization on weights
if self.l2_reg > 0:
self.loss += tf.contrib.layers.l2_regularizer(
self.l2_reg)(self.weights["concat_projection"])
if self.use_deep:
for i in range(len(self.deep_layers)):
self.loss += tf.contrib.layers.l2_regularizer(
self.l2_reg)(self.weights["layer_%d"%i])
# for nn in self.graph.as_graph_def().node:
# print(nn.name)
# optimizer
if self.optimizer_type == "adam":
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate, beta1=0.9, beta2=0.999,
epsilon=1e-8).minimize(self.loss)
elif self.optimizer_type == "adagrad":
self.optimizer = tf.train.AdagradOptimizer(learning_rate=self.learning_rate,
initial_accumulator_value=1e-8).minimize(self.loss)
elif self.optimizer_type == "gd":
self.optimizer = tf.train.GradientDescentOptimizer(learning_rate=self.learning_rate).minimize(self.loss)
elif self.optimizer_type == "momentum":
self.optimizer = tf.train.MomentumOptimizer(learning_rate=self.learning_rate, momentum=0.95).minimize(
self.loss)
# elif self.optimizer_type == "yellowfin":
# self.optimizer = YFOptimizer(learning_rate=self.learning_rate, momentum=0.0).minimize(
# self.loss)
# init
self.saver = tf.train.Saver()
if self.is_finetune:
self._load_old_model()
# opt = tf.train.MomentumOptimizer(learning_rate=self.learning_rate, momentum=0.95)
# self.optimizer = opt.minimize(self.loss)
# self.sess.run(tf.variables_initializer(opt.variables()))
# pass
else:
init = tf.global_variables_initializer()
self.sess.run(init)
# number of params
total_parameters = 0
for variable in self.weights.values():
shape = variable.get_shape()
variable_parameters = 1
for dim in shape:
variable_parameters *= dim.value
total_parameters += variable_parameters
if self.verbose > 0:
print("#params: %d" % total_parameters)
def _init_session(self):
config = tf.ConfigProto(device_count={"gpu": 0})
config.gpu_options.allow_growth = True
return tf.Session(config=config)
def _load_old_model(self):
weights = dict()
#saver = tf.train.import_meta_graph(os.path.join(config.SUB_DIR, 'model/0', 'fm-series-%d.meta' % (self.epoch-1)))
self.saver.restore(self.sess, tf.train.latest_checkpoint(os.path.join(config.SUB_DIR, 'model/0')))
# graph = tf.get_default_graph()
# weights["feature_embeddings"] = graph.get_tensor_by_name("feature_embeddings:0")
# weights["feature_bias"] = graph.get_tensor_by_name("feature_bias:0")
# weights["layer_0"] = graph.get_tensor_by_name("layer_0:0")
# weights["bias_0"] = graph.get_tensor_by_name("bias_0:0")
# num_layer = len(self.deep_layers)
# for i in range(1, num_layer):
# weights["layer_%d" % i] = graph.get_tensor_by_name("layer_%d:0" % i)
# weights["bias_%d"% i] = graph.get_tensor_by_name("bias_%d:0" % i)
#
# weights["concat_projection"] = graph.get_tensor_by_name("concat_projection:0")
# weights["concat_bias"] = graph.get_tensor_by_name("concat_bias:0")
#
# self.weights = weights
def _initialize_weights(self):
weights = dict()
# embeddings
weights["feature_embeddings"] = tf.Variable(
tf.random_normal([self.feature_size, self.embedding_size], 0.0, 0.01),
name="feature_embeddings") # feature_size * K
weights["feature_bias"] = tf.Variable(
tf.random_uniform([self.feature_size, 1], 0.0, 1.0), name="feature_bias") # feature_size * 1
# deep layers
num_layer = len(self.deep_layers)
input_size = self.field_size * self.embedding_size
glorot = np.sqrt(2.0 / (input_size + self.deep_layers[0]))
weights["layer_0"] = tf.Variable(
np.random.normal(loc=0, scale=glorot, size=(input_size, self.deep_layers[0])), dtype=np.float32, name="layer_0")
weights["bias_0"] = tf.Variable(np.random.normal(loc=0, scale=glorot, size=(1, self.deep_layers[0])),
dtype=np.float32, name="bias_0") # 1 * layers[0]
for i in range(1, num_layer):
glorot = np.sqrt(2.0 / (self.deep_layers[i-1] + self.deep_layers[i]))
weights["layer_%d" % i] = tf.Variable(
np.random.normal(loc=0, scale=glorot, size=(self.deep_layers[i-1], self.deep_layers[i])),
dtype=np.float32, name="layer_%d" % i) # layers[i-1] * layers[i]
weights["bias_%d" % i] = tf.Variable(
np.random.normal(loc=0, scale=glorot, size=(1, self.deep_layers[i])),
dtype=np.float32, name="bias_%d" % i ) # 1 * layer[i]
# final concat projection layer
if self.use_fm and self.use_deep:
input_size = self.field_size + self.embedding_size + self.deep_layers[-1]
elif self.use_fm:
input_size = self.field_size + self.embedding_size
elif self.use_deep:
input_size = self.deep_layers[-1]
glorot = np.sqrt(2.0 / (input_size + 1))
weights["concat_projection"] = tf.Variable(
np.random.normal(loc=0, scale=glorot, size=(input_size, 1)),
dtype=np.float32, name="concat_projection") # layers[i-1]*layers[i]
weights["concat_bias"] = tf.Variable(tf.constant(0.01), dtype=np.float32, name="concat_bias")
return weights
def batch_norm_layer(self, x, train_phase, scope_bn):
bn_train = batch_norm(x, decay=self.batch_norm_decay, center=True, scale=True, updates_collections=None,
is_training=True, reuse=None, trainable=True, scope=scope_bn)
bn_inference = batch_norm(x, decay=self.batch_norm_decay, center=True, scale=True, updates_collections=None,
is_training=False, reuse=True, trainable=True, scope=scope_bn)
z = tf.cond(train_phase, lambda: bn_train, lambda: bn_inference)
return z
def get_batch(self, Xi, Xv, y, batch_size, index):
start = index * batch_size
end = (index+1) * batch_size
end = end if end < len(y) else len(y)
return Xi[start:end], Xv[start:end], [[y_] for y_ in y[start:end]]
# shuffle three lists simutaneously
def shuffle_in_unison_scary(self, a, b, c):
rng_state = np.random.get_state()
np.random.shuffle(a)
np.random.set_state(rng_state)
np.random.shuffle(b)
np.random.set_state(rng_state)
np.random.shuffle(c)
def fit_on_batch(self, Xi, Xv, y):
feed_dict = {self.feat_index: Xi,
self.feat_value: Xv,
self.label: y,
self.dropout_keep_fm: self.dropout_fm,
self.dropout_keep_deep: self.dropout_deep,
self.train_phase: True}
loss, opt = self.sess.run((self.loss, self.optimizer), feed_dict=feed_dict)
return loss
def fit(self, Xi_train, Xv_train, y_train,
Xi_valid=None, Xv_valid=None, y_valid=None,
early_stopping=False, refit=False, fold_seq = 0):
"""
:param Xi_train: [[ind1_1, ind1_2, ...], [ind2_1, ind2_2, ...], ..., [indi_1, indi_2, ..., indi_j, ...], ...]
indi_j is the feature index of feature field j of sample i in the training set
:param Xv_train: [[val1_1, val1_2, ...], [val2_1, val2_2, ...], ..., [vali_1, vali_2, ..., vali_j, ...], ...]
vali_j is the feature value of feature field j of sample i in the training set
vali_j can be either binary (1/0, for binary/categorical features) or float (e.g., 10.24, for numerical features)
:param y_train: label of each sample in the training set
:param Xi_valid: list of list of feature indices of each sample in the validation set
:param Xv_valid: list of list of feature values of each sample in the validation set
:param y_valid: label of each sample in the validation set
:param early_stopping: perform early stopping or not
:param refit: refit the model on the train+valid dataset or not
:return: None
"""
has_valid = Xv_valid is not None
for epoch in range(self.epoch):
t1 = time()
self.shuffle_in_unison_scary(Xi_train, Xv_train, y_train)
total_batch = int(len(y_train) / self.batch_size)
for i in range(total_batch):
Xi_batch, Xv_batch, y_batch = self.get_batch(Xi_train, Xv_train, y_train, self.batch_size, i)
self.fit_on_batch(Xi_batch, Xv_batch, y_batch)
self.saver.save(self.sess, os.path.join(config.SUB_DIR, 'model', str(fold_seq), 'fm-series'), global_step=epoch)
# evaluate training and validation datasets
train_result = self.evaluate(Xi_train, Xv_train, y_train)
self.train_result.append(train_result)
if has_valid:
valid_result = self.evaluate(Xi_valid, Xv_valid, y_valid)
self.valid_result.append(valid_result)
if self.verbose > 0 and epoch % self.verbose == 0:
if has_valid:
print("[%d] train-result=%.4f, valid-result=%.4f [%.1f s]"
% (epoch + 1, train_result, valid_result, time() - t1))
else:
print("[%d] train-result=%.4f [%.1f s]"
% (epoch + 1, train_result, time() - t1))
if has_valid and early_stopping and self.training_termination(self.valid_result):
break
# fit a few more epoch on train+valid until result reaches the best_train_score
if has_valid and refit:
if self.greater_is_better:
best_valid_score = max(self.valid_result)
else:
best_valid_score = min(self.valid_result)
best_epoch = self.valid_result.index(best_valid_score)
best_train_score = self.train_result[best_epoch]
Xi_train = Xi_train + Xi_valid
Xv_train = Xv_train + Xv_valid
y_train = y_train + y_valid
for epoch in range(100):
self.shuffle_in_unison_scary(Xi_train, Xv_train, y_train)
total_batch = int(len(y_train) / self.batch_size)
for i in range(total_batch):
Xi_batch, Xv_batch, y_batch = self.get_batch(Xi_train, Xv_train, y_train,
self.batch_size, i)
self.fit_on_batch(Xi_batch, Xv_batch, y_batch)
# check
train_result = self.evaluate(Xi_train, Xv_train, y_train)
if abs(train_result - best_train_score) < 0.001 or \
(self.greater_is_better and train_result > best_train_score) or \
((not self.greater_is_better) and train_result < best_train_score):
break
def training_termination(self, valid_result):
if len(valid_result) > 5:
if self.greater_is_better:
if valid_result[-1] < valid_result[-2] and \
valid_result[-2] < valid_result[-3] and \
valid_result[-3] < valid_result[-4] and \
valid_result[-4] < valid_result[-5]:
return True
else:
if valid_result[-1] > valid_result[-2] and \
valid_result[-2] > valid_result[-3] and \
valid_result[-3] > valid_result[-4] and \
valid_result[-4] > valid_result[-5]:
return True
return False
def predict(self, Xi, Xv):
"""
:param Xi: list of list of feature indices of each sample in the dataset
:param Xv: list of list of feature values of each sample in the dataset
:return: predicted probability of each sample
"""
# dummy y
dummy_y = [1] * len(Xi)
batch_index = 0
Xi_batch, Xv_batch, y_batch = self.get_batch(Xi, Xv, dummy_y, self.batch_size, batch_index)
y_pred = None
while len(Xi_batch) > 0:
num_batch = len(y_batch)
feed_dict = {self.feat_index: Xi_batch,
self.feat_value: Xv_batch,
self.label: y_batch,
self.dropout_keep_fm: [1.0] * len(self.dropout_fm),
self.dropout_keep_deep: [1.0] * len(self.dropout_deep),
self.train_phase: False}
batch_out = self.sess.run(self.out, feed_dict=feed_dict)
if batch_index == 0:
y_pred = np.reshape(batch_out, (num_batch,))
else:
y_pred = np.concatenate((y_pred, np.reshape(batch_out, (num_batch,))))
batch_index += 1
Xi_batch, Xv_batch, y_batch = self.get_batch(Xi, Xv, dummy_y, self.batch_size, batch_index)
return y_pred
def evaluate(self, Xi, Xv, y):
"""
:param Xi: list of list of feature indices of each sample in the dataset
:param Xv: list of list of feature values of each sample in the dataset
:param y: label of each sample in the dataset
:return: metric of the evaluation
"""
y_pred = self.predict(Xi, Xv)
return self.eval_metric(y, y_pred)
|
[
"tensorflow.cond",
"tensorflow.reduce_sum",
"tensorflow.contrib.layers.l2_regularizer",
"tensorflow.reshape",
"numpy.random.set_state",
"tensorflow.train.AdamOptimizer",
"tensorflow.ConfigProto",
"tensorflow.multiply",
"tensorflow.matmul",
"tensorflow.losses.log_loss",
"numpy.random.normal",
"os.path.join",
"tensorflow.subtract",
"tensorflow.concat",
"tensorflow.set_random_seed",
"tensorflow.placeholder",
"numpy.reshape",
"numpy.random.shuffle",
"tensorflow.train.Saver",
"tensorflow.nn.embedding_lookup",
"tensorflow.global_variables_initializer",
"tensorflow.train.AdagradOptimizer",
"tensorflow.Session",
"tensorflow.constant",
"tensorflow.random_normal",
"tensorflow.train.MomentumOptimizer",
"tensorflow.Graph",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.random_uniform",
"tensorflow.contrib.layers.python.layers.batch_norm",
"numpy.random.get_state",
"time.time",
"tensorflow.square",
"tensorflow.nn.sigmoid",
"tensorflow.nn.dropout",
"numpy.sqrt"
] |
[((2513, 2523), 'tensorflow.Graph', 'tf.Graph', ([], {}), '()\n', (2521, 2523), True, 'import tensorflow as tf\n'), ((8938, 8977), 'tensorflow.ConfigProto', 'tf.ConfigProto', ([], {'device_count': "{'gpu': 0}"}), "(device_count={'gpu': 0})\n", (8952, 8977), True, 'import tensorflow as tf\n'), ((9040, 9065), 'tensorflow.Session', 'tf.Session', ([], {'config': 'config'}), '(config=config)\n', (9050, 9065), True, 'import tensorflow as tf\n'), ((10739, 10788), 'numpy.sqrt', 'np.sqrt', (['(2.0 / (input_size + self.deep_layers[0]))'], {}), '(2.0 / (input_size + self.deep_layers[0]))\n', (10746, 10788), True, 'import numpy as np\n'), ((12087, 12118), 'numpy.sqrt', 'np.sqrt', (['(2.0 / (input_size + 1))'], {}), '(2.0 / (input_size + 1))\n', (12094, 12118), True, 'import numpy as np\n'), ((12554, 12717), 'tensorflow.contrib.layers.python.layers.batch_norm', 'batch_norm', (['x'], {'decay': 'self.batch_norm_decay', 'center': '(True)', 'scale': '(True)', 'updates_collections': 'None', 'is_training': '(True)', 'reuse': 'None', 'trainable': '(True)', 'scope': 'scope_bn'}), '(x, decay=self.batch_norm_decay, center=True, scale=True,\n updates_collections=None, is_training=True, reuse=None, trainable=True,\n scope=scope_bn)\n', (12564, 12717), True, 'from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm\n'), ((12763, 12927), 'tensorflow.contrib.layers.python.layers.batch_norm', 'batch_norm', (['x'], {'decay': 'self.batch_norm_decay', 'center': '(True)', 'scale': '(True)', 'updates_collections': 'None', 'is_training': '(False)', 'reuse': '(True)', 'trainable': '(True)', 'scope': 'scope_bn'}), '(x, decay=self.batch_norm_decay, center=True, scale=True,\n updates_collections=None, is_training=False, reuse=True, trainable=True,\n scope=scope_bn)\n', (12773, 12927), True, 'from tensorflow.contrib.layers.python.layers import batch_norm as batch_norm\n'), ((12966, 13028), 'tensorflow.cond', 'tf.cond', (['train_phase', '(lambda : bn_train)', '(lambda : bn_inference)'], {}), '(train_phase, lambda : bn_train, lambda : bn_inference)\n', (12973, 13028), True, 'import tensorflow as tf\n'), ((13404, 13425), 'numpy.random.get_state', 'np.random.get_state', ([], {}), '()\n', (13423, 13425), True, 'import numpy as np\n'), ((13434, 13454), 'numpy.random.shuffle', 'np.random.shuffle', (['a'], {}), '(a)\n', (13451, 13454), True, 'import numpy as np\n'), ((13463, 13493), 'numpy.random.set_state', 'np.random.set_state', (['rng_state'], {}), '(rng_state)\n', (13482, 13493), True, 'import numpy as np\n'), ((13502, 13522), 'numpy.random.shuffle', 'np.random.shuffle', (['b'], {}), '(b)\n', (13519, 13522), True, 'import numpy as np\n'), ((13531, 13561), 'numpy.random.set_state', 'np.random.set_state', (['rng_state'], {}), '(rng_state)\n', (13550, 13561), True, 'import numpy as np\n'), ((13570, 13590), 'numpy.random.shuffle', 'np.random.shuffle', (['c'], {}), '(c)\n', (13587, 13590), True, 'import numpy as np\n'), ((2575, 2611), 'tensorflow.set_random_seed', 'tf.set_random_seed', (['self.random_seed'], {}), '(self.random_seed)\n', (2593, 2611), True, 'import tensorflow as tf\n'), ((2687, 2750), 'tensorflow.placeholder', 'tf.placeholder', (['tf.int32'], {'shape': '[None, None]', 'name': '"""feat_index"""'}), "(tf.int32, shape=[None, None], name='feat_index')\n", (2701, 2750), True, 'import tensorflow as tf\n'), ((2793, 2858), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, None]', 'name': '"""feat_value"""'}), "(tf.float32, shape=[None, None], name='feat_value')\n", (2807, 2858), True, 'import tensorflow as tf\n'), ((2896, 2953), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None, 1]', 'name': '"""label"""'}), "(tf.float32, shape=[None, 1], name='label')\n", (2910, 2953), True, 'import tensorflow as tf\n'), ((3001, 3065), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None]', 'name': '"""dropout_keep_fm"""'}), "(tf.float32, shape=[None], name='dropout_keep_fm')\n", (3015, 3065), True, 'import tensorflow as tf\n'), ((3103, 3169), 'tensorflow.placeholder', 'tf.placeholder', (['tf.float32'], {'shape': '[None]', 'name': '"""dropout_keep_deep"""'}), "(tf.float32, shape=[None], name='dropout_keep_deep')\n", (3117, 3169), True, 'import tensorflow as tf\n'), ((3201, 3244), 'tensorflow.placeholder', 'tf.placeholder', (['tf.bool'], {'name': '"""train_phase"""'}), "(tf.bool, name='train_phase')\n", (3215, 3244), True, 'import tensorflow as tf\n'), ((3351, 3426), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (["self.weights['feature_embeddings']", 'self.feat_index'], {}), "(self.weights['feature_embeddings'], self.feat_index)\n", (3373, 3426), True, 'import tensorflow as tf\n'), ((3468, 3527), 'tensorflow.reshape', 'tf.reshape', (['self.feat_value'], {'shape': '[-1, self.field_size, 1]'}), '(self.feat_value, shape=[-1, self.field_size, 1])\n', (3478, 3527), True, 'import tensorflow as tf\n'), ((3558, 3598), 'tensorflow.multiply', 'tf.multiply', (['self.embeddings', 'feat_value'], {}), '(self.embeddings, feat_value)\n', (3569, 3598), True, 'import tensorflow as tf\n'), ((3686, 3755), 'tensorflow.nn.embedding_lookup', 'tf.nn.embedding_lookup', (["self.weights['feature_bias']", 'self.feat_index'], {}), "(self.weights['feature_bias'], self.feat_index)\n", (3708, 3755), True, 'import tensorflow as tf\n'), ((3911, 3969), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['self.y_first_order', 'self.dropout_keep_fm[0]'], {}), '(self.y_first_order, self.dropout_keep_fm[0])\n', (3924, 3969), True, 'import tensorflow as tf\n'), ((4110, 4143), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self.embeddings', '(1)'], {}), '(self.embeddings, 1)\n', (4123, 4143), True, 'import tensorflow as tf\n'), ((4202, 4237), 'tensorflow.square', 'tf.square', (['self.summed_features_emb'], {}), '(self.summed_features_emb)\n', (4211, 4237), True, 'import tensorflow as tf\n'), ((4321, 4347), 'tensorflow.square', 'tf.square', (['self.embeddings'], {}), '(self.embeddings)\n', (4330, 4347), True, 'import tensorflow as tf\n'), ((4392, 4435), 'tensorflow.reduce_sum', 'tf.reduce_sum', (['self.squared_features_emb', '(1)'], {}), '(self.squared_features_emb, 1)\n', (4405, 4435), True, 'import tensorflow as tf\n'), ((4638, 4697), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['self.y_second_order', 'self.dropout_keep_fm[1]'], {}), '(self.y_second_order, self.dropout_keep_fm[1])\n', (4651, 4697), True, 'import tensorflow as tf\n'), ((4788, 4866), 'tensorflow.reshape', 'tf.reshape', (['self.embeddings'], {'shape': '[-1, self.field_size * self.embedding_size]'}), '(self.embeddings, shape=[-1, self.field_size * self.embedding_size])\n', (4798, 4866), True, 'import tensorflow as tf\n'), ((4908, 4961), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['self.y_deep', 'self.dropout_keep_deep[0]'], {}), '(self.y_deep, self.dropout_keep_deep[0])\n', (4921, 4961), True, 'import tensorflow as tf\n'), ((7997, 8013), 'tensorflow.train.Saver', 'tf.train.Saver', ([], {}), '()\n', (8011, 8013), True, 'import tensorflow as tf\n'), ((10315, 10384), 'tensorflow.random_normal', 'tf.random_normal', (['[self.feature_size, self.embedding_size]', '(0.0)', '(0.01)'], {}), '([self.feature_size, self.embedding_size], 0.0, 0.01)\n', (10331, 10384), True, 'import tensorflow as tf\n'), ((10504, 10555), 'tensorflow.random_uniform', 'tf.random_uniform', (['[self.feature_size, 1]', '(0.0)', '(1.0)'], {}), '([self.feature_size, 1], 0.0, 1.0)\n', (10521, 10555), True, 'import tensorflow as tf\n'), ((10843, 10920), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0)', 'scale': 'glorot', 'size': '(input_size, self.deep_layers[0])'}), '(loc=0, scale=glorot, size=(input_size, self.deep_layers[0]))\n', (10859, 10920), True, 'import numpy as np\n'), ((10996, 11064), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0)', 'scale': 'glorot', 'size': '(1, self.deep_layers[0])'}), '(loc=0, scale=glorot, size=(1, self.deep_layers[0]))\n', (11012, 11064), True, 'import numpy as np\n'), ((11231, 11293), 'numpy.sqrt', 'np.sqrt', (['(2.0 / (self.deep_layers[i - 1] + self.deep_layers[i]))'], {}), '(2.0 / (self.deep_layers[i - 1] + self.deep_layers[i]))\n', (11238, 11293), True, 'import numpy as np\n'), ((12195, 12254), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0)', 'scale': 'glorot', 'size': '(input_size, 1)'}), '(loc=0, scale=glorot, size=(input_size, 1))\n', (12211, 12254), True, 'import numpy as np\n'), ((12394, 12411), 'tensorflow.constant', 'tf.constant', (['(0.01)'], {}), '(0.01)\n', (12405, 12411), True, 'import tensorflow as tf\n'), ((15371, 15377), 'time.time', 'time', ([], {}), '()\n', (15375, 15377), False, 'from time import time\n'), ((3818, 3861), 'tensorflow.multiply', 'tf.multiply', (['self.y_first_order', 'feat_value'], {}), '(self.y_first_order, feat_value)\n', (3829, 3861), True, 'import tensorflow as tf\n'), ((4516, 4591), 'tensorflow.subtract', 'tf.subtract', (['self.summed_features_emb_square', 'self.squared_sum_features_emb'], {}), '(self.summed_features_emb_square, self.squared_sum_features_emb)\n', (4527, 4591), True, 'import tensorflow as tf\n'), ((5434, 5491), 'tensorflow.nn.dropout', 'tf.nn.dropout', (['self.y_deep', 'self.dropout_keep_deep[1 + i]'], {}), '(self.y_deep, self.dropout_keep_deep[1 + i])\n', (5447, 5491), True, 'import tensorflow as tf\n'), ((5640, 5713), 'tensorflow.concat', 'tf.concat', (['[self.y_first_order, self.y_second_order, self.y_deep]'], {'axis': '(1)'}), '([self.y_first_order, self.y_second_order, self.y_deep], axis=1)\n', (5649, 5713), True, 'import tensorflow as tf\n'), ((5941, 5999), 'tensorflow.matmul', 'tf.matmul', (['concat_input', "self.weights['concat_projection']"], {}), "(concat_input, self.weights['concat_projection'])\n", (5950, 5999), True, 'import tensorflow as tf\n'), ((6121, 6144), 'tensorflow.nn.sigmoid', 'tf.nn.sigmoid', (['self.out'], {}), '(self.out)\n', (6134, 6144), True, 'import tensorflow as tf\n'), ((6173, 6213), 'tensorflow.losses.log_loss', 'tf.losses.log_loss', (['self.label', 'self.out'], {}), '(self.label, self.out)\n', (6191, 6213), True, 'import tensorflow as tf\n'), ((8384, 8417), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (8415, 8417), True, 'import tensorflow as tf\n'), ((9312, 9351), 'os.path.join', 'os.path.join', (['config.SUB_DIR', '"""model/0"""'], {}), "(config.SUB_DIR, 'model/0')\n", (9324, 9351), False, 'import os\n'), ((11359, 11454), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0)', 'scale': 'glorot', 'size': '(self.deep_layers[i - 1], self.deep_layers[i])'}), '(loc=0, scale=glorot, size=(self.deep_layers[i - 1], self.\n deep_layers[i]))\n', (11375, 11454), True, 'import numpy as np\n'), ((11597, 11665), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0)', 'scale': 'glorot', 'size': '(1, self.deep_layers[i])'}), '(loc=0, scale=glorot, size=(1, self.deep_layers[i]))\n', (11613, 11665), True, 'import numpy as np\n'), ((19815, 19850), 'numpy.reshape', 'np.reshape', (['batch_out', '(num_batch,)'], {}), '(batch_out, (num_batch,))\n', (19825, 19850), True, 'import numpy as np\n'), ((5053, 5105), 'tensorflow.matmul', 'tf.matmul', (['self.y_deep', "self.weights['layer_%d' % i]"], {}), "(self.y_deep, self.weights['layer_%d' % i])\n", (5062, 5105), True, 'import tensorflow as tf\n'), ((5775, 5835), 'tensorflow.concat', 'tf.concat', (['[self.y_first_order, self.y_second_order]'], {'axis': '(1)'}), '([self.y_first_order, self.y_second_order], axis=1)\n', (5784, 5835), True, 'import tensorflow as tf\n'), ((6437, 6482), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['self.l2_reg'], {}), '(self.l2_reg)\n', (6469, 6482), True, 'import tensorflow as tf\n'), ((6298, 6331), 'tensorflow.subtract', 'tf.subtract', (['self.label', 'self.out'], {}), '(self.label, self.out)\n', (6309, 6331), True, 'import tensorflow as tf\n'), ((6964, 7064), 'tensorflow.train.AdamOptimizer', 'tf.train.AdamOptimizer', ([], {'learning_rate': 'self.learning_rate', 'beta1': '(0.9)', 'beta2': '(0.999)', 'epsilon': '(1e-08)'}), '(learning_rate=self.learning_rate, beta1=0.9, beta2=\n 0.999, epsilon=1e-08)\n', (6986, 7064), True, 'import tensorflow as tf\n'), ((19918, 19953), 'numpy.reshape', 'np.reshape', (['batch_out', '(num_batch,)'], {}), '(batch_out, (num_batch,))\n', (19928, 19953), True, 'import numpy as np\n'), ((6669, 6714), 'tensorflow.contrib.layers.l2_regularizer', 'tf.contrib.layers.l2_regularizer', (['self.l2_reg'], {}), '(self.l2_reg)\n', (6701, 6714), True, 'import tensorflow as tf\n'), ((7219, 7315), 'tensorflow.train.AdagradOptimizer', 'tf.train.AdagradOptimizer', ([], {'learning_rate': 'self.learning_rate', 'initial_accumulator_value': '(1e-08)'}), '(learning_rate=self.learning_rate,\n initial_accumulator_value=1e-08)\n', (7244, 7315), True, 'import tensorflow as tf\n'), ((7469, 7536), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', ([], {'learning_rate': 'self.learning_rate'}), '(learning_rate=self.learning_rate)\n', (7502, 7536), True, 'import tensorflow as tf\n'), ((7642, 7717), 'tensorflow.train.MomentumOptimizer', 'tf.train.MomentumOptimizer', ([], {'learning_rate': 'self.learning_rate', 'momentum': '(0.95)'}), '(learning_rate=self.learning_rate, momentum=0.95)\n', (7668, 7717), True, 'import tensorflow as tf\n'), ((16419, 16425), 'time.time', 'time', ([], {}), '()\n', (16423, 16425), False, 'from time import time\n'), ((16567, 16573), 'time.time', 'time', ([], {}), '()\n', (16571, 16573), False, 'from time import time\n')]
|
'''
DIO using a serial port + microcontroller instead of the NIDAQ card
'''
import serial
from collections import defaultdict
import struct
from numpy import binary_repr
from .dio.parse import MSG_TYPE_ROWBYTE, MSG_TYPE_REGISTER
import time
import threading
import pyfirmata
def construct_word(aux, msg_type, data, n_bits_data=8, n_bits_msg_type=3):
word = (aux << (n_bits_data + n_bits_msg_type)) | (msg_type << n_bits_data) | data
return word
def parse_word(word, n_bits_data=8, n_bits_msg_type=3):
data = word & ((1 << n_bits_data) - 1)
msg_type = (word >> n_bits_data) & ((1 << n_bits_msg_type) - 1)
aux = word >> n_bits_msg_type + n_bits_data
return aux, msg_type, data
baudrate = 115200
class SendRowByte(object):
'''
Send only an 8-bit data word corresponding to the 8 lower
bits of the current row number of the HDF table
'''
'''
Interface for sending all the task-generated data through the NIDAQ interface card
'''
def __init__(self, device=None):
'''
Constructor for SendRowByte
Parameters
----------
device : string, optional
Linux name of the serial port for the Arduino board, defined by setserial
Returns
-------
SendAll instance
'''
self.systems = dict()
self.port = serial.Serial('/dev/arduino_neurosync', baudrate=baudrate)
self.n_systems = 0
self.rowcount = defaultdict(int)
def close(self):
'''
Release access to the Arduino serial port
'''
# stop recording
self.port.write('p')
self.port.close()
def register(self, system, dtype):
'''
Send information about the registration system (name and datatype) in string form, one byte at a time.
Parameters
----------
system : string
Name of the system being registered
dtype : np.dtype instance
Datatype of incoming data, for later decoding of the binary data during analysis
Returns
-------
None
'''
# Save the index of the system being registered (arbitrary number corresponding to the order in which systems were registered)
self.n_systems += 1
self.systems[system] = self.n_systems
# if self.n_systems > 1:
# raise Exception("This currently only works for one system!")
#print "System Register: %s" % system, self.systems[system]
#print "Arduino register %s" % system, self.systems[system]
#if self.n_systems > 1:
# raise Exception("This currently only works for one system!")
print("Arduino register %s" % system, self.systems[system])
for sys_name_chr in system:
reg_word = construct_word(self.systems[system], MSG_TYPE_REGISTER, ord(sys_name_chr))
self._send_data_word_to_serial_port(reg_word)
null_term_word = construct_word(self.systems[system], MSG_TYPE_REGISTER, 0) # data payload is 0 for null terminator
self._send_data_word_to_serial_port(null_term_word)
def sendMsg(self, msg):
'''
Do nothing. Messages are stored with row numbers in the HDF table, so no need to also send the message over to the recording system.
Parameters
----------
msg : string
Message to send
Returns
-------
None
'''
# there's no point in sending a message, since every message is
# stored in the HDF table anyway with a row number,
# and every row number is automatically synced.
pass
def send(self, system, data):
'''
Send the row number for a data word to the neural system
Parameters
----------
system : string
Name of system
data : object
This is unused. Only used in the parent's version where the actual data, and not just the HDF row number, is sent.
Returns
-------
None
'''
if not (system in self.systems):
# if the system is not registered, do nothing
return
current_sys_rowcount = self.rowcount[system]
self.rowcount[system] += 1
# construct the data packet
word = construct_word(self.systems[system], MSG_TYPE_ROWBYTE, current_sys_rowcount % 256)
self._send_data_word_to_serial_port(word)
# if verbose:
# print binary_repr(word, 16)
# word_str = 'd' + struct.pack('<H', word)
# self.port.write(word_str)
def _send_data_word_to_serial_port(self, word, verbose=False):
#self.port.write(word)
if verbose:
print(binary_repr(word, 16))
word_str = 'd' + struct.pack('<H', word)
self.port.write(word_str)
|
[
"serial.Serial",
"collections.defaultdict",
"numpy.binary_repr",
"struct.pack"
] |
[((1347, 1405), 'serial.Serial', 'serial.Serial', (['"""/dev/arduino_neurosync"""'], {'baudrate': 'baudrate'}), "('/dev/arduino_neurosync', baudrate=baudrate)\n", (1360, 1405), False, 'import serial\n'), ((1457, 1473), 'collections.defaultdict', 'defaultdict', (['int'], {}), '(int)\n', (1468, 1473), False, 'from collections import defaultdict\n'), ((4815, 4838), 'struct.pack', 'struct.pack', (['"""<H"""', 'word'], {}), "('<H', word)\n", (4826, 4838), False, 'import struct\n'), ((4767, 4788), 'numpy.binary_repr', 'binary_repr', (['word', '(16)'], {}), '(word, 16)\n', (4778, 4788), False, 'from numpy import binary_repr\n')]
|
import copy
import os
import pickle
import numpy as np
from numpy.linalg import inv
from numpy.matlib import repmat
import pylot.utils
class DepthFrame(object):
"""Class that stores depth frames.
Args:
frame: A numpy array storing the depth frame.
camera_setup (:py:class:`~pylot.drivers.sensor_setup.DepthCameraSetup`): # noqa: E501
The camera setup used by the sensor that generated this frame.
original_frame: A numpy array storing the RGB encoded depth image.
Attributes:
frame: A numpy array storing the depth frame.
camera_setup (:py:class:`~pylot.drivers.sensor_setup.DepthCameraSetup`):
The camera setup used by the sensor that generated this frame.
original_frame: A numpy array storing the RGB encoded depth image.
"""
def __init__(self, frame, camera_setup, original_frame=None):
self.frame = frame
self.camera_setup = camera_setup
self.original_frame = original_frame
# Attribute used to cache the depth frame as a point cloud. We're doing
# this because it is computationally expensive to transform a depth
# frame to a point cloud.
self._cached_point_cloud = None
@classmethod
def from_simulator_frame(cls,
frame,
camera_setup,
save_original_frame=False):
"""Creates a pylot depth frame from a simulator depth frame.
Args:
frame: An image instance containing the depth image.
camera_setup: The setup of the depth camera.
save_original_frame: True if the original RGB image needs to be
saved.
Returns:
:py:class:`.DepthFrame`: A depth frame.
"""
original_frame = None
# Convert an image containing simulator encoded depth-map to a 2D
# array containing the depth value of each pixel normalized
# between [0.0, 1.0]
_frame = np.frombuffer(frame.raw_data, dtype=np.dtype("uint8"))
_frame = np.reshape(_frame, (frame.height, frame.width, 4))
frame = _frame.astype(np.float32)
if save_original_frame:
original_frame = copy.deepcopy(frame[:, :, :3])
# Apply (R + G * 256 + B * 256 * 256) / (256 * 256 * 256 - 1).
frame = np.dot(frame[:, :, :3], [65536.0, 256.0, 1.0])
frame /= 16777215.0 # (256.0 * 256.0 * 256.0 - 1.0)
return cls(frame, camera_setup, original_frame)
def as_numpy_array(self):
"""Returns the depth frame as a numpy array."""
return self.frame
def as_point_cloud(self):
"""Converts the depth frame to a 1D array containing the 3D
position of each pixel in world coordinates.
See :py:class:`~pylot.drivers.sensor_setup.CameraSetup` for
coordinate axis orientations.
"""
far = 1000.0 # max depth in meters.
intrinsic_mat = self.camera_setup.get_intrinsic_matrix()
width, height = self.camera_setup.width, self.camera_setup.height
# 2d pixel coordinates
pixel_length = width * height
u_coord = repmat(np.r_[0:width:1], height, 1).reshape(pixel_length)
v_coord = repmat(np.c_[0:height:1], 1, width).reshape(pixel_length)
normalized_depth = np.reshape(self.frame, pixel_length)
# p2d = [u,v,1]
p2d = np.array([u_coord, v_coord, np.ones_like(u_coord)])
# P = [X,Y,Z]
p3d = np.dot(inv(intrinsic_mat), p2d)
p3d *= normalized_depth * far
# [[X1,Y1,Z1],[X2,Y2,Z2], ... [Xn,Yn,Zn]]
locations = np.asarray(np.transpose(p3d))
# Transform the points in 3D world coordinates.
to_world_transform = self.camera_setup.get_unreal_transform()
point_cloud = to_world_transform.transform_points(locations)
return point_cloud
def get_pixel_locations(self, pixels):
""" Gets the 3D world locations from pixel coordinates.
Args:
pixels: List of pylot.utils.Vector2D pixel coordinates.
Returns:
List of pylot.utils.Locations
"""
if self._cached_point_cloud is None:
self._cached_point_cloud = self.as_point_cloud()
pixel_locations = [
self._cached_point_cloud[pixel.y * self.camera_setup.width +
pixel.x] for pixel in pixels
]
return [
pylot.utils.Location(loc[0], loc[1], loc[2])
for loc in pixel_locations
]
def pixel_has_same_depth(self, x, y, z, threshold):
"""Checks if the depth of pixel (y,x) is within threshold of z."""
return abs(self.frame[int(y)][int(x)] * 1000 - z) < threshold
def resize(self, width, height):
"""Resizes the frame."""
import cv2
self.camera_setup.set_resolution(width, height)
self.frame = cv2.resize(self.frame,
dsize=(width, height),
interpolation=cv2.INTER_NEAREST)
def visualize(self, pygame_display, timestamp=None):
"""Visualizes the frame on a pygame display."""
if self.original_frame is not None:
import pygame
image_np = self.original_frame
image_np = image_np[:, :, ::-1]
image_np = np.transpose(image_np, (1, 0, 2))
pygame.surfarray.blit_array(pygame_display, image_np)
pygame.display.flip()
def save(self, timestamp, data_path, file_base):
"""Saves the depth frame to a file.
Args:
timestamp (:obj:`int`): Timestamp associated with the depth frame.
data_path (:obj:`str`): Path where to save the depth frame.
file_base (:obj:`str`): Base name of the file.
"""
file_name = os.path.join(data_path,
'{}-{}.pkl'.format(file_base, timestamp))
pickle.dump(self.as_numpy_array(),
open(file_name, 'wb'),
protocol=pickle.HIGHEST_PROTOCOL)
def __repr__(self):
return 'DepthFrame(camera_setup: {}, frame: {})'.format(
self.camera_setup, self.frame)
def __str__(self):
return 'DepthFrame(camera_setup: {})'.format(self.camera_setup)
|
[
"copy.deepcopy",
"numpy.ones_like",
"numpy.dtype",
"numpy.transpose",
"pygame.display.flip",
"pygame.surfarray.blit_array",
"numpy.linalg.inv",
"numpy.reshape",
"numpy.dot",
"numpy.matlib.repmat",
"cv2.resize"
] |
[((2098, 2148), 'numpy.reshape', 'np.reshape', (['_frame', '(frame.height, frame.width, 4)'], {}), '(_frame, (frame.height, frame.width, 4))\n', (2108, 2148), True, 'import numpy as np\n'), ((2370, 2416), 'numpy.dot', 'np.dot', (['frame[:, :, :3]', '[65536.0, 256.0, 1.0]'], {}), '(frame[:, :, :3], [65536.0, 256.0, 1.0])\n', (2376, 2416), True, 'import numpy as np\n'), ((3350, 3386), 'numpy.reshape', 'np.reshape', (['self.frame', 'pixel_length'], {}), '(self.frame, pixel_length)\n', (3360, 3386), True, 'import numpy as np\n'), ((4945, 5023), 'cv2.resize', 'cv2.resize', (['self.frame'], {'dsize': '(width, height)', 'interpolation': 'cv2.INTER_NEAREST'}), '(self.frame, dsize=(width, height), interpolation=cv2.INTER_NEAREST)\n', (4955, 5023), False, 'import cv2\n'), ((2252, 2282), 'copy.deepcopy', 'copy.deepcopy', (['frame[:, :, :3]'], {}), '(frame[:, :, :3])\n', (2265, 2282), False, 'import copy\n'), ((3522, 3540), 'numpy.linalg.inv', 'inv', (['intrinsic_mat'], {}), '(intrinsic_mat)\n', (3525, 3540), False, 'from numpy.linalg import inv\n'), ((3667, 3684), 'numpy.transpose', 'np.transpose', (['p3d'], {}), '(p3d)\n', (3679, 3684), True, 'import numpy as np\n'), ((5382, 5415), 'numpy.transpose', 'np.transpose', (['image_np', '(1, 0, 2)'], {}), '(image_np, (1, 0, 2))\n', (5394, 5415), True, 'import numpy as np\n'), ((5428, 5481), 'pygame.surfarray.blit_array', 'pygame.surfarray.blit_array', (['pygame_display', 'image_np'], {}), '(pygame_display, image_np)\n', (5455, 5481), False, 'import pygame\n'), ((5494, 5515), 'pygame.display.flip', 'pygame.display.flip', ([], {}), '()\n', (5513, 5515), False, 'import pygame\n'), ((2062, 2079), 'numpy.dtype', 'np.dtype', (['"""uint8"""'], {}), "('uint8')\n", (2070, 2079), True, 'import numpy as np\n'), ((3189, 3224), 'numpy.matlib.repmat', 'repmat', (['np.r_[0:width:1]', 'height', '(1)'], {}), '(np.r_[0:width:1], height, 1)\n', (3195, 3224), False, 'from numpy.matlib import repmat\n'), ((3265, 3300), 'numpy.matlib.repmat', 'repmat', (['np.c_[0:height:1]', '(1)', 'width'], {}), '(np.c_[0:height:1], 1, width)\n', (3271, 3300), False, 'from numpy.matlib import repmat\n'), ((3454, 3475), 'numpy.ones_like', 'np.ones_like', (['u_coord'], {}), '(u_coord)\n', (3466, 3475), True, 'import numpy as np\n')]
|
"""
Coordinate Transformation Functions
This module contains the functions for converting one
`sunpy.coordinates.frames` object to another.
.. warning::
The functions in this submodule should never be called directly, transforming
between coordinate frames should be done using the ``.transform_to`` methods
on `~astropy.coordinates.BaseCoordinateFrame` or
`~astropy.coordinates.SkyCoord` instances.
"""
import logging
from copy import deepcopy
from functools import wraps
from contextlib import contextmanager
import numpy as np
import astropy.units as u
from astropy.constants import c as speed_of_light
from astropy.coordinates import (
HCRS,
ICRS,
BaseCoordinateFrame,
ConvertError,
HeliocentricMeanEcliptic,
get_body_barycentric,
)
from astropy.coordinates.baseframe import frame_transform_graph
from astropy.coordinates.builtin_frames import make_transform_graph_docs
from astropy.coordinates.builtin_frames.utils import get_jd12
from astropy.coordinates.matrix_utilities import matrix_product, matrix_transpose, rotation_matrix
from astropy.coordinates.representation import (
CartesianRepresentation,
SphericalRepresentation,
UnitSphericalRepresentation,
)
# Import erfa via astropy to make sure we are using the same ERFA library as Astropy
from astropy.coordinates.sky_coordinate import erfa
from astropy.coordinates.transformations import FunctionTransform, FunctionTransformWithFiniteDifference
from astropy.time import Time
from sunpy import log
from sunpy.sun import constants
from .frames import (
_J2000,
GeocentricEarthEquatorial,
GeocentricSolarEcliptic,
Heliocentric,
HeliocentricEarthEcliptic,
HeliocentricInertial,
HeliographicCarrington,
HeliographicStonyhurst,
Helioprojective,
)
RSUN_METERS = constants.get('radius').si.to(u.m)
__all__ = ['transform_with_sun_center',
'propagate_with_solar_surface',
'hgs_to_hgc', 'hgc_to_hgs', 'hcc_to_hpc',
'hpc_to_hcc', 'hcc_to_hgs', 'hgs_to_hcc',
'hpc_to_hpc',
'hcrs_to_hgs', 'hgs_to_hcrs',
'hgs_to_hgs', 'hgc_to_hgc', 'hcc_to_hcc',
'hme_to_hee', 'hee_to_hme', 'hee_to_hee',
'hee_to_gse', 'gse_to_hee', 'gse_to_gse',
'hgs_to_hci', 'hci_to_hgs', 'hci_to_hci',
'hme_to_gei', 'gei_to_hme', 'gei_to_gei']
# Boolean flag for whether to ignore the motion of the center of the Sun in inertial space
_ignore_sun_motion = False
# If not None, the name of the differential-rotation model to use for any obstime change
_autoapply_diffrot = None
@contextmanager
def transform_with_sun_center():
"""
Context manager for coordinate transformations to ignore the motion of the center of the Sun.
Normally, coordinates refer to a point in inertial space (relative to the barycenter of the
solar system). Transforming to a different observation time does not move the point at all,
but rather only updates the coordinate representation as needed for the origin and axis
orientations at the new observation time. However, the center of the Sun moves over time.
Thus, for example, a coordinate that lies on the surface of the Sun at one observation time
will not continue to lie on the surface of the Sun at other observation times.
Under this context manager, transformations will instead move the coordinate over time to
"follow" the translational motion of the center of Sun, thus maintaining the position of the
coordinate relative to the center of the Sun.
Notes
-----
This context manager accounts only for the motion of the center of the Sun, i.e.,
translational motion. The motion of solar features due to any rotation of the Sun about its
rotational axis is not accounted for.
Due to the implementation approach, this context manager modifies transformations between only
these five coordinate frames:
`~sunpy.coordinates.frames.HeliographicStonyhurst`,
`~sunpy.coordinates.frames.HeliographicCarrington`,
`~sunpy.coordinates.frames.HeliocentricInertial`,
`~sunpy.coordinates.frames.Heliocentric`, and
`~sunpy.coordinates.frames.Helioprojective`.
Examples
--------
>>> from astropy.coordinates import SkyCoord
>>> from sunpy.coordinates import HeliographicStonyhurst, transform_with_sun_center
>>> import astropy.units as u
>>> start_frame = HeliographicStonyhurst(obstime="2001-01-01")
>>> end_frame = HeliographicStonyhurst(obstime="2001-02-01")
>>> sun_center = SkyCoord(0*u.deg, 0*u.deg, 0*u.AU, frame=start_frame)
>>> sun_center
<SkyCoord (HeliographicStonyhurst: obstime=2001-01-01T00:00:00.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, AU)
(0., 0., 0.)>
>>> sun_center.transform_to(end_frame) # transformations do not normally follow Sun center
<SkyCoord (HeliographicStonyhurst: obstime=2001-02-01T00:00:00.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, AU)
(23.33174233, -5.96399877, 0.00027959)>
>>> with transform_with_sun_center():
... sun_center.transform_to(end_frame) # now following Sun center
<SkyCoord (HeliographicStonyhurst: obstime=2001-02-01T00:00:00.000, rsun=695700.0 km): (lon, lat, radius) in (deg, deg, AU)
(0., 0., 0.)>
"""
try:
global _ignore_sun_motion
old_ignore_sun_motion = _ignore_sun_motion # nominally False
if not old_ignore_sun_motion:
log.debug("Ignoring the motion of the center of the Sun for transformations")
_ignore_sun_motion = True
yield
finally:
if not old_ignore_sun_motion:
log.debug("Stop ignoring the motion of the center of the Sun for transformations")
_ignore_sun_motion = old_ignore_sun_motion
@contextmanager
def propagate_with_solar_surface(rotation_model='howard'):
"""
Context manager for coordinate transformations to automatically apply solar
differential rotation for any change in observation time.
Normally, coordinates refer to a point in inertial space (relative to the
barycenter of the solar system). Transforming to a different observation time
does not move the point at all, but rather only updates the coordinate
representation as needed for the origin and axis orientations at the new
observation time.
Under this context manager, transformations will instead treat the coordinate
as if it were referring to a point on the solar surface instead of a point in
inertial space. If a transformation has a change in observation time, the
heliographic longitude of the point will be updated according to the specified
rotation model.
Parameters
----------
rotation_model : `str`
Accepted model names are ``'howard'`` (default), ``'snodgrass'``,
``'allen'``, and ``'rigid'``. See the documentation for
:func:`~sunpy.physics.differential_rotation.diff_rot` for the differences
between these models.
Notes
-----
This context manager also ignores the motion of the center of the Sun (see
:func:`~sunpy.coordinates.transformations.transform_with_sun_center`).
Due to the implementation approach, this context manager modifies
transformations between only these five coordinate frames:
`~sunpy.coordinates.frames.HeliographicStonyhurst`,
`~sunpy.coordinates.frames.HeliographicCarrington`,
`~sunpy.coordinates.frames.HeliocentricInertial`,
`~sunpy.coordinates.frames.Heliocentric`, and
`~sunpy.coordinates.frames.Helioprojective`.
Examples
--------
.. minigallery:: sunpy.coordinates.propagate_with_solar_surface
>>> import astropy.units as u
>>> from astropy.coordinates import SkyCoord
>>> from sunpy.coordinates import HeliocentricInertial, propagate_with_solar_surface
>>> meridian = SkyCoord(0*u.deg, [-60, -30, 0, 30, 60]*u.deg, 1*u.AU,
... frame=HeliocentricInertial, obstime='2021-09-15')
>>> out_frame = HeliocentricInertial(obstime='2021-09-21')
>>> with propagate_with_solar_surface():
... print(meridian.transform_to(out_frame))
<SkyCoord (HeliocentricInertial: obstime=2021-09-21T00:00:00.000): (lon, lat, distance) in (deg, deg, AU)
[(70.24182965, -60., 1.),
(82.09298036, -30., 1.),
(85.9579703 , 0., 1.),
(82.09298036, 30., 1.),
(70.24182965, 60., 1.)]>
>>> with propagate_with_solar_surface(rotation_model='rigid'):
... print(meridian.transform_to(out_frame))
<SkyCoord (HeliocentricInertial: obstime=2021-09-21T00:00:00.000): (lon, lat, distance) in (deg, deg, AU)
[(85.1064, -60., 1.), (85.1064, -30., 1.),
(85.1064, 0., 1.), (85.1064, 30., 1.),
(85.1064, 60., 1.)]>
"""
with transform_with_sun_center():
try:
global _autoapply_diffrot
old_autoapply_diffrot = _autoapply_diffrot # nominally False
log.debug("Enabling automatic solar differential rotation "
f"('{rotation_model}') for any changes in obstime")
_autoapply_diffrot = rotation_model
yield
finally:
if not old_autoapply_diffrot:
log.debug("Disabling automatic solar differential rotation "
"for any changes in obstime")
_autoapply_diffrot = old_autoapply_diffrot
# Global counter to keep track of the layer of transformation
_layer_level = 0
def _transformation_debug(description):
"""
Decorator to produce debugging output for a transformation function: its description, inputs,
and output. Unicode box-drawing characters are used.
"""
def decorator(func):
@wraps(func)
def wrapped_func(*args, **kwargs):
global _layer_level
# Check if the logging level is at least DEBUG (for performance reasons)
debug_output = log.getEffectiveLevel() <= logging.DEBUG
if debug_output:
# Indention for transformation layer
indention = u"\u2502 " * _layer_level
# For the input arguments, add indention to any lines after the first line
from_str = str(args[0]).replace("\n", f"\n {indention}\u2502 ")
to_str = str(args[1]).replace("\n", f"\n {indention}\u2502 ")
# Log the description and the input arguments
log.debug(f"{indention}{description}")
log.debug(f"{indention}\u251c\u2500From: {from_str}")
log.debug(f"{indention}\u251c\u2500To : {to_str}")
# Increment the layer level to increase the indention for nested transformations
_layer_level += 1
result = func(*args, **kwargs)
if debug_output:
# Decrement the layer level
_layer_level -= 1
# For the output, add intention to any lines after the first line
out_str = str(result).replace("\n", f"\n {indention} ")
# Log the output
log.debug(f"{indention}\u2514\u2500Out : {out_str}")
return result
return wrapped_func
return decorator
def _observers_are_equal(obs_1, obs_2):
# Note that this also lets pass the situation where both observers are None
if obs_1 is obs_2:
return True
# obs_1 != obs_2
if obs_1 is None:
raise ConvertError("The source observer is set to None, but the transformation requires "
"the source observer to be specified, as the destination observer "
f"is set to {obs_2}.")
if obs_2 is None:
raise ConvertError("The destination observer is set to None, but the transformation "
"requires the destination observer to be specified, as the "
f"source observer is set to {obs_1}.")
if isinstance(obs_1, str):
if obs_1 == "self":
return False
raise ConvertError("The source observer needs to have `obstime` set because the "
"destination observer is different.")
if isinstance(obs_2, str):
if obs_2 == "self":
return False
raise ConvertError("The destination observer needs to have `obstime` set because the "
"source observer is different.")
return np.atleast_1d((u.allclose(obs_1.lat, obs_2.lat) and
u.allclose(obs_1.lon, obs_2.lon) and
u.allclose(obs_1.radius, obs_2.radius) and
_times_are_equal(obs_1.obstime, obs_2.obstime))).all()
def _check_observer_defined(frame):
if frame.observer is None:
raise ConvertError("This transformation cannot be performed because the "
f"{frame.__class__.__name__} frame has observer=None.")
elif isinstance(frame.observer, str):
if frame.observer != "self":
raise ConvertError("This transformation cannot be performed because the "
f"{frame.__class__.__name__} frame needs a specified obstime "
f"to fully resolve observer='{frame.observer}'.")
elif not isinstance(frame, HeliographicCarrington):
raise ConvertError(f"The {frame.__class__.__name__} frame has observer='self' "
"but this is valid for only HeliographicCarrington frames.")
def _times_are_equal(time_1, time_2):
# Checks whether times are equal
if isinstance(time_1, Time) and isinstance(time_2, Time):
# We explicitly perform the check in TAI to avoid possible numerical precision differences
# between a time in UTC and the same time after a UTC->TAI->UTC conversion
return np.all(time_1.tai == time_2.tai)
# We also deem the times equal if they are both None
return time_1 is None and time_2 is None
# =============================================================================
# ------------------------- Transformation Framework --------------------------
# =============================================================================
def _transform_obstime(frame, obstime):
"""
Transform a frame to a new obstime using the appropriate loopback transformation.
If the new obstime is None, no transformation is performed.
If the frame's obstime is None, the frame is copied with the new obstime.
"""
# If obstime is None or the obstime matches, nothing needs to be done
if obstime is None or _times_are_equal(frame.obstime, obstime):
return frame
# Transform to the new obstime using the appropriate loopback transformation
new_frame = frame.replicate(obstime=obstime)
if frame.obstime is not None:
return frame.transform_to(new_frame)
else:
return new_frame
def _rotation_matrix_hgs_to_hgc(obstime, observer_distance_from_sun):
"""
Return the rotation matrix from HGS to HGC at the same observation time
"""
if obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
# Import here to avoid a circular import
from .sun import L0, earth_distance
# Calculate the difference in light travel time if the observer is at a different distance from
# the Sun than the Earth is
delta_time = (observer_distance_from_sun - earth_distance(obstime)) / speed_of_light
# Calculate the corresponding difference in apparent longitude
delta_lon = delta_time * constants.sidereal_rotation_rate
# Rotation is only in longitude, so only around the Z axis
return rotation_matrix(-(L0(obstime) + delta_lon), 'z')
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliographicStonyhurst, HeliographicCarrington)
@_transformation_debug("HGS->HGC")
def hgs_to_hgc(hgscoord, hgcframe):
"""
Convert from Heliographic Stonyhurst to Heliographic Carrington.
"""
_check_observer_defined(hgcframe)
if isinstance(hgcframe.observer, str) and hgcframe.observer == "self":
observer_radius = hgscoord.radius
else:
observer_radius = hgcframe.observer.radius
# First transform the HGS coord to the HGC obstime
int_coord = _transform_obstime(hgscoord, hgcframe.obstime)
# Rotate from HGS to HGC
total_matrix = _rotation_matrix_hgs_to_hgc(int_coord.obstime, observer_radius)
newrepr = int_coord.cartesian.transform(total_matrix)
return hgcframe._replicate(newrepr, obstime=int_coord.obstime)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliographicCarrington, HeliographicStonyhurst)
@_transformation_debug("HGC->HGS")
def hgc_to_hgs(hgccoord, hgsframe):
"""
Convert from Heliographic Carrington to Heliographic Stonyhurst.
"""
_check_observer_defined(hgccoord)
hgccoord = hgccoord.make_3d()
if isinstance(hgccoord.observer, str) and hgccoord.observer == "self":
observer_radius = hgccoord.radius
else:
observer_radius = hgccoord.observer.radius
# First transform the HGC coord to the HGS obstime
int_coord = _transform_obstime(hgccoord, hgsframe.obstime)
# Rotate from HGC to HGS
total_matrix = matrix_transpose(_rotation_matrix_hgs_to_hgc(int_coord.obstime,
observer_radius))
newrepr = int_coord.cartesian.transform(total_matrix)
return hgsframe._replicate(newrepr, obstime=int_coord.obstime)
def _matrix_hcc_to_hpc():
# Returns the transformation matrix that permutes/swaps axes from HCC to HPC
# HPC spherical coordinates are a left-handed frame with these equivalent Cartesian axes:
# HPC_X = -HCC_Z
# HPC_Y = HCC_X
# HPC_Z = HCC_Y
# (HPC_X and HPC_Y are not to be confused with HPC_Tx and HPC_Ty)
return np.array([[0, 0, -1],
[1, 0, 0],
[0, 1, 0]])
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
Heliocentric, Helioprojective)
@_transformation_debug("HCC->HPC")
def hcc_to_hpc(helioccoord, heliopframe):
"""
Convert from Heliocentric Cartesian to Helioprojective Cartesian.
"""
_check_observer_defined(helioccoord)
_check_observer_defined(heliopframe)
# Transform the HPC observer (in HGS) to the HPC obstime in case it's different
observer = _transform_obstime(heliopframe.observer, heliopframe.obstime)
# Loopback transform HCC coord to obstime and observer of HPC frame
int_frame = Heliocentric(obstime=observer.obstime, observer=observer)
int_coord = helioccoord.transform_to(int_frame)
# Shift the origin from the Sun to the observer
distance = int_coord.observer.radius
newrepr = int_coord.cartesian - CartesianRepresentation(0*u.m, 0*u.m, distance)
# Permute/swap axes from HCC to HPC equivalent Cartesian
newrepr = newrepr.transform(_matrix_hcc_to_hpc())
# Explicitly represent as spherical because external code (e.g., wcsaxes) expects it
return heliopframe.realize_frame(newrepr.represent_as(SphericalRepresentation))
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
Helioprojective, Heliocentric)
@_transformation_debug("HPC->HCC")
def hpc_to_hcc(heliopcoord, heliocframe):
"""
Convert from Helioprojective Cartesian to Heliocentric Cartesian.
"""
_check_observer_defined(heliopcoord)
_check_observer_defined(heliocframe)
heliopcoord = heliopcoord.make_3d()
# Permute/swap axes from HPC equivalent Cartesian to HCC
newrepr = heliopcoord.cartesian.transform(matrix_transpose(_matrix_hcc_to_hpc()))
# Transform the HPC observer (in HGS) to the HPC obstime in case it's different
observer = _transform_obstime(heliopcoord.observer, heliopcoord.obstime)
# Shift the origin from the observer to the Sun
distance = observer.radius
newrepr += CartesianRepresentation(0*u.m, 0*u.m, distance)
# Complete the conversion of HPC to HCC at the obstime and observer of the HPC coord
int_coord = Heliocentric(newrepr, obstime=observer.obstime, observer=observer)
# Loopback transform HCC as needed
return int_coord.transform_to(heliocframe)
def _rotation_matrix_hcc_to_hgs(longitude, latitude):
# Returns the rotation matrix from HCC to HGS based on the observer longitude and latitude
# Permute the axes of HCC to match HGS Cartesian equivalent
# HGS_X = HCC_Z
# HGS_Y = HCC_X
# HGS_Z = HCC_Y
axes_matrix = np.array([[0, 0, 1],
[1, 0, 0],
[0, 1, 0]])
# Rotate in latitude and longitude (sign difference because of direction difference)
lat_matrix = rotation_matrix(latitude, 'y')
lon_matrix = rotation_matrix(-longitude, 'z')
return lon_matrix @ lat_matrix @ axes_matrix
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
Heliocentric, HeliographicStonyhurst)
@_transformation_debug("HCC->HGS")
def hcc_to_hgs(helioccoord, heliogframe):
"""
Convert from Heliocentric Cartesian to Heliographic Stonyhurst.
"""
_check_observer_defined(helioccoord)
# Transform the HCC observer (in HGS) to the HCC obstime in case it's different
hcc_observer_at_hcc_obstime = _transform_obstime(helioccoord.observer, helioccoord.obstime)
total_matrix = _rotation_matrix_hcc_to_hgs(hcc_observer_at_hcc_obstime.lon,
hcc_observer_at_hcc_obstime.lat)
# Transform from HCC to HGS at the HCC obstime
newrepr = helioccoord.cartesian.transform(total_matrix)
int_coord = HeliographicStonyhurst(newrepr, obstime=hcc_observer_at_hcc_obstime.obstime)
# For historical reasons, we support HCC with no obstime transforming to HGS with an obstime
if int_coord.obstime is None and heliogframe.obstime is not None:
int_coord = int_coord.replicate(obstime=heliogframe.obstime)
# Loopback transform HGS as needed
return int_coord.transform_to(heliogframe)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliographicStonyhurst, Heliocentric)
@_transformation_debug("HGS->HCC")
def hgs_to_hcc(heliogcoord, heliocframe):
"""
Convert from Heliographic Stonyhurst to Heliocentric Cartesian.
"""
_check_observer_defined(heliocframe)
heliogcoord = heliogcoord.make_3d()
# Loopback transform HGS if there is a change in obstime
int_coord = _transform_obstime(heliogcoord, heliocframe.obstime)
# Transform the HCC observer (in HGS) to the HCC obstime in case it's different
hcc_observer_at_hcc_obstime = _transform_obstime(heliocframe.observer, int_coord.obstime)
total_matrix = matrix_transpose(_rotation_matrix_hcc_to_hgs(hcc_observer_at_hcc_obstime.lon,
hcc_observer_at_hcc_obstime.lat))
# Transform from HGS to HCC at the same obstime
newrepr = int_coord.cartesian.transform(total_matrix)
return heliocframe.realize_frame(newrepr)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
Helioprojective, Helioprojective)
@_transformation_debug("HPC->HPC")
def hpc_to_hpc(from_coo, to_frame):
"""
This converts from HPC to HPC, with different observer location parameters.
It does this by transforming through HGS.
"""
if _observers_are_equal(from_coo.observer, to_frame.observer) and \
_times_are_equal(from_coo.obstime, to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
_check_observer_defined(from_coo)
_check_observer_defined(to_frame)
hgs = from_coo.transform_to(HeliographicStonyhurst(obstime=to_frame.obstime))
hpc = hgs.transform_to(to_frame)
return hpc
def _rotation_matrix_reprs_to_reprs(start_representation, end_representation):
"""
Return the matrix for the direct rotation from one representation to a second representation.
The representations need not be normalized first, and can be arrays of representations.
"""
A = start_representation.to_cartesian()
B = end_representation.to_cartesian()
rotation_axis = A.cross(B)
rotation_angle = -np.arccos(A.dot(B) / (A.norm() * B.norm())) # negation is required
if rotation_angle.isscalar:
# This line works around some input/output quirks of Astropy's rotation_matrix()
matrix = np.array(rotation_matrix(rotation_angle, rotation_axis.xyz.value.tolist()))
else:
matrix_list = [np.array(rotation_matrix(angle, axis.xyz.value.tolist()))
for angle, axis in zip(rotation_angle, rotation_axis)]
matrix = np.stack(matrix_list)
return matrix
def _rotation_matrix_reprs_to_xz_about_z(representations):
"""
Return one or more matrices for rotating one or more representations around the Z axis into the
XZ plane.
"""
A = representations.to_cartesian()
# Zero out the Z components
# (The additional transpose operations are to handle both scalar and array inputs)
A_no_z = CartesianRepresentation((A.xyz.T * [1, 1, 0]).T)
# Rotate the resulting vector to the X axis
x_axis = CartesianRepresentation(1, 0, 0)
matrix = _rotation_matrix_reprs_to_reprs(A_no_z, x_axis)
return matrix
def _sun_earth_icrf(time):
"""
Return the Sun-Earth vector for ICRF-based frames.
"""
sun_pos_icrs = get_body_barycentric('sun', time)
earth_pos_icrs = get_body_barycentric('earth', time)
return earth_pos_icrs - sun_pos_icrs
# The Sun's north pole is oriented RA=286.13 deg, dec=63.87 deg in ICRS, and thus HCRS as well
# (See Archinal et al. 2011,
# "Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2009")
# The orientation of the north pole in ICRS/HCRS is assumed to be constant in time
_SOLAR_NORTH_POLE_HCRS = UnitSphericalRepresentation(lon=constants.get('alpha_0'),
lat=constants.get('delta_0'))
# Calculate the rotation matrix to de-tilt the Sun's rotation axis to be parallel to the Z axis
_SUN_DETILT_MATRIX = _rotation_matrix_reprs_to_reprs(_SOLAR_NORTH_POLE_HCRS,
CartesianRepresentation(0, 0, 1))
def _affine_params_hcrs_to_hgs(hcrs_time, hgs_time):
"""
Return the affine parameters (matrix and offset) from HCRS to HGS
HGS shares the same origin (the Sun) as HCRS, but has its Z axis aligned with the Sun's
rotation axis and its X axis aligned with the projection of the Sun-Earth vector onto the Sun's
equatorial plane (i.e., the component of the Sun-Earth vector perpendicular to the Z axis).
Thus, the transformation matrix is the product of the matrix to align the Z axis (by de-tilting
the Sun's rotation axis) and the matrix to align the X axis. The first matrix is independent
of time and is pre-computed, while the second matrix depends on the time-varying Sun-Earth
vector.
"""
# Determine the Sun-Earth vector in ICRS
# Since HCRS is ICRS with an origin shift, this is also the Sun-Earth vector in HCRS
sun_pos_icrs = get_body_barycentric('sun', hgs_time)
earth_pos_icrs = get_body_barycentric('earth', hgs_time)
sun_earth = earth_pos_icrs - sun_pos_icrs
# De-tilt the Sun-Earth vector to the frame with the Sun's rotation axis parallel to the Z axis
sun_earth_detilt = sun_earth.transform(_SUN_DETILT_MATRIX)
# Rotate the Sun-Earth vector about the Z axis so that it lies in the XZ plane
rot_matrix = _rotation_matrix_reprs_to_xz_about_z(sun_earth_detilt)
total_matrix = rot_matrix @ _SUN_DETILT_MATRIX
# All of the above is calculated for the HGS observation time
# If the HCRS observation time is different, calculate the translation in origin
if not _ignore_sun_motion and np.any(hcrs_time != hgs_time):
sun_pos_old_icrs = get_body_barycentric('sun', hcrs_time)
offset_icrf = sun_pos_old_icrs - sun_pos_icrs
else:
offset_icrf = sun_pos_icrs * 0 # preserves obstime shape
offset = offset_icrf.transform(total_matrix)
return total_matrix, offset
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HCRS, HeliographicStonyhurst)
@_transformation_debug("HCRS->HGS")
def hcrs_to_hgs(hcrscoord, hgsframe):
"""
Convert from HCRS to Heliographic Stonyhurst (HGS).
Even though we calculate the parameters for the affine transform, we use
``FunctionTransformWithFiniteDifference`` because otherwise there is no way to account for the
induced angular velocity when transforming a coordinate with velocity information.
"""
if hgsframe.obstime is None:
raise ConvertError("To perform this transformation, the HeliographicStonyhurst"
" frame needs a specified `obstime`.")
rot_matrix, offset = _affine_params_hcrs_to_hgs(hcrscoord.obstime, hgsframe.obstime)
return hgsframe.realize_frame(hcrscoord.cartesian.transform(rot_matrix) + offset)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliographicStonyhurst, HCRS)
@_transformation_debug("HGS->HCRS")
def hgs_to_hcrs(hgscoord, hcrsframe):
"""
Convert from Heliographic Stonyhurst to HCRS.
Even though we calculate the parameters for the affine transform, we use
``FunctionTransformWithFiniteDifference`` because otherwise there is no way to account for the
induced angular velocity when transforming a coordinate with velocity information.
"""
if hgscoord.obstime is None:
raise ConvertError("To perform this transformation, the HeliographicStonyhurst"
" frame needs a specified `obstime`.")
hgscoord = hgscoord.make_3d()
# Calculate the matrix and offset in the HCRS->HGS direction
forward_matrix, forward_offset = _affine_params_hcrs_to_hgs(hcrsframe.obstime, hgscoord.obstime)
# Invert the transformation to get the HGS->HCRS transformation
reverse_matrix = matrix_transpose(forward_matrix)
reverse_offset = (-forward_offset).transform(reverse_matrix)
return hcrsframe.realize_frame(hgscoord.cartesian.transform(reverse_matrix) + reverse_offset)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliographicStonyhurst, HeliographicStonyhurst)
@_transformation_debug("HGS->HGS")
def hgs_to_hgs(from_coo, to_frame):
"""
Convert between two Heliographic Stonyhurst frames.
"""
if to_frame.obstime is None:
return from_coo.replicate()
elif _times_are_equal(from_coo.obstime, to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
else:
if _autoapply_diffrot:
from_coo = from_coo._apply_diffrot((to_frame.obstime - from_coo.obstime).to('day'),
_autoapply_diffrot)
return from_coo.transform_to(HCRS(obstime=to_frame.obstime)).transform_to(to_frame)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliographicCarrington, HeliographicCarrington)
@_transformation_debug("HGC->HGC")
def hgc_to_hgc(from_coo, to_frame):
"""
Convert between two Heliographic Carrington frames.
"""
if _observers_are_equal(from_coo.observer, to_frame.observer) and \
_times_are_equal(from_coo.obstime, to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
_check_observer_defined(from_coo)
_check_observer_defined(to_frame)
# Convert through HGS
hgscoord = from_coo.transform_to(HeliographicStonyhurst(obstime=from_coo.obstime))
return hgscoord.transform_to(to_frame)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
Heliocentric, Heliocentric)
@_transformation_debug("HCC->HCC")
def hcc_to_hcc(from_coo, to_frame):
"""
Convert between two Heliocentric frames.
"""
if _observers_are_equal(from_coo.observer, to_frame.observer) and \
_times_are_equal(from_coo.obstime, to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
_check_observer_defined(from_coo)
_check_observer_defined(to_frame)
# Convert through HGS
hgscoord = from_coo.transform_to(HeliographicStonyhurst(obstime=to_frame.obstime))
return hgscoord.transform_to(to_frame)
def _rotation_matrix_hme_to_hee(hmeframe):
"""
Return the rotation matrix from HME to HEE at the same observation time
"""
# Get the Sun-Earth vector
sun_earth = HCRS(_sun_earth_icrf(hmeframe.obstime), obstime=hmeframe.obstime)
sun_earth_hme = sun_earth.transform_to(hmeframe).cartesian
# Rotate the Sun-Earth vector about the Z axis so that it lies in the XZ plane
rot_matrix = _rotation_matrix_reprs_to_xz_about_z(sun_earth_hme)
# Tilt the rotated Sun-Earth vector so that it is aligned with the X axis
tilt_matrix = _rotation_matrix_reprs_to_reprs(sun_earth_hme.transform(rot_matrix),
CartesianRepresentation(1, 0, 0))
return matrix_product(tilt_matrix, rot_matrix)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliocentricMeanEcliptic, HeliocentricEarthEcliptic)
@_transformation_debug("HME->HEE")
def hme_to_hee(hmecoord, heeframe):
"""
Convert from Heliocentric Mean Ecliptic to Heliocentric Earth Ecliptic
"""
if heeframe.obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
# Convert to the HME frame with mean equinox of date at the HEE obstime, through HCRS
int_frame = HeliocentricMeanEcliptic(obstime=heeframe.obstime, equinox=heeframe.obstime)
int_coord = hmecoord.transform_to(HCRS(obstime=hmecoord.obstime)).transform_to(int_frame)
# Rotate the intermediate coord to the HEE frame
total_matrix = _rotation_matrix_hme_to_hee(int_frame)
newrepr = int_coord.cartesian.transform(total_matrix)
return heeframe.realize_frame(newrepr)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliocentricEarthEcliptic, HeliocentricMeanEcliptic)
@_transformation_debug("HEE->HME")
def hee_to_hme(heecoord, hmeframe):
"""
Convert from Heliocentric Earth Ecliptic to Heliocentric Mean Ecliptic
"""
if heecoord.obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
int_frame = HeliocentricMeanEcliptic(obstime=heecoord.obstime, equinox=heecoord.obstime)
# Rotate the HEE coord to the intermediate frame
total_matrix = matrix_transpose(_rotation_matrix_hme_to_hee(int_frame))
int_repr = heecoord.cartesian.transform(total_matrix)
int_coord = int_frame.realize_frame(int_repr)
# Convert to the HME frame through HCRS
return int_coord.transform_to(HCRS(obstime=int_coord.obstime)).transform_to(hmeframe)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliocentricEarthEcliptic, HeliocentricEarthEcliptic)
@_transformation_debug("HEE->HEE")
def hee_to_hee(from_coo, to_frame):
"""
Convert between two Heliocentric Earth Ecliptic frames.
"""
if _times_are_equal(from_coo.obstime, to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
elif to_frame.obstime is None:
return from_coo
else:
return from_coo.transform_to(HCRS(obstime=from_coo.obstime)).transform_to(to_frame)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliocentricEarthEcliptic, GeocentricSolarEcliptic)
@_transformation_debug("HEE->GSE")
def hee_to_gse(heecoord, gseframe):
"""
Convert from Heliocentric Earth Ecliptic to Geocentric Solar Ecliptic
"""
# First transform the HEE coord to the GSE obstime
int_coord = _transform_obstime(heecoord, gseframe.obstime)
if int_coord.obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
# Import here to avoid a circular import
from .sun import earth_distance
# Find the Earth-object vector in the intermediate frame
sun_earth_int = earth_distance(int_coord.obstime) * CartesianRepresentation(1, 0, 0)
earth_object_int = int_coord.cartesian - sun_earth_int
# Flip the vector in X and Y, but leave Z untouched
# (The additional transpose operations are to handle both scalar and array inputs)
newrepr = CartesianRepresentation((earth_object_int.xyz.T * [-1, -1, 1]).T)
return gseframe._replicate(newrepr, obstime=int_coord.obstime)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
GeocentricSolarEcliptic, HeliocentricEarthEcliptic)
@_transformation_debug("GSE->HEE")
def gse_to_hee(gsecoord, heeframe):
"""
Convert from Geocentric Solar Ecliptic to Heliocentric Earth Ecliptic
"""
# First transform the GSE coord to the HEE obstime
int_coord = _transform_obstime(gsecoord, heeframe.obstime)
if int_coord.obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
# Import here to avoid a circular import
from .sun import earth_distance
# Find the Sun-object vector in the intermediate frame
earth_sun_int = earth_distance(int_coord.obstime) * CartesianRepresentation(1, 0, 0)
sun_object_int = int_coord.cartesian - earth_sun_int
# Flip the vector in X and Y, but leave Z untouched
# (The additional transpose operations are to handle both scalar and array inputs)
newrepr = CartesianRepresentation((sun_object_int.xyz.T * [-1, -1, 1]).T)
return heeframe._replicate(newrepr, obstime=int_coord.obstime)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
GeocentricSolarEcliptic, GeocentricSolarEcliptic)
@_transformation_debug("GSE->GSE")
def gse_to_gse(from_coo, to_frame):
"""
Convert between two Geocentric Solar Ecliptic frames.
"""
if _times_are_equal(from_coo.obstime, to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
else:
heecoord = from_coo.transform_to(HeliocentricEarthEcliptic(obstime=from_coo.obstime))
return heecoord.transform_to(to_frame)
def _rotation_matrix_hgs_to_hci(obstime):
"""
Return the rotation matrix from HGS to HCI at the same observation time
"""
z_axis = CartesianRepresentation(0, 0, 1)*u.m
if not obstime.isscalar:
z_axis = z_axis._apply('repeat', obstime.size)
# Get the ecliptic pole in HGS
ecliptic_pole = HeliocentricMeanEcliptic(z_axis, obstime=obstime, equinox=_J2000)
ecliptic_pole_hgs = ecliptic_pole.transform_to(HeliographicStonyhurst(obstime=obstime))
# Rotate the ecliptic pole to the -YZ plane, which aligns the solar ascending node with the X
# axis
rot_matrix = _rotation_matrix_reprs_to_xz_about_z(ecliptic_pole_hgs.cartesian)
xz_to_yz_matrix = rotation_matrix(-90*u.deg, 'z')
return xz_to_yz_matrix @ rot_matrix
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliographicStonyhurst, HeliocentricInertial)
@_transformation_debug("HGS->HCI")
def hgs_to_hci(hgscoord, hciframe):
"""
Convert from Heliographic Stonyhurst to Heliocentric Inertial
"""
hgscoord = hgscoord.make_3d()
# First transform the HGS coord to the HCI obstime
int_coord = _transform_obstime(hgscoord, hciframe.obstime)
if int_coord.obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
# Rotate from HGS to HCI
total_matrix = _rotation_matrix_hgs_to_hci(int_coord.obstime)
newrepr = int_coord.cartesian.transform(total_matrix)
return hciframe._replicate(newrepr, obstime=int_coord.obstime)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliocentricInertial, HeliographicStonyhurst)
@_transformation_debug("HCI->HGS")
def hci_to_hgs(hcicoord, hgsframe):
"""
Convert from Heliocentric Inertial to Heliographic Stonyhurst
"""
# First transform the HCI coord to the HGS obstime
int_coord = _transform_obstime(hcicoord, hgsframe.obstime)
if int_coord.obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
# Rotate from HCI to HGS
total_matrix = matrix_transpose(_rotation_matrix_hgs_to_hci(int_coord.obstime))
newrepr = int_coord.cartesian.transform(total_matrix)
return hgsframe._replicate(newrepr, obstime=int_coord.obstime)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliocentricInertial, HeliocentricInertial)
@_transformation_debug("HCI->HCI")
def hci_to_hci(from_coo, to_frame):
"""
Convert between two Heliocentric Inertial frames.
"""
if _times_are_equal(from_coo.obstime, to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
else:
return from_coo.transform_to(HeliographicStonyhurst(obstime=from_coo.obstime)).\
transform_to(to_frame)
def _rotation_matrix_obliquity(time):
"""
Return the rotation matrix from Earth equatorial to ecliptic coordinates
"""
return rotation_matrix(erfa.obl06(*get_jd12(time, 'tt'))*u.radian, 'x')
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
HeliocentricMeanEcliptic, GeocentricEarthEquatorial)
@_transformation_debug("HME->GEI")
def hme_to_gei(hmecoord, geiframe):
"""
Convert from Heliocentric Mean Ecliptic to Geocentric Earth Equatorial
"""
if geiframe.obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
# Use an intermediate frame of HME at the GEI observation time, through HCRS
int_frame = HeliocentricMeanEcliptic(obstime=geiframe.obstime, equinox=geiframe.equinox)
int_coord = hmecoord.transform_to(HCRS(obstime=int_frame.obstime)).transform_to(int_frame)
# Get the Sun-Earth vector in the intermediate frame
sun_earth = HCRS(_sun_earth_icrf(int_frame.obstime), obstime=int_frame.obstime)
sun_earth_int = sun_earth.transform_to(int_frame).cartesian
# Find the Earth-object vector in the intermediate frame
earth_object_int = int_coord.cartesian - sun_earth_int
# Rotate from ecliptic to Earth equatorial
rot_matrix = matrix_transpose(_rotation_matrix_obliquity(int_frame.equinox))
newrepr = earth_object_int.transform(rot_matrix)
return geiframe.realize_frame(newrepr)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
GeocentricEarthEquatorial, HeliocentricMeanEcliptic)
@_transformation_debug("GEI->HME")
def gei_to_hme(geicoord, hmeframe):
"""
Convert from Geocentric Earth Equatorial to Heliocentric Mean Ecliptic
"""
if geicoord.obstime is None:
raise ConvertError("To perform this transformation, the coordinate"
" frame needs a specified `obstime`.")
# Use an intermediate frame of HME at the GEI observation time
int_frame = HeliocentricMeanEcliptic(obstime=geicoord.obstime, equinox=geicoord.equinox)
# Get the Sun-Earth vector in the intermediate frame
sun_earth = HCRS(_sun_earth_icrf(int_frame.obstime), obstime=int_frame.obstime)
sun_earth_int = sun_earth.transform_to(int_frame).cartesian
# Rotate from Earth equatorial to ecliptic
rot_matrix = _rotation_matrix_obliquity(int_frame.equinox)
earth_object_int = geicoord.cartesian.transform(rot_matrix)
# Find the Sun-object vector in the intermediate frame
sun_object_int = sun_earth_int + earth_object_int
int_coord = int_frame.realize_frame(sun_object_int)
# Convert to the final frame through HCRS
return int_coord.transform_to(HCRS(obstime=int_coord.obstime)).transform_to(hmeframe)
@frame_transform_graph.transform(FunctionTransformWithFiniteDifference,
GeocentricEarthEquatorial, GeocentricEarthEquatorial)
@_transformation_debug("GEI->GEI")
def gei_to_gei(from_coo, to_frame):
"""
Convert between two Geocentric Earth Equatorial frames.
"""
if _times_are_equal(from_coo.equinox, to_frame.equinox) and \
_times_are_equal(from_coo.obstime, to_frame.obstime):
return to_frame.realize_frame(from_coo.data)
else:
return from_coo.transform_to(HCRS(obstime=from_coo.obstime)).transform_to(to_frame)
def _make_sunpy_graph():
"""
Culls down the full transformation graph for SunPy purposes and returns the string version
"""
# Frames to keep in the transformation graph
keep_list = ['icrs', 'hcrs', 'heliocentrictrueecliptic', 'heliocentricmeanecliptic',
'heliographic_stonyhurst', 'heliographic_carrington',
'heliocentric', 'helioprojective',
'heliocentricearthecliptic', 'geocentricsolarecliptic',
'heliocentricinertial', 'geocentricearthequatorial',
'gcrs', 'precessedgeocentric', 'geocentrictrueecliptic', 'geocentricmeanecliptic',
'cirs', 'altaz', 'itrs']
small_graph = deepcopy(frame_transform_graph)
cull_list = [name for name in small_graph.get_names() if name not in keep_list]
cull_frames = [small_graph.lookup_name(name) for name in cull_list]
for frame in cull_frames:
# Remove the part of the graph where the unwanted frame is the source frame
if frame in small_graph._graph:
del small_graph._graph[frame]
# Remove all instances of the unwanted frame as the destination frame
for entry in small_graph._graph:
if frame in small_graph._graph[entry]:
del (small_graph._graph[entry])[frame]
# Clean up the node list
for name in cull_list:
small_graph._cached_names.pop(name)
_add_astropy_node(small_graph)
docstr = make_transform_graph_docs(small_graph)
# Make adjustments to the graph
docstr = _tweak_graph(docstr)
return docstr
def _add_astropy_node(graph):
"""
Add an 'Astropy' node that links to an ICRS node in the graph
"""
class Astropy(BaseCoordinateFrame):
name = "REPLACE"
@graph.transform(FunctionTransform, Astropy, ICRS)
def fake_transform1():
pass
@graph.transform(FunctionTransform, ICRS, Astropy)
def fake_transform2():
pass
def _tweak_graph(docstr):
# Remove Astropy's diagram description
output = docstr[docstr.find('.. Wrap the graph'):]
# Change the Astropy node
output = output.replace('Astropy [shape=oval label="Astropy\\n`REPLACE`"]',
'Astropy [shape=box3d style=filled fillcolor=lightcyan '
'label="Other frames\\nin Astropy"]')
# Change the Astropy<->ICRS links to black
output = output.replace('ICRS -> Astropy[ color = "#783001" ]',
'ICRS -> Astropy[ color = "#000000" ]')
output = output.replace('Astropy -> ICRS[ color = "#783001" ]',
'Astropy -> ICRS[ color = "#000000" ]')
# Set the nodes to be filled and cyan by default
output = output.replace('AstropyCoordinateTransformGraph {',
'AstropyCoordinateTransformGraph {\n'
' node [style=filled fillcolor=lightcyan]')
# Set the nodes for SunPy frames to be white
sunpy_frames = ['HeliographicStonyhurst', 'HeliographicCarrington',
'Heliocentric', 'Helioprojective',
'HeliocentricEarthEcliptic', 'GeocentricSolarEcliptic',
'HeliocentricInertial', 'GeocentricEarthEquatorial']
for frame in sunpy_frames:
output = output.replace(frame + ' [', frame + ' [fillcolor=white ')
# Set the rank direction to be left->right (as opposed to top->bottom)
# Force nodes for ICRS, HCRS, and "Other frames in Astropy" to be at the same rank
output = output.replace(' overlap=false',
' overlap=false\n'
' rankdir=LR\n'
' {rank=same; ICRS; HCRS; Astropy}')
output = output.replace('<ul>\n\n',
'<ul>\n\n' +
_add_legend_row('SunPy frames', 'white') +
_add_legend_row('Astropy frames', 'lightcyan'))
return output
def _add_legend_row(label, color):
row = ' <li style="list-style: none;">\n'\
' <p style="font-size: 12px;line-height: 24px;font-weight: normal;'\
'color: #848484;padding: 0;margin: 0;">\n'\
' <b>' + label + ':</b>\n'\
' <span class="dot" style="height: 20px;width: 40px;'\
'background-color: ' + color + ';border-radius: 50%;border: 1px solid black;'\
'display: inline-block;"></span>\n'\
' </p>\n'\
' </li>\n\n\n'
return row
|
[
"astropy.coordinates.ConvertError",
"astropy.coordinates.matrix_utilities.matrix_product",
"sunpy.sun.constants.get",
"astropy.coordinates.HeliocentricMeanEcliptic",
"astropy.units.allclose",
"astropy.coordinates.representation.CartesianRepresentation",
"astropy.coordinates.HCRS",
"astropy.coordinates.get_body_barycentric",
"numpy.stack",
"copy.deepcopy",
"astropy.coordinates.builtin_frames.make_transform_graph_docs",
"sunpy.log.debug",
"astropy.coordinates.builtin_frames.utils.get_jd12",
"functools.wraps",
"sunpy.log.getEffectiveLevel",
"numpy.all",
"astropy.coordinates.baseframe.frame_transform_graph.transform",
"astropy.coordinates.matrix_utilities.matrix_transpose",
"numpy.any",
"astropy.coordinates.matrix_utilities.rotation_matrix",
"numpy.array"
] |
[((15927, 16049), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliographicStonyhurst', 'HeliographicCarrington'], {}), '(FunctionTransformWithFiniteDifference,\n HeliographicStonyhurst, HeliographicCarrington)\n', (15958, 16049), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((16812, 16934), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliographicCarrington', 'HeliographicStonyhurst'], {}), '(FunctionTransformWithFiniteDifference,\n HeliographicCarrington, HeliographicStonyhurst)\n', (16843, 16934), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((18254, 18359), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'Heliocentric', 'Helioprojective'], {}), '(FunctionTransformWithFiniteDifference,\n Heliocentric, Helioprojective)\n', (18285, 18359), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((19466, 19571), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'Helioprojective', 'Heliocentric'], {}), '(FunctionTransformWithFiniteDifference,\n Helioprojective, Heliocentric)\n', (19497, 19571), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((21245, 21357), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'Heliocentric', 'HeliographicStonyhurst'], {}), '(FunctionTransformWithFiniteDifference,\n Heliocentric, HeliographicStonyhurst)\n', (21276, 21357), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((22463, 22575), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliographicStonyhurst', 'Heliocentric'], {}), '(FunctionTransformWithFiniteDifference,\n HeliographicStonyhurst, Heliocentric)\n', (22494, 22575), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((23514, 23622), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'Helioprojective', 'Helioprojective'], {}), '(FunctionTransformWithFiniteDifference,\n Helioprojective, Helioprojective)\n', (23545, 23622), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((28675, 28779), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HCRS', 'HeliographicStonyhurst'], {}), '(FunctionTransformWithFiniteDifference, HCRS,\n HeliographicStonyhurst)\n', (28706, 28779), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((29586, 29690), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliographicStonyhurst', 'HCRS'], {}), '(FunctionTransformWithFiniteDifference,\n HeliographicStonyhurst, HCRS)\n', (29617, 29690), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((30803, 30925), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliographicStonyhurst', 'HeliographicStonyhurst'], {}), '(FunctionTransformWithFiniteDifference,\n HeliographicStonyhurst, HeliographicStonyhurst)\n', (30834, 30925), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((31582, 31704), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliographicCarrington', 'HeliographicCarrington'], {}), '(FunctionTransformWithFiniteDifference,\n HeliographicCarrington, HeliographicCarrington)\n', (31613, 31704), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((32301, 32403), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'Heliocentric', 'Heliocentric'], {}), '(FunctionTransformWithFiniteDifference,\n Heliocentric, Heliocentric)\n', (32332, 32403), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((33757, 33884), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliocentricMeanEcliptic', 'HeliocentricEarthEcliptic'], {}), '(FunctionTransformWithFiniteDifference,\n HeliocentricMeanEcliptic, HeliocentricEarthEcliptic)\n', (33788, 33884), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((34746, 34873), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliocentricEarthEcliptic', 'HeliocentricMeanEcliptic'], {}), '(FunctionTransformWithFiniteDifference,\n HeliocentricEarthEcliptic, HeliocentricMeanEcliptic)\n', (34777, 34873), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((35710, 35838), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliocentricEarthEcliptic', 'HeliocentricEarthEcliptic'], {}), '(FunctionTransformWithFiniteDifference,\n HeliocentricEarthEcliptic, HeliocentricEarthEcliptic)\n', (35741, 35838), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((36293, 36419), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliocentricEarthEcliptic', 'GeocentricSolarEcliptic'], {}), '(FunctionTransformWithFiniteDifference,\n HeliocentricEarthEcliptic, GeocentricSolarEcliptic)\n', (36324, 36419), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((37492, 37618), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'GeocentricSolarEcliptic', 'HeliocentricEarthEcliptic'], {}), '(FunctionTransformWithFiniteDifference,\n GeocentricSolarEcliptic, HeliocentricEarthEcliptic)\n', (37523, 37618), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((38685, 38809), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'GeocentricSolarEcliptic', 'GeocentricSolarEcliptic'], {}), '(FunctionTransformWithFiniteDifference,\n GeocentricSolarEcliptic, GeocentricSolarEcliptic)\n', (38716, 38809), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((40024, 40144), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliographicStonyhurst', 'HeliocentricInertial'], {}), '(FunctionTransformWithFiniteDifference,\n HeliographicStonyhurst, HeliocentricInertial)\n', (40055, 40144), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((40883, 41003), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliocentricInertial', 'HeliographicStonyhurst'], {}), '(FunctionTransformWithFiniteDifference,\n HeliocentricInertial, HeliographicStonyhurst)\n', (40914, 41003), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((41724, 41842), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliocentricInertial', 'HeliocentricInertial'], {}), '(FunctionTransformWithFiniteDifference,\n HeliocentricInertial, HeliocentricInertial)\n', (41755, 41842), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((42473, 42600), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'HeliocentricMeanEcliptic', 'GeocentricEarthEquatorial'], {}), '(FunctionTransformWithFiniteDifference,\n HeliocentricMeanEcliptic, GeocentricEarthEquatorial)\n', (42504, 42600), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((43793, 43920), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'GeocentricEarthEquatorial', 'HeliocentricMeanEcliptic'], {}), '(FunctionTransformWithFiniteDifference,\n GeocentricEarthEquatorial, HeliocentricMeanEcliptic)\n', (43824, 43920), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((45139, 45267), 'astropy.coordinates.baseframe.frame_transform_graph.transform', 'frame_transform_graph.transform', (['FunctionTransformWithFiniteDifference', 'GeocentricEarthEquatorial', 'GeocentricEarthEquatorial'], {}), '(FunctionTransformWithFiniteDifference,\n GeocentricEarthEquatorial, GeocentricEarthEquatorial)\n', (45170, 45267), False, 'from astropy.coordinates.baseframe import frame_transform_graph\n'), ((18164, 18208), 'numpy.array', 'np.array', (['[[0, 0, -1], [1, 0, 0], [0, 1, 0]]'], {}), '([[0, 0, -1], [1, 0, 0], [0, 1, 0]])\n', (18172, 18208), True, 'import numpy as np\n'), ((20296, 20347), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(0 * u.m)', '(0 * u.m)', 'distance'], {}), '(0 * u.m, 0 * u.m, distance)\n', (20319, 20347), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((20904, 20947), 'numpy.array', 'np.array', (['[[0, 0, 1], [1, 0, 0], [0, 1, 0]]'], {}), '([[0, 0, 1], [1, 0, 0], [0, 1, 0]])\n', (20912, 20947), True, 'import numpy as np\n'), ((21111, 21141), 'astropy.coordinates.matrix_utilities.rotation_matrix', 'rotation_matrix', (['latitude', '"""y"""'], {}), "(latitude, 'y')\n", (21126, 21141), False, 'from astropy.coordinates.matrix_utilities import matrix_product, matrix_transpose, rotation_matrix\n'), ((21159, 21191), 'astropy.coordinates.matrix_utilities.rotation_matrix', 'rotation_matrix', (['(-longitude)', '"""z"""'], {}), "(-longitude, 'z')\n", (21174, 21191), False, 'from astropy.coordinates.matrix_utilities import matrix_product, matrix_transpose, rotation_matrix\n'), ((25563, 25611), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(A.xyz.T * [1, 1, 0]).T'], {}), '((A.xyz.T * [1, 1, 0]).T)\n', (25586, 25611), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((25674, 25706), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(1)', '(0)', '(0)'], {}), '(1, 0, 0)\n', (25697, 25706), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((25906, 25939), 'astropy.coordinates.get_body_barycentric', 'get_body_barycentric', (['"""sun"""', 'time'], {}), "('sun', time)\n", (25926, 25939), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((25961, 25996), 'astropy.coordinates.get_body_barycentric', 'get_body_barycentric', (['"""earth"""', 'time'], {}), "('earth', time)\n", (25981, 25996), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((26738, 26770), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(0)', '(0)', '(1)'], {}), '(0, 0, 1)\n', (26761, 26770), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((27660, 27697), 'astropy.coordinates.get_body_barycentric', 'get_body_barycentric', (['"""sun"""', 'hgs_time'], {}), "('sun', hgs_time)\n", (27680, 27697), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((27719, 27758), 'astropy.coordinates.get_body_barycentric', 'get_body_barycentric', (['"""earth"""', 'hgs_time'], {}), "('earth', hgs_time)\n", (27739, 27758), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((30603, 30635), 'astropy.coordinates.matrix_utilities.matrix_transpose', 'matrix_transpose', (['forward_matrix'], {}), '(forward_matrix)\n', (30619, 30635), False, 'from astropy.coordinates.matrix_utilities import matrix_product, matrix_transpose, rotation_matrix\n'), ((33714, 33753), 'astropy.coordinates.matrix_utilities.matrix_product', 'matrix_product', (['tilt_matrix', 'rot_matrix'], {}), '(tilt_matrix, rot_matrix)\n', (33728, 33753), False, 'from astropy.coordinates.matrix_utilities import matrix_product, matrix_transpose, rotation_matrix\n'), ((34358, 34434), 'astropy.coordinates.HeliocentricMeanEcliptic', 'HeliocentricMeanEcliptic', ([], {'obstime': 'heeframe.obstime', 'equinox': 'heeframe.obstime'}), '(obstime=heeframe.obstime, equinox=heeframe.obstime)\n', (34382, 34434), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((35257, 35333), 'astropy.coordinates.HeliocentricMeanEcliptic', 'HeliocentricMeanEcliptic', ([], {'obstime': 'heecoord.obstime', 'equinox': 'heecoord.obstime'}), '(obstime=heecoord.obstime, equinox=heecoord.obstime)\n', (35281, 35333), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((37355, 37420), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(earth_object_int.xyz.T * [-1, -1, 1]).T'], {}), '((earth_object_int.xyz.T * [-1, -1, 1]).T)\n', (37378, 37420), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((38550, 38613), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(sun_object_int.xyz.T * [-1, -1, 1]).T'], {}), '((sun_object_int.xyz.T * [-1, -1, 1]).T)\n', (38573, 38613), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((39575, 39640), 'astropy.coordinates.HeliocentricMeanEcliptic', 'HeliocentricMeanEcliptic', (['z_axis'], {'obstime': 'obstime', 'equinox': '_J2000'}), '(z_axis, obstime=obstime, equinox=_J2000)\n', (39599, 39640), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((39948, 39981), 'astropy.coordinates.matrix_utilities.rotation_matrix', 'rotation_matrix', (['(-90 * u.deg)', '"""z"""'], {}), "(-90 * u.deg, 'z')\n", (39963, 39981), False, 'from astropy.coordinates.matrix_utilities import matrix_product, matrix_transpose, rotation_matrix\n'), ((43065, 43141), 'astropy.coordinates.HeliocentricMeanEcliptic', 'HeliocentricMeanEcliptic', ([], {'obstime': 'geiframe.obstime', 'equinox': 'geiframe.equinox'}), '(obstime=geiframe.obstime, equinox=geiframe.equinox)\n', (43089, 43141), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((44371, 44447), 'astropy.coordinates.HeliocentricMeanEcliptic', 'HeliocentricMeanEcliptic', ([], {'obstime': 'geicoord.obstime', 'equinox': 'geicoord.equinox'}), '(obstime=geicoord.obstime, equinox=geicoord.equinox)\n', (44395, 44447), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((46429, 46460), 'copy.deepcopy', 'deepcopy', (['frame_transform_graph'], {}), '(frame_transform_graph)\n', (46437, 46460), False, 'from copy import deepcopy\n'), ((47191, 47229), 'astropy.coordinates.builtin_frames.make_transform_graph_docs', 'make_transform_graph_docs', (['small_graph'], {}), '(small_graph)\n', (47216, 47229), False, 'from astropy.coordinates.builtin_frames import make_transform_graph_docs\n'), ((9788, 9799), 'functools.wraps', 'wraps', (['func'], {}), '(func)\n', (9793, 9799), False, 'from functools import wraps\n'), ((11552, 11730), 'astropy.coordinates.ConvertError', 'ConvertError', (['f"""The source observer is set to None, but the transformation requires the source observer to be specified, as the destination observer is set to {obs_2}."""'], {}), "(\n f'The source observer is set to None, but the transformation requires the source observer to be specified, as the destination observer is set to {obs_2}.'\n )\n", (11564, 11730), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((11817, 12000), 'astropy.coordinates.ConvertError', 'ConvertError', (['f"""The destination observer is set to None, but the transformation requires the destination observer to be specified, as the source observer is set to {obs_1}."""'], {}), "(\n f'The destination observer is set to None, but the transformation requires the destination observer to be specified, as the source observer is set to {obs_1}.'\n )\n", (11829, 12000), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((12149, 12269), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""The source observer needs to have `obstime` set because the destination observer is different."""'], {}), "(\n 'The source observer needs to have `obstime` set because the destination observer is different.'\n )\n", (12161, 12269), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((12388, 12508), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""The destination observer needs to have `obstime` set because the source observer is different."""'], {}), "(\n 'The destination observer needs to have `obstime` set because the source observer is different.'\n )\n", (12400, 12508), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((12889, 13019), 'astropy.coordinates.ConvertError', 'ConvertError', (['f"""This transformation cannot be performed because the {frame.__class__.__name__} frame has observer=None."""'], {}), "(\n f'This transformation cannot be performed because the {frame.__class__.__name__} frame has observer=None.'\n )\n", (12901, 13019), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((13960, 13992), 'numpy.all', 'np.all', (['(time_1.tai == time_2.tai)'], {}), '(time_1.tai == time_2.tai)\n', (13966, 13992), True, 'import numpy as np\n'), ((15234, 15341), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (15246, 15341), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((19125, 19176), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(0 * u.m)', '(0 * u.m)', 'distance'], {}), '(0 * u.m, 0 * u.m, distance)\n', (19148, 19176), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((25159, 25180), 'numpy.stack', 'np.stack', (['matrix_list'], {}), '(matrix_list)\n', (25167, 25180), True, 'import numpy as np\n'), ((26401, 26425), 'sunpy.sun.constants.get', 'constants.get', (['"""alpha_0"""'], {}), "('alpha_0')\n", (26414, 26425), False, 'from sunpy.sun import constants\n'), ((26484, 26508), 'sunpy.sun.constants.get', 'constants.get', (['"""delta_0"""'], {}), "('delta_0')\n", (26497, 26508), False, 'from sunpy.sun import constants\n'), ((28363, 28392), 'numpy.any', 'np.any', (['(hcrs_time != hgs_time)'], {}), '(hcrs_time != hgs_time)\n', (28369, 28392), True, 'import numpy as np\n'), ((28421, 28459), 'astropy.coordinates.get_body_barycentric', 'get_body_barycentric', (['"""sun"""', 'hcrs_time'], {}), "('sun', hcrs_time)\n", (28441, 28459), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((29266, 29385), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the HeliographicStonyhurst frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the HeliographicStonyhurst frame needs a specified `obstime`.'\n )\n", (29278, 29385), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((30171, 30290), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the HeliographicStonyhurst frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the HeliographicStonyhurst frame needs a specified `obstime`.'\n )\n", (30183, 30290), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((33668, 33700), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(1)', '(0)', '(0)'], {}), '(1, 0, 0)\n', (33691, 33700), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((34123, 34230), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (34135, 34230), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((35112, 35219), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (35124, 35219), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((36777, 36884), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (36789, 36884), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((37105, 37137), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(1)', '(0)', '(0)'], {}), '(1, 0, 0)\n', (37128, 37137), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((37976, 38083), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (37988, 38083), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((38302, 38334), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(1)', '(0)', '(0)'], {}), '(1, 0, 0)\n', (38325, 38334), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((39398, 39430), 'astropy.coordinates.representation.CartesianRepresentation', 'CartesianRepresentation', (['(0)', '(0)', '(1)'], {}), '(0, 0, 1)\n', (39421, 39430), False, 'from astropy.coordinates.representation import CartesianRepresentation, SphericalRepresentation, UnitSphericalRepresentation\n'), ((40530, 40637), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (40542, 40637), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((41353, 41460), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (41365, 41460), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((42839, 42946), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (42851, 42946), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((44159, 44266), 'astropy.coordinates.ConvertError', 'ConvertError', (['"""To perform this transformation, the coordinate frame needs a specified `obstime`."""'], {}), "(\n 'To perform this transformation, the coordinate frame needs a specified `obstime`.'\n )\n", (44171, 44266), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((1805, 1828), 'sunpy.sun.constants.get', 'constants.get', (['"""radius"""'], {}), "('radius')\n", (1818, 1828), False, 'from sunpy.sun import constants\n'), ((5488, 5565), 'sunpy.log.debug', 'log.debug', (['"""Ignoring the motion of the center of the Sun for transformations"""'], {}), "('Ignoring the motion of the center of the Sun for transformations')\n", (5497, 5565), False, 'from sunpy import log\n'), ((5677, 5764), 'sunpy.log.debug', 'log.debug', (['"""Stop ignoring the motion of the center of the Sun for transformations"""'], {}), "(\n 'Stop ignoring the motion of the center of the Sun for transformations')\n", (5686, 5764), False, 'from sunpy import log\n'), ((9012, 9130), 'sunpy.log.debug', 'log.debug', (['f"""Enabling automatic solar differential rotation (\'{rotation_model}\') for any changes in obstime"""'], {}), '(\n f"Enabling automatic solar differential rotation (\'{rotation_model}\') for any changes in obstime"\n )\n', (9021, 9130), False, 'from sunpy import log\n'), ((9287, 9384), 'sunpy.log.debug', 'log.debug', (['"""Disabling automatic solar differential rotation for any changes in obstime"""'], {}), "(\n 'Disabling automatic solar differential rotation for any changes in obstime'\n )\n", (9296, 9384), False, 'from sunpy import log\n'), ((9988, 10011), 'sunpy.log.getEffectiveLevel', 'log.getEffectiveLevel', ([], {}), '()\n', (10009, 10011), False, 'from sunpy import log\n'), ((10521, 10559), 'sunpy.log.debug', 'log.debug', (['f"""{indention}{description}"""'], {}), "(f'{indention}{description}')\n", (10530, 10559), False, 'from sunpy import log\n'), ((10576, 10619), 'sunpy.log.debug', 'log.debug', (['f"""{indention}├─From: {from_str}"""'], {}), "(f'{indention}├─From: {from_str}')\n", (10585, 10619), False, 'from sunpy import log\n'), ((10646, 10687), 'sunpy.log.debug', 'log.debug', (['f"""{indention}├─To : {to_str}"""'], {}), "(f'{indention}├─To : {to_str}')\n", (10655, 10687), False, 'from sunpy import log\n'), ((11200, 11242), 'sunpy.log.debug', 'log.debug', (['f"""{indention}└─Out : {out_str}"""'], {}), "(f'{indention}└─Out : {out_str}')\n", (11209, 11242), False, 'from sunpy import log\n'), ((13137, 13320), 'astropy.coordinates.ConvertError', 'ConvertError', (['f"""This transformation cannot be performed because the {frame.__class__.__name__} frame needs a specified obstime to fully resolve observer=\'{frame.observer}\'."""'], {}), '(\n f"This transformation cannot be performed because the {frame.__class__.__name__} frame needs a specified obstime to fully resolve observer=\'{frame.observer}\'."\n )\n', (13149, 13320), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((34473, 34503), 'astropy.coordinates.HCRS', 'HCRS', ([], {'obstime': 'hmecoord.obstime'}), '(obstime=hmecoord.obstime)\n', (34477, 34503), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((35651, 35682), 'astropy.coordinates.HCRS', 'HCRS', ([], {'obstime': 'int_coord.obstime'}), '(obstime=int_coord.obstime)\n', (35655, 35682), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((43180, 43211), 'astropy.coordinates.HCRS', 'HCRS', ([], {'obstime': 'int_frame.obstime'}), '(obstime=int_frame.obstime)\n', (43184, 43211), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((45080, 45111), 'astropy.coordinates.HCRS', 'HCRS', ([], {'obstime': 'int_coord.obstime'}), '(obstime=int_coord.obstime)\n', (45084, 45111), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((12556, 12588), 'astropy.units.allclose', 'u.allclose', (['obs_1.lat', 'obs_2.lat'], {}), '(obs_1.lat, obs_2.lat)\n', (12566, 12588), True, 'import astropy.units as u\n'), ((12619, 12651), 'astropy.units.allclose', 'u.allclose', (['obs_1.lon', 'obs_2.lon'], {}), '(obs_1.lon, obs_2.lon)\n', (12629, 12651), True, 'import astropy.units as u\n'), ((12682, 12720), 'astropy.units.allclose', 'u.allclose', (['obs_1.radius', 'obs_2.radius'], {}), '(obs_1.radius, obs_2.radius)\n', (12692, 12720), True, 'import astropy.units as u\n'), ((13458, 13599), 'astropy.coordinates.ConvertError', 'ConvertError', (['f"""The {frame.__class__.__name__} frame has observer=\'self\' but this is valid for only HeliographicCarrington frames."""'], {}), '(\n f"The {frame.__class__.__name__} frame has observer=\'self\' but this is valid for only HeliographicCarrington frames."\n )\n', (13470, 13599), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((42433, 42453), 'astropy.coordinates.builtin_frames.utils.get_jd12', 'get_jd12', (['time', '"""tt"""'], {}), "(time, 'tt')\n", (42441, 42453), False, 'from astropy.coordinates.builtin_frames.utils import get_jd12\n'), ((45671, 45701), 'astropy.coordinates.HCRS', 'HCRS', ([], {'obstime': 'from_coo.obstime'}), '(obstime=from_coo.obstime)\n', (45675, 45701), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((31524, 31554), 'astropy.coordinates.HCRS', 'HCRS', ([], {'obstime': 'to_frame.obstime'}), '(obstime=to_frame.obstime)\n', (31528, 31554), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n'), ((36235, 36265), 'astropy.coordinates.HCRS', 'HCRS', ([], {'obstime': 'from_coo.obstime'}), '(obstime=from_coo.obstime)\n', (36239, 36265), False, 'from astropy.coordinates import HCRS, ICRS, BaseCoordinateFrame, ConvertError, HeliocentricMeanEcliptic, get_body_barycentric\n')]
|
from keras.callbacks import Callback
import keras.backend as K
import numpy as np
class SGDRScheduler(Callback):
'''Cosine annealing learning rate scheduler with periodic restarts.
# Usage
```python
schedule = SGDRScheduler(min_lr=1e-5,
max_lr=1e-2,
steps_per_epoch=np.ceil(epoch_size/batch_size),
lr_decay=0.9,
cycle_length=5,
mult_factor=1.5)
model.fit(X_train, Y_train, epochs=100, callbacks=[schedule])
```
# Arguments
min_lr: The lower bound of the learning rate range for the experiment.
max_lr: The upper bound of the learning rate range for the experiment.
steps_per_epoch: Number of mini-batches in the dataset. Calculated as `np.ceil(epoch_size/batch_size)`.
lr_decay: Reduce the max_lr after the completion of each cycle.
Ex. To reduce the max_lr by 20% after each cycle, set this value to 0.8.
cycle_length: Initial number of epochs in a cycle.
mult_factor: Scale epochs_to_restart after each full cycle completion.
# References
Blog post: jeremyjordan.me/nn-learning-rate
Original paper: http://arxiv.org/abs/1608.03983
'''
def __init__(self,
min_lr,
max_lr,
steps_per_epoch,
lr_decay=1,
cycle_length=10,
mult_factor=2):
self.min_lr = min_lr
self.max_lr = max_lr
self.lr_decay = lr_decay
self.batch_since_restart = 0
self.next_restart = cycle_length
self.steps_per_epoch = steps_per_epoch
self.cycle_length = cycle_length
self.mult_factor = mult_factor
self.history = {}
def clr(self):
'''Calculate the learning rate.'''
fraction_to_restart = self.batch_since_restart / (self.steps_per_epoch * self.cycle_length)
lr = self.min_lr + 0.5 * (self.max_lr - self.min_lr) * (1 + np.cos(fraction_to_restart * np.pi))
return lr
def on_train_begin(self, logs={}):
'''Initialize the learning rate to the minimum value at the start of training.'''
logs = logs or {}
K.set_value(self.model.optimizer.lr, self.max_lr)
def on_batch_end(self, batch, logs={}):
'''Record previous batch statistics and update the learning rate.'''
logs = logs or {}
self.history.setdefault('lr', []).append(K.get_value(self.model.optimizer.lr))
for k, v in logs.items():
self.history.setdefault(k, []).append(v)
self.batch_since_restart += 1
K.set_value(self.model.optimizer.lr, self.clr())
def on_epoch_end(self, epoch, logs={}):
if callable(self.lr_decay):
decay = self.lr_decay(epoch)
else:
decay = self.lr_decay
'''Check for end of current cycle, apply restarts when necessary.'''
if epoch + 1 == self.next_restart:
self.batch_since_restart = 0
self.cycle_length = np.ceil(self.cycle_length * self.mult_factor)
self.next_restart += self.cycle_length
self.max_lr *= decay
print('SGDRScheduler :: set max lr in ', self.max_lr)
# def on_train_end(self, logs={}):
# '''Set weights to the values from the end of the most recent cycle for best performance.'''
# self.model.set_weights(self.best_weights)
|
[
"keras.backend.set_value",
"keras.backend.get_value",
"numpy.ceil",
"numpy.cos"
] |
[((2345, 2394), 'keras.backend.set_value', 'K.set_value', (['self.model.optimizer.lr', 'self.max_lr'], {}), '(self.model.optimizer.lr, self.max_lr)\n', (2356, 2394), True, 'import keras.backend as K\n'), ((2592, 2628), 'keras.backend.get_value', 'K.get_value', (['self.model.optimizer.lr'], {}), '(self.model.optimizer.lr)\n', (2603, 2628), True, 'import keras.backend as K\n'), ((3176, 3221), 'numpy.ceil', 'np.ceil', (['(self.cycle_length * self.mult_factor)'], {}), '(self.cycle_length * self.mult_factor)\n', (3183, 3221), True, 'import numpy as np\n'), ((2126, 2161), 'numpy.cos', 'np.cos', (['(fraction_to_restart * np.pi)'], {}), '(fraction_to_restart * np.pi)\n', (2132, 2161), True, 'import numpy as np\n')]
|
import cv2
import numpy as np
from PIL import Image
import os
path = "./photo/myobject"
filelist = os.listdir(path)
total_num = len(filelist)
n = 6
for i in range(1,total_num):
n = 6 - len(str(i))
filepath = "./photo/myobject/"+str(0)*n + str(i)+".jpg"
imgsize = Image.open(filepath)#開啟圖片
print('開啟檔案:' + filepath)
for a in range(1,101):
for b in range(1,101):
print('round %s_%s_%s' % (str(i),str(a),str(b)))
img = cv2.imread(filepath)
mask = np.zeros(img.shape[:2],np.uint8)
bgdModel = np.zeros((1,65),np.float64)
fgdModel = np.zeros((1,65),np.float64)
rect = (a,b,imgsize.size[0],imgsize.size[1])
cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)
mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
img = img*mask2[:,:,np.newaxis]
print('輸出檔案:%s_%s_%s.jpg' %(str(0)*n + str(i),str(a),str(b)))
cv2.imwrite('./save/%s_%s_%s.jpg' %(str(0)*n + str(i),str(a),str(b)),img)
|
[
"cv2.grabCut",
"numpy.zeros",
"PIL.Image.open",
"cv2.imread",
"numpy.where",
"os.listdir"
] |
[((101, 117), 'os.listdir', 'os.listdir', (['path'], {}), '(path)\n', (111, 117), False, 'import os\n'), ((278, 298), 'PIL.Image.open', 'Image.open', (['filepath'], {}), '(filepath)\n', (288, 298), False, 'from PIL import Image\n'), ((471, 491), 'cv2.imread', 'cv2.imread', (['filepath'], {}), '(filepath)\n', (481, 491), False, 'import cv2\n'), ((511, 544), 'numpy.zeros', 'np.zeros', (['img.shape[:2]', 'np.uint8'], {}), '(img.shape[:2], np.uint8)\n', (519, 544), True, 'import numpy as np\n'), ((567, 596), 'numpy.zeros', 'np.zeros', (['(1, 65)', 'np.float64'], {}), '((1, 65), np.float64)\n', (575, 596), True, 'import numpy as np\n'), ((618, 647), 'numpy.zeros', 'np.zeros', (['(1, 65)', 'np.float64'], {}), '((1, 65), np.float64)\n', (626, 647), True, 'import numpy as np\n'), ((715, 789), 'cv2.grabCut', 'cv2.grabCut', (['img', 'mask', 'rect', 'bgdModel', 'fgdModel', '(5)', 'cv2.GC_INIT_WITH_RECT'], {}), '(img, mask, rect, bgdModel, fgdModel, 5, cv2.GC_INIT_WITH_RECT)\n', (726, 789), False, 'import cv2\n'), ((804, 845), 'numpy.where', 'np.where', (['((mask == 2) | (mask == 0))', '(0)', '(1)'], {}), '((mask == 2) | (mask == 0), 0, 1)\n', (812, 845), True, 'import numpy as np\n')]
|
"""
Math Utilities
"""
import collections
import numpy as np
from nnlib.utils.functional import not_none
__all__ = ['FNVHash', 'ceil_div', 'normalize', 'pow', 'prod', 'sum', 'random_subset', 'softmax']
class FNVHash:
hval = 0x811c9dc5
fnv_32_prime = 0x01000193
uint32_max = 2 ** 32
@staticmethod
def hash(s):
h = FNVHash.hval
for ch in s:
h = ((h ^ ord(ch)) * FNVHash.fnv_32_prime) % FNVHash.uint32_max
return h
def ceil_div(a, b):
r"""
Integer division that rounds up.
"""
return (a + b - 1) // b
def normalize(xs):
r"""
NumPy-based normalization.
"""
arr = np.asarray(xs, dtype=np.float)
return arr / np.sum(arr)
# noinspection PyShadowingBuiltins
def pow(a, b, fast=True):
r"""
Compute ``a ** b`` (``a`` raised to ``b``-th power). ``b`` has to be a positive integer.
**Note:** It is not required for ``type(a)`` to have an identity element.
:param a: The base. Can be any variable that supports multiplication ``*``.
:type b: int
:param b: The exponent.
:param fast: Whether to use fast exponent algorithm (that runs in logarithmic time).
"""
if type(b) is not int:
raise TypeError("Exponent should be a positive integer.")
if b < 1:
raise ValueError("Exponent should be a positive integer.")
result = a
b -= 1
if fast: # O(log b)
while b > 0:
if b % 2 == 1:
result *= a
b //= 2
a *= a
else: # O(b)
while b > 0:
result *= a
b -= 1
return result
def _reduce(fn, *args):
r"""
Recursively reduce over sequence of values, where values can be sequences. None values are ignored.
:type fn: (Any, Any) -> Any
:param fn: Function taking (accumulator, element) and returning new accumulator.
"""
result = None
for x in filter(not_none, args):
val = _reduce(fn, *x) if isinstance(x, collections.Iterable) else x
if result is None:
result = val
else:
result = fn(result, val)
return result
def _ireduce(fn, *args):
r"""
In-place version of ``_reduce``.
:type fn: (Any, Any) -> None
:param fn: Function taking (accumulator, element) and performing in-place operation on accumulator.
"""
return _reduce(lambda x, y: [fn(x, y), x][-1], *args)
def prod(*args):
r"""
Compute product of arguments, ignoring ``None`` values. Arguments could contain lists, or list of lists, etc.
**Note:** It is not required for list elements to have an identity element.
"""
return _reduce(lambda x, y: x.__rmul__(y), *args)
# noinspection PyShadowingBuiltins
def sum(*args):
r"""
Compute sum of arguments, ignoring ``None`` values. Arguments could contain lists, or list of lists, etc.
**Note:** It is not required for list elements to have an identity element.
"""
return _reduce(lambda x, y: x.__add__(y), *args)
def random_subset(total, size):
r"""
Select a random subset of size ``size`` from the larger set of size ``total``.
This method is implemented to replace :func:`numpy.random.choice` with :attr:`replacement=False`.
:param total: Size of the original set.
:param size: Size of the randomly selected subset.
:return: The 0-based indices of the subset elements.
"""
if isinstance(size, float):
size = int(total * size)
# Don't trust `np.random.choice` without replacement! It's using brute force!
if size * np.log(size) > total:
return np.random.permutation(np.arange(total))[:size]
else:
choices = set()
while len(choices) < size:
choices.add(np.random.choice(total, size - len(choices)).tolist())
return choices
def softmax(xs, t=1):
r"""
NumPy-based softmax with temperature. Returns a sequence with each element calculated as:
.. math::
s_i = \frac{ \exp(x_i / t) }{ \sum_x \exp(x / t) }
:param xs: The sequence of weights.
:param t: Temperature. Higher temperatures give a more uniform distribution, while lower temperatures give a more
peaked distribution.
"""
arr = np.exp(np.asarray(xs) / t)
return arr / np.sum(arr)
|
[
"numpy.arange",
"numpy.asarray",
"numpy.sum",
"numpy.log"
] |
[((657, 687), 'numpy.asarray', 'np.asarray', (['xs'], {'dtype': 'np.float'}), '(xs, dtype=np.float)\n', (667, 687), True, 'import numpy as np\n'), ((705, 716), 'numpy.sum', 'np.sum', (['arr'], {}), '(arr)\n', (711, 716), True, 'import numpy as np\n'), ((4282, 4293), 'numpy.sum', 'np.sum', (['arr'], {}), '(arr)\n', (4288, 4293), True, 'import numpy as np\n'), ((3576, 3588), 'numpy.log', 'np.log', (['size'], {}), '(size)\n', (3582, 3588), True, 'import numpy as np\n'), ((4245, 4259), 'numpy.asarray', 'np.asarray', (['xs'], {}), '(xs)\n', (4255, 4259), True, 'import numpy as np\n'), ((3635, 3651), 'numpy.arange', 'np.arange', (['total'], {}), '(total)\n', (3644, 3651), True, 'import numpy as np\n')]
|
"""Beat-synchronous chroma feature calculation with LabROSA.
<NAME> <EMAIL> 2016-04-08
"""
from __future__ import print_function
import cPickle as pickle
import getopt
import os
import sys
import time
import numpy as np
import scipy
import sklearn.mixture
import librosa
def read_iso_label_file(filename):
"""Read in an isophonics-format chord label file."""
times = []
labels = []
with open(filename, 'r') as f:
for line in f:
fields = line.strip().split(' ')
start_secs = float(fields[0])
end_secs = float(fields[1])
times.append((start_secs, end_secs))
labels.append(fields[2])
return np.array(times), labels
def calculate_overlap_durations(ranges_a, ranges_b):
"""Calculate duration of overlaps between all (start, end) intervals."""
max_starts_matrix = np.maximum.outer(ranges_a[:, 0], ranges_b[:, 0])
min_ends_matrix = np.minimum.outer(ranges_a[:, 1], ranges_b[:, 1])
overlap_durations = np.maximum(0, min_ends_matrix - max_starts_matrix)
return overlap_durations
def sample_label_sequence(sample_ranges, label_ranges, labels):
"""Find the most-overlapping label for a list of (start, end) intervals."""
overlaps = calculate_overlap_durations(sample_ranges, label_ranges)
best_label = np.argmax(overlaps, axis=1)
return [labels[i] for i in best_label]
def chord_name_to_index(labels):
"""Convert chord name strings into model indices (0..25)."""
indices = np.zeros(len(labels), dtype=int)
root_degrees = {'C': 0, 'D': 2, 'E': 4, 'F':5, 'G': 7, 'A':9, 'B': 11}
for label_index, label in enumerate(labels):
if label == 'N' or label == 'X':
# Leave at zero.
continue
root_degree = root_degrees[label[0].upper()]
minor = False
if len(label) > 1:
if label[1] == '#':
root_degree = (root_degree + 1) % 12
if label[1] == 'b':
root_degree = (root_degree - 1) % 12
if ':' in label:
modifier = label[label.index(':') + 1:]
if modifier[:3] == 'min':
minor = True
indices[label_index] = 1 + root_degree + 12 * minor
return indices
def calculate_beat_sync_chroma_of_file(wavfilename):
"""Read the audio, calculate beat-sync chroma."""
y, sr = librosa.load(wavfilename, sr=None)
hop_length = 128 # 8 ms at 16 kHz
tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr,
hop_length=hop_length,
start_bpm=240)
# Append a final beat time one beat beyond the end.
extended_beat_frames = np.hstack([beat_frames,
2*beat_frames[-1] - beat_frames[-2]])
frame_chroma = librosa.feature.chroma_cqt(y=y, sr=sr, hop_length=hop_length)
# Drop the first beat_chroma which is stuff before the first beat,
# and the final beat_chroma which is everything after the last beat time.
beat_chroma = librosa.feature.sync(frame_chroma,
extended_beat_frames).transpose()
# Drop first row if the beat_frames start after the beginning.
if beat_frames[0] > 0:
beat_chroma = beat_chroma[1:]
# Keep only as many frames as beat times.
beat_chroma = beat_chroma[:len(beat_frames)]
assert beat_chroma.shape[0] == beat_frames.shape[0]
frame_rate = sr / float(hop_length)
beat_times = beat_frames / frame_rate
return beat_times, beat_chroma
def calculate_label_indices(labfilename, beat_times):
"""Read a label file, sample at beat times, return 0..25 indices."""
# MP3s encoded with lame have a 68 ms delay
LAME_DELAY_SECONDS = 0.068
extended_beat_times = (np.hstack([beat_times,
2*beat_times[-1] - beat_times[-2]]) -
LAME_DELAY_SECONDS)
beat_ranges = np.hstack([extended_beat_times[:-1, np.newaxis],
extended_beat_times[1:, np.newaxis]])
label_time_ranges, labels = read_iso_label_file(labfilename)
beat_labels = sample_label_sequence(beat_ranges, label_time_ranges, labels)
label_indices = chord_name_to_index(beat_labels)
return label_indices
def write_beat_chroma_labels(filename, beat_times, chroma_features,
label_indices):
"""Write out the computed beat-synchronous chroma data."""
# Create the enclosing directory if needed.
directory = os.path.dirname(filename)
if directory and not os.path.exists(directory):
os.makedirs(directory)
with open(filename, "wb") as f:
pickle.dump((beat_times, chroma_features, label_indices),
f, pickle.HIGHEST_PROTOCOL)
def read_beat_chroma_labels(filename):
"""Read back a precomputed beat-synchronous chroma record."""
with open(filename, "rb") as f:
beat_times, chroma_features, label_indices = pickle.load(f)
return beat_times, chroma_features, label_indices
def read_file_list(filename):
"""Read a text file with one item per line."""
items = []
with open(filename, 'r') as f:
for line in f:
items.append(line.strip())
return items
def process_items(input_list_file, wav_base_dir, lab_base_dir, output_base_dir,
start_index, num_to_process):
"""Process files from a list."""
all_ids = read_file_list(input_list_file)
print("total ids in list:", len(all_ids))
if num_to_process > 0:
ids_to_process = all_ids[start_index : start_index + num_to_process]
else:
ids_to_process = all_ids[start_index:]
for number, file_id in enumerate(ids_to_process):
print(time.ctime(), "File {:d} of {:d}: {:s}".format(
number, len(ids_to_process), file_id))
wavfilename = os.path.join(wav_base_dir, file_id + '.mp3')
beat_times, beat_chroma = calculate_beat_sync_chroma_of_file(
wavfilename)
if lab_base_dir:
labfilename = os.path.join(lab_base_dir, file_id + '.txt')
label_indices = calculate_label_indices(labfilename, beat_times)
else:
label_indices = None
beatchromlab_filename = os.path.join(output_base_dir, file_id + '.pkl')
write_beat_chroma_labels(beatchromlab_filename, beat_times,
beat_chroma, label_indices)
#DATA_DIR = '/q/porkpie/porkpie-p9/hog-restored/hog-p9/drspeech/data/music/'
HELP_STRING = '-i <inputlistfile> -o <outputbasedir> -w <wavbasedir> -l <labbasedir> -s <startindex> -n <numtoprocess>'
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv[1:], "hi:o:s:n:w:l:",
["inputlistfile=", "outputbasedir=",
"startindex=", "numtoprocess=",
"wavbasedir=", "labbasedir="])
except getopt.GetoptError:
print(argv[0], HELP_STRING)
sys.exit(2)
input_list_file = 'mp3s-mp3s.txt'
output_base_dir = 'beatchromftrs'
wav_base_dir = 'mp3s-32k'
lab_base_dir = None
start_index = 0
num_to_process = -1
for opt, arg in opts:
if opt == '-h':
print(argv[0], HELP_STRING)
sys.exit()
elif opt in ("-i", "--inputlistfile"):
input_list_file = arg
elif opt in ("-o", "--outputbasedir"):
output_base_dir = arg
elif opt in ("-s", "--startindex"):
start_index = int(arg)
elif opt in ("-n", "--numtoprocess"):
num_to_process = int(arg)
elif opt in ("-w", "--wavbasedir"):
wav_base_dir = arg
elif opt in ("-l", "--labbasedir"):
lab_base_dir = arg
process_items(input_list_file, wav_base_dir, lab_base_dir,
output_base_dir, start_index, num_to_process)
if __name__ == "__main__":
main(sys.argv)
|
[
"numpy.maximum",
"getopt.getopt",
"numpy.argmax",
"time.ctime",
"cPickle.load",
"librosa.feature.sync",
"os.path.join",
"os.path.dirname",
"os.path.exists",
"numpy.maximum.outer",
"librosa.feature.chroma_cqt",
"numpy.hstack",
"librosa.load",
"sys.exit",
"os.makedirs",
"cPickle.dump",
"numpy.array",
"librosa.beat.beat_track",
"numpy.minimum.outer"
] |
[((864, 912), 'numpy.maximum.outer', 'np.maximum.outer', (['ranges_a[:, 0]', 'ranges_b[:, 0]'], {}), '(ranges_a[:, 0], ranges_b[:, 0])\n', (880, 912), True, 'import numpy as np\n'), ((935, 983), 'numpy.minimum.outer', 'np.minimum.outer', (['ranges_a[:, 1]', 'ranges_b[:, 1]'], {}), '(ranges_a[:, 1], ranges_b[:, 1])\n', (951, 983), True, 'import numpy as np\n'), ((1008, 1058), 'numpy.maximum', 'np.maximum', (['(0)', '(min_ends_matrix - max_starts_matrix)'], {}), '(0, min_ends_matrix - max_starts_matrix)\n', (1018, 1058), True, 'import numpy as np\n'), ((1323, 1350), 'numpy.argmax', 'np.argmax', (['overlaps'], {'axis': '(1)'}), '(overlaps, axis=1)\n', (1332, 1350), True, 'import numpy as np\n'), ((2388, 2422), 'librosa.load', 'librosa.load', (['wavfilename'], {'sr': 'None'}), '(wavfilename, sr=None)\n', (2400, 2422), False, 'import librosa\n'), ((2487, 2560), 'librosa.beat.beat_track', 'librosa.beat.beat_track', ([], {'y': 'y', 'sr': 'sr', 'hop_length': 'hop_length', 'start_bpm': '(240)'}), '(y=y, sr=sr, hop_length=hop_length, start_bpm=240)\n', (2510, 2560), False, 'import librosa\n'), ((2744, 2807), 'numpy.hstack', 'np.hstack', (['[beat_frames, 2 * beat_frames[-1] - beat_frames[-2]]'], {}), '([beat_frames, 2 * beat_frames[-1] - beat_frames[-2]])\n', (2753, 2807), True, 'import numpy as np\n'), ((2864, 2925), 'librosa.feature.chroma_cqt', 'librosa.feature.chroma_cqt', ([], {'y': 'y', 'sr': 'sr', 'hop_length': 'hop_length'}), '(y=y, sr=sr, hop_length=hop_length)\n', (2890, 2925), False, 'import librosa\n'), ((4003, 4094), 'numpy.hstack', 'np.hstack', (['[extended_beat_times[:-1, np.newaxis], extended_beat_times[1:, np.newaxis]]'], {}), '([extended_beat_times[:-1, np.newaxis], extended_beat_times[1:, np\n .newaxis]])\n', (4012, 4094), True, 'import numpy as np\n'), ((4586, 4611), 'os.path.dirname', 'os.path.dirname', (['filename'], {}), '(filename)\n', (4601, 4611), False, 'import os\n'), ((684, 699), 'numpy.array', 'np.array', (['times'], {}), '(times)\n', (692, 699), True, 'import numpy as np\n'), ((3838, 3898), 'numpy.hstack', 'np.hstack', (['[beat_times, 2 * beat_times[-1] - beat_times[-2]]'], {}), '([beat_times, 2 * beat_times[-1] - beat_times[-2]])\n', (3847, 3898), True, 'import numpy as np\n'), ((4672, 4694), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (4683, 4694), False, 'import os\n'), ((4739, 4829), 'cPickle.dump', 'pickle.dump', (['(beat_times, chroma_features, label_indices)', 'f', 'pickle.HIGHEST_PROTOCOL'], {}), '((beat_times, chroma_features, label_indices), f, pickle.\n HIGHEST_PROTOCOL)\n', (4750, 4829), True, 'import cPickle as pickle\n'), ((5042, 5056), 'cPickle.load', 'pickle.load', (['f'], {}), '(f)\n', (5053, 5056), True, 'import cPickle as pickle\n'), ((5935, 5979), 'os.path.join', 'os.path.join', (['wav_base_dir', "(file_id + '.mp3')"], {}), "(wav_base_dir, file_id + '.mp3')\n", (5947, 5979), False, 'import os\n'), ((6327, 6374), 'os.path.join', 'os.path.join', (['output_base_dir', "(file_id + '.pkl')"], {}), "(output_base_dir, file_id + '.pkl')\n", (6339, 6374), False, 'import os\n'), ((6792, 6940), 'getopt.getopt', 'getopt.getopt', (['argv[1:]', '"""hi:o:s:n:w:l:"""', "['inputlistfile=', 'outputbasedir=', 'startindex=', 'numtoprocess=',\n 'wavbasedir=', 'labbasedir=']"], {}), "(argv[1:], 'hi:o:s:n:w:l:', ['inputlistfile=',\n 'outputbasedir=', 'startindex=', 'numtoprocess=', 'wavbasedir=',\n 'labbasedir='])\n", (6805, 6940), False, 'import getopt\n'), ((3094, 3150), 'librosa.feature.sync', 'librosa.feature.sync', (['frame_chroma', 'extended_beat_frames'], {}), '(frame_chroma, extended_beat_frames)\n', (3114, 3150), False, 'import librosa\n'), ((4637, 4662), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (4651, 4662), False, 'import os\n'), ((5814, 5826), 'time.ctime', 'time.ctime', ([], {}), '()\n', (5824, 5826), False, 'import time\n'), ((6126, 6170), 'os.path.join', 'os.path.join', (['lab_base_dir', "(file_id + '.txt')"], {}), "(lab_base_dir, file_id + '.txt')\n", (6138, 6170), False, 'import os\n'), ((7115, 7126), 'sys.exit', 'sys.exit', (['(2)'], {}), '(2)\n', (7123, 7126), False, 'import sys\n'), ((7403, 7413), 'sys.exit', 'sys.exit', ([], {}), '()\n', (7411, 7413), False, 'import sys\n')]
|
import logging
import numpy as np
from amset.constants import defaults
from amset.deformation.common import desymmetrize_deformation_potentials
from amset.deformation.io import load_deformation_potentials
from amset.electronic_structure.kpoints import get_mesh_from_kpoint_numbers
from amset.electronic_structure.symmetry import expand_kpoints
from amset.interpolation.periodic import PeriodicLinearInterpolator
__author__ = "<NAME>"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
logger = logging.getLogger(__name__)
class DeformationPotentialInterpolator(PeriodicLinearInterpolator):
@classmethod
def from_file(cls, filename, scale=1.0):
deform_potentials, kpoints, structure = load_deformation_potentials(filename)
deform_potentials = {s: d * scale for s, d in deform_potentials.items()}
return cls.from_deformation_potentials(deform_potentials, kpoints, structure)
@classmethod
def from_deformation_potentials(
cls, deformation_potentials, kpoints, structure, symprec=defaults["symprec"]
):
logger.info("Initializing deformation potential interpolator")
mesh_dim = get_mesh_from_kpoint_numbers(kpoints)
if np.product(mesh_dim) == len(kpoints):
return cls.from_data(kpoints, deformation_potentials)
full_kpoints, rotations, _, _, op_mapping, kp_mapping = expand_kpoints(
structure, kpoints, time_reversal=True, return_mapping=True, symprec=symprec
)
logger.warning("Desymmetrizing deformation potentials, this could go wrong.")
deformation_potentials = desymmetrize_deformation_potentials(
deformation_potentials, structure, rotations, op_mapping, kp_mapping
)
return cls.from_data(full_kpoints, deformation_potentials)
|
[
"amset.deformation.common.desymmetrize_deformation_potentials",
"amset.electronic_structure.kpoints.get_mesh_from_kpoint_numbers",
"numpy.product",
"amset.electronic_structure.symmetry.expand_kpoints",
"logging.getLogger",
"amset.deformation.io.load_deformation_potentials"
] |
[((495, 522), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (512, 522), False, 'import logging\n'), ((703, 740), 'amset.deformation.io.load_deformation_potentials', 'load_deformation_potentials', (['filename'], {}), '(filename)\n', (730, 740), False, 'from amset.deformation.io import load_deformation_potentials\n'), ((1146, 1183), 'amset.electronic_structure.kpoints.get_mesh_from_kpoint_numbers', 'get_mesh_from_kpoint_numbers', (['kpoints'], {}), '(kpoints)\n', (1174, 1183), False, 'from amset.electronic_structure.kpoints import get_mesh_from_kpoint_numbers\n'), ((1364, 1460), 'amset.electronic_structure.symmetry.expand_kpoints', 'expand_kpoints', (['structure', 'kpoints'], {'time_reversal': '(True)', 'return_mapping': '(True)', 'symprec': 'symprec'}), '(structure, kpoints, time_reversal=True, return_mapping=True,\n symprec=symprec)\n', (1378, 1460), False, 'from amset.electronic_structure.symmetry import expand_kpoints\n'), ((1598, 1707), 'amset.deformation.common.desymmetrize_deformation_potentials', 'desymmetrize_deformation_potentials', (['deformation_potentials', 'structure', 'rotations', 'op_mapping', 'kp_mapping'], {}), '(deformation_potentials, structure,\n rotations, op_mapping, kp_mapping)\n', (1633, 1707), False, 'from amset.deformation.common import desymmetrize_deformation_potentials\n'), ((1195, 1215), 'numpy.product', 'np.product', (['mesh_dim'], {}), '(mesh_dim)\n', (1205, 1215), True, 'import numpy as np\n')]
|
"""
Utilities for working with videos, pulling out patches, etc.
"""
import numpy
from pylearn2.compat import OrderedDict
from pylearn2.utils.rng import make_np_rng
__author__ = "<NAME>"
__copyright__ = "Copyright 2011, <NAME> / Universite de Montreal"
__license__ = "BSD"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__all__ = ["get_video_dims", "spatiotemporal_cubes"]
def get_video_dims(fname):
"""
Pull out the frame length, spatial height and spatial width of
a video file using ffmpeg.
Parameters
----------
fname : str
Path to video file to be inspected.
Returns
-------
shape : tuple
The spatiotemporal dimensions of the video
(length, height, width).
"""
try:
import pyffmpeg
except ImportError:
raise ImportError("This function requires pyffmpeg "
"<http://code.google.com/p/pyffmpeg/>")
mp = pyffmpeg.FFMpegReader()
try:
mp.open(fname)
tracks = mp.get_tracks()
for track in tracks:
if isinstance(track, pyffmpeg.VideoTrack):
break
else:
raise ValueError('no video track found')
return (track.duration(),) + track.get_orig_size()
finally:
mp.close()
class FrameLookup(object):
"""
Class encapsulating the logic of turning a frame index into a
collection of files into the frame index of a specific video file.
Item-indexing on this object will yield a (filename, nframes, frame_no)
tuple, where nframes is the number of frames in the given file
(mainly for checking that we're far enough from the end so that we
can sample a big enough chunk).
Parameters
----------
names_ang_lengths : WRITEME
"""
def __init__(self, names_and_lengths):
self.files, self.lengths = zip(*names_and_lengths)
self.terminals = numpy.cumsum([s[1] for s in names_and_lengths])
def __getitem__(self, i):
idx = (i < self.terminals).nonzero()[0][0]
frame_no = i
if idx > 0:
frame_no -= self.terminals[idx - 1]
return self.files[idx], self.lengths[idx], frame_no
def __len__(self):
return self.terminals[-1]
def __iter__(self):
raise TypeError('iteration not supported')
def spatiotemporal_cubes(file_tuples, shape, n_patches=numpy.inf, rng=None):
"""
Generator function that yields a stream of (filename, slicetuple)
representing a spatiotemporal patch of that file.
Parameters
----------
file_tuples : list of tuples
Each element should be a 2-tuple consisting of a filename
(or arbitrary identifier) and a (length, height, width)
shape tuple of the dimensions (number of frames in the video,
height and width of each frame).
shape : tuple
A shape tuple consisting of the desired (length, height, width)
of each spatiotemporal patch.
n_patches : int, optional
The number of patches to generate. By default, generates patches
infinitely.
rng : RandomState object or seed, optional
The random number generator (or seed) to use. Defaults to None,
meaning it will be seeded from /dev/urandom or the clock.
Returns
-------
generator : generator object
A generator that yields a stream of (filename, slicetuple) tuples.
The slice tuple is such that it indexes into a 3D array containing
the entire clip with frames indexed along the first axis, rows
along the second and columns along the third.
"""
frame_lookup = FrameLookup([(a, b[0]) for a, b in file_tuples])
file_lookup = OrderedDict(file_tuples)
patch_length, patch_height, patch_width = shape
done = 0
rng = make_np_rng(rng, which_method="random_integers")
while done < n_patches:
frame = numpy.random.random_integers(0, len(frame_lookup) - 1)
filename, file_length, frame_no = frame_lookup[frame]
# Check that there is a contiguous block of frames starting at
# frame_no that is at least as long as our desired cube length.
if file_length - frame_no < patch_length:
continue
_, video_height, video_width = file_lookup[filename][:3]
# The last row and column in which a patch could "start" to still
# fall within frame.
last_row = video_height - patch_height
last_col = video_width - patch_width
row = numpy.random.random_integers(0, last_row)
col = numpy.random.random_integers(0, last_col)
patch_slice = (slice(frame_no, frame_no + patch_length),
slice(row, row + patch_height),
slice(col, col + patch_width))
done += 1
yield filename, patch_slice
|
[
"pylearn2.utils.rng.make_np_rng",
"pylearn2.compat.OrderedDict",
"pyffmpeg.FFMpegReader",
"numpy.cumsum",
"numpy.random.random_integers"
] |
[((930, 953), 'pyffmpeg.FFMpegReader', 'pyffmpeg.FFMpegReader', ([], {}), '()\n', (951, 953), False, 'import pyffmpeg\n'), ((3701, 3725), 'pylearn2.compat.OrderedDict', 'OrderedDict', (['file_tuples'], {}), '(file_tuples)\n', (3712, 3725), False, 'from pylearn2.compat import OrderedDict\n'), ((3801, 3849), 'pylearn2.utils.rng.make_np_rng', 'make_np_rng', (['rng'], {'which_method': '"""random_integers"""'}), "(rng, which_method='random_integers')\n", (3812, 3849), False, 'from pylearn2.utils.rng import make_np_rng\n'), ((1906, 1953), 'numpy.cumsum', 'numpy.cumsum', (['[s[1] for s in names_and_lengths]'], {}), '([s[1] for s in names_and_lengths])\n', (1918, 1953), False, 'import numpy\n'), ((4499, 4540), 'numpy.random.random_integers', 'numpy.random.random_integers', (['(0)', 'last_row'], {}), '(0, last_row)\n', (4527, 4540), False, 'import numpy\n'), ((4555, 4596), 'numpy.random.random_integers', 'numpy.random.random_integers', (['(0)', 'last_col'], {}), '(0, last_col)\n', (4583, 4596), False, 'import numpy\n')]
|
import numpy as np
import pickle, os, ntpath, cv2
tot_list = []
img_list = []
label_list = []
pickle_dict = {}
load_path = ''
def _load_data(path):
count = 0
for root, dirs, files in os.walk(path):
for file in files:
imgpath = os.path.join(root, file)
tot_list.append(imgpath)
np.random.shuffle(tot_list)
for img in tot_list:
image = cv2.imread(img)
image = cv2.resize(image, (192, 192), cv2.INTER_CUBIC)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
label = [1, 0] if ntpath.basename(img)[0] == '1' else [0, 1]
img_list.append(image)
label_list.append(label)
count += 1
print('>> 총 {} 데이터 loading !'.format(count))
tot_img = np.asarray(img_list)
pickle_dict[b'labels'] = label_list
pickle_dict[b'data'] = tot_img
with open('database/rgb_data/gelontoxon_data', 'wb') as data:
pickle.dump(pickle_dict, data)
print('>> pickle dumpling 완료 ! ')
if __name__ == '__main__':
path = '/home/kyh/dataset/gelontoxon/'
_load_data(path)
|
[
"pickle.dump",
"numpy.random.shuffle",
"ntpath.basename",
"cv2.cvtColor",
"numpy.asarray",
"os.walk",
"cv2.imread",
"os.path.join",
"cv2.resize"
] |
[((193, 206), 'os.walk', 'os.walk', (['path'], {}), '(path)\n', (200, 206), False, 'import pickle, os, ntpath, cv2\n'), ((324, 351), 'numpy.random.shuffle', 'np.random.shuffle', (['tot_list'], {}), '(tot_list)\n', (341, 351), True, 'import numpy as np\n'), ((747, 767), 'numpy.asarray', 'np.asarray', (['img_list'], {}), '(img_list)\n', (757, 767), True, 'import numpy as np\n'), ((394, 409), 'cv2.imread', 'cv2.imread', (['img'], {}), '(img)\n', (404, 409), False, 'import pickle, os, ntpath, cv2\n'), ((426, 472), 'cv2.resize', 'cv2.resize', (['image', '(192, 192)', 'cv2.INTER_CUBIC'], {}), '(image, (192, 192), cv2.INTER_CUBIC)\n', (436, 472), False, 'import pickle, os, ntpath, cv2\n'), ((489, 527), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2RGB'], {}), '(image, cv2.COLOR_BGR2RGB)\n', (501, 527), False, 'import pickle, os, ntpath, cv2\n'), ((920, 950), 'pickle.dump', 'pickle.dump', (['pickle_dict', 'data'], {}), '(pickle_dict, data)\n', (931, 950), False, 'import pickle, os, ntpath, cv2\n'), ((257, 281), 'os.path.join', 'os.path.join', (['root', 'file'], {}), '(root, file)\n', (269, 281), False, 'import pickle, os, ntpath, cv2\n'), ((555, 575), 'ntpath.basename', 'ntpath.basename', (['img'], {}), '(img)\n', (570, 575), False, 'import pickle, os, ntpath, cv2\n')]
|
import numpy as np
from . import _colormixer
from . import _histograms
import threading
from ...util import img_as_ubyte
# utilities to make life easier for plugin writers.
import multiprocessing
CPU_COUNT = multiprocessing.cpu_count()
class GuiLockError(Exception):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class WindowManager(object):
''' A class to keep track of spawned windows,
and make any needed callback once all the windows,
are closed.'''
def __init__(self):
self._windows = []
self._callback = None
self._callback_args = ()
self._callback_kwargs = {}
self._gui_lock = False
self._guikit = ''
def _check_locked(self):
if not self._gui_lock:
raise GuiLockError(\
'Must first acquire the gui lock before using this image manager')
def _exec_callback(self):
if self._callback:
self._callback(*self._callback_args, **self._callback_kwargs)
def acquire(self, kit):
if self._gui_lock:
raise GuiLockError(\
'The gui lock can only be acquired by one toolkit per session. \
The lock is already acquired by %s' % self._guikit)
else:
self._gui_lock = True
self._guikit = str(kit)
def _release(self, kit):
# releaseing the lock will lose all references to currently
# tracked images and the callback.
# this function is private for reason!
self._check_locked()
if str(kit) == self._guikit:
self._windows = []
self._callback = None
self._callback_args = ()
self._callback_kwargs = {}
self._gui_lock = False
self._guikit = ''
else:
raise RuntimeError('Only the toolkit that owns the lock may '
'release it')
def add_window(self, win):
self._check_locked()
self._windows.append(win)
def remove_window(self, win):
self._check_locked()
try:
self._windows.remove(win)
except ValueError:
print('Unable to find referenced window in tracked windows.')
print('Ignoring...')
else:
if len(self._windows) == 0:
self._exec_callback()
def register_callback(self, cb, *cbargs, **cbkwargs):
self._check_locked()
self._callback = cb
self._callback_args = cbargs
self._callback_kwargs = cbkwargs
def has_windows(self):
if len(self._windows) > 0:
return True
else:
return False
window_manager = WindowManager()
def prepare_for_display(npy_img):
'''Convert a 2D or 3D numpy array of any dtype into a
3D numpy array with dtype uint8. This array will
be suitable for use in passing to gui toolkits for
image display purposes.
Parameters
----------
npy_img : ndarray, 2D or 3D
The image to convert for display
Returns
-------
out : ndarray, 3D dtype=np.uint8
The converted image. This is guaranteed to be a contiguous array.
Notes
-----
If the input image is floating point, it is assumed that the data
is in the range of 0.0 - 1.0. No check is made to assert this
condition. The image is then scaled to be in the range 0 - 255
and then cast to np.uint8
For all other dtypes, the array is simply cast to np.uint8
If a 2D array is passed, the single channel is replicated
to the 2nd and 3rd channels.
If the array contains an alpha channel, this channel is
ignored.
'''
if npy_img.ndim < 2:
raise ValueError('Image must be 2D or 3D array')
height = npy_img.shape[0]
width = npy_img.shape[1]
out = np.empty((height, width, 3), dtype=np.uint8)
npy_img = img_as_ubyte(npy_img)
if npy_img.ndim == 2 or \
(npy_img.ndim == 3 and npy_img.shape[2] == 1):
npy_plane = npy_img.reshape((height, width))
out[:, :, 0] = npy_plane
out[:, :, 1] = npy_plane
out[:, :, 2] = npy_plane
elif npy_img.ndim == 3:
if npy_img.shape[2] == 3 or npy_img.shape[2] == 4:
out[:, :, :3] = npy_img[:, :, :3]
else:
raise ValueError('Image must have 1, 3, or 4 channels')
else:
raise ValueError('Image must have 2 or 3 dimensions')
return out
def histograms(image, nbins):
'''Calculate the channel histograms of the current image.
Parameters
----------
image : ndarray, ndim=3, dtype=np.uint8
Input image.
nbins : int
The number of bins.
Returns
-------
out : (rcounts, gcounts, bcounts, vcounts)
The binned histograms of the RGB channels and intensity values.
This is a NAIVE histogram routine, meant primarily for fast display.
'''
return _histograms.histograms(image, nbins)
class ImgThread(threading.Thread):
def __init__(self, func, *args):
super(ImgThread, self).__init__()
self.func = func
self.args = args
def run(self):
self.func(*self.args)
class ThreadDispatch(object):
def __init__(self, img, stateimg, func, *args):
height = img.shape[0]
self.cores = CPU_COUNT
self.threads = []
self.chunks = []
if self.cores == 1:
self.chunks.append((img, stateimg))
elif self.cores >= 4:
self.chunks.append((img[:(height // 4), :, :],
stateimg[:(height // 4), :, :]))
self.chunks.append((img[(height // 4):(height // 2), :, :],
stateimg[(height // 4):(height // 2), :, :]))
self.chunks.append((img[(height // 2):(3 * height // 4), :, :],
stateimg[(height // 2):(3 * height // 4), :, :]
))
self.chunks.append((img[(3 * height // 4):, :, :],
stateimg[(3 * height // 4):, :, :]))
# if they don't have 1, or 4 or more, 2 is good.
else:
self.chunks.append((img[:(height // 2), :, :],
stateimg[:(height // 2), :, :]))
self.chunks.append((img[(height // 2):, :, :],
stateimg[(height // 2):, :, :]))
for i in range(len(self.chunks)):
self.threads.append(ImgThread(func, self.chunks[i][0],
self.chunks[i][1], *args))
def run(self):
for t in self.threads:
t.start()
for t in self.threads:
t.join()
class ColorMixer(object):
''' a class to manage mixing colors in an image.
The input array must be an RGB uint8 image.
The mixer maintains an original copy of the image,
and uses this copy to query the pixel data for operations.
It also makes a copy for sharing state across operations.
That is, if you add to a channel, and multiply to same channel,
the two operations are carried separately and the results
averaged together.
it modifies your array in place. This ensures that if you
bust over a threshold, you can always come back down.
The passed values to a function are always considered
absolute. Thus to threshold a channel completely you
can do mixer.add(RED, 255). Or to double the intensity
of the blue channel: mixer.multiply(BLUE, 2.)
To reverse these operations, respectively:
mixer.add(RED, 0), mixer.multiply(BLUE, 1.)
The majority of the backend is implemented in Cython,
so it should be quite quick.
'''
RED = 0
GREEN = 1
BLUE = 2
valid_channels = [RED, GREEN, BLUE]
def __init__(self, img):
if type(img) != np.ndarray:
raise ValueError('Image must be a numpy array')
if img.dtype != np.uint8:
raise ValueError('Image must have dtype uint8')
if img.ndim != 3 or img.shape[2] != 3:
raise ValueError('Image must be 3 channel MxNx3')
self.img = img
self.origimg = img.copy()
self.stateimg = img.copy()
def get_stateimage(self):
return self.stateimg
def commit_changes(self):
self.stateimg[:] = self.img[:]
def revert(self):
self.stateimg[:] = self.origimg[:]
self.img[:] = self.stateimg[:]
def set_to_stateimg(self):
self.img[:] = self.stateimg[:]
def add(self, channel, ammount):
'''Add the specified ammount to the specified channel.
Parameters
----------
channel : flag
the color channel to operate on
RED, GREED, or BLUE
ammount : integer
the ammount of color to add to the channel,
can be positive or negative.
'''
if channel not in self.valid_channels:
raise ValueError('assert_channel is not a valid channel.')
pool = ThreadDispatch(self.img, self.stateimg,
_colormixer.add, channel, ammount)
pool.run()
def multiply(self, channel, ammount):
'''Mutliply the indicated channel by the specified value.
Parameters
----------
channel : flag
the color channel to operate on
RED, GREED, or BLUE
ammount : integer
the ammount of color to add to the channel,
can be positive or negative.
'''
if channel not in self.valid_channels:
raise ValueError('assert_channel is not a valid channel.')
pool = ThreadDispatch(self.img, self.stateimg,
_colormixer.multiply, channel, ammount)
pool.run()
def brightness(self, factor, offset):
'''Adjust the brightness off an image with an offset and factor.
Parameters
----------
offset : integer
The ammount to add to each channel.
factor : float
The factor to multiply each channel by.
result = clip((pixel + offset)*factor)
'''
pool = ThreadDispatch(self.img, self.stateimg,
_colormixer.brightness, factor, offset)
pool.run()
def sigmoid_gamma(self, alpha, beta):
pool = ThreadDispatch(self.img, self.stateimg,
_colormixer.sigmoid_gamma, alpha, beta)
pool.run()
def gamma(self, gamma):
pool = ThreadDispatch(self.img, self.stateimg,
_colormixer.gamma, gamma)
pool.run()
def hsv_add(self, h_amt, s_amt, v_amt):
'''Adjust the H, S, V channels of an image by a constant ammount.
This is similar to the add() mixer function, but operates over the
entire image at once. Thus all three additive values, H, S, V, must
be supplied simultaneously.
Parameters
----------
h_amt : float
The ammount to add to the hue (-180..180)
s_amt : float
The ammount to add to the saturation (-1..1)
v_amt : float
The ammount to add to the value (-1..1)
'''
pool = ThreadDispatch(self.img, self.stateimg,
_colormixer.hsv_add, h_amt, s_amt, v_amt)
pool.run()
def hsv_multiply(self, h_amt, s_amt, v_amt):
'''Adjust the H, S, V channels of an image by a constant ammount.
This is similar to the add() mixer function, but operates over the
entire image at once. Thus all three additive values, H, S, V, must
be supplied simultaneously.
Note that since hue is in degrees, it makes no sense to multiply
that channel, thus an add operation is performed on the hue. And the
values given for h_amt, should be the same as for hsv_add
Parameters
----------
h_amt : float
The ammount to to add to the hue (-180..180)
s_amt : float
The ammount to multiply to the saturation (0..1)
v_amt : float
The ammount to multiply to the value (0..1)
'''
pool = ThreadDispatch(self.img, self.stateimg,
_colormixer.hsv_multiply, h_amt, s_amt, v_amt)
pool.run()
def rgb_2_hsv_pixel(self, R, G, B):
'''Convert an RGB value to HSV
Parameters
----------
R : int
Red value
G : int
Green value
B : int
Blue value
Returns
-------
out : (H, S, V) Floats
The HSV values
'''
H, S, V = _colormixer.py_rgb_2_hsv(R, G, B)
return (H, S, V)
def hsv_2_rgb_pixel(self, H, S, V):
'''Convert an HSV value to RGB
Parameters
----------
H : float
Hue value
S : float
Saturation value
V : float
Intensity value
Returns
-------
out : (R, G, B) ints
The RGB values
'''
R, G, B = _colormixer.py_hsv_2_rgb(H, S, V)
return (R, G, B)
|
[
"numpy.empty",
"multiprocessing.cpu_count"
] |
[((210, 237), 'multiprocessing.cpu_count', 'multiprocessing.cpu_count', ([], {}), '()\n', (235, 237), False, 'import multiprocessing\n'), ((3854, 3898), 'numpy.empty', 'np.empty', (['(height, width, 3)'], {'dtype': 'np.uint8'}), '((height, width, 3), dtype=np.uint8)\n', (3862, 3898), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
feign blocks module
zs. elter, a. cserkaszky 2019
"""
import os
import math
import re
import numpy as np
import matplotlib.pyplot as plt
from feign.geometry import *
def isFloat(s):
try:
float(s)
return True
except ValueError:
return False
def readMu(path,column,energy):
"""The function to read attenuaton coefficients from XCOM datafiles.
Parameters
----------
path : str
path to the file (str)
column : int
column which contains the total attenuation coefficients in case more
columns are present in the file
energy : float or list of floats
energy or energies where the attenuation coefficient is needed.
Returns
-------
float or list of floats
the interpolated value(s) of the attenuaton coefficient.
"""
try:
inputfile=open(path,'r').readlines()
except FileNotFoundError:
inputfile=open(os.getcwd()+path,'r').readlines()
en=[]
mu=[]
for line in inputfile:
x=line.strip().split()
if len(x)>=1 and isFloat(x[0]):
en.append(float(x[0]))
mu.append(float(x[column]))
return np.interp(energy,en,mu)
def is_hex_color(input_string):
"""The function to assess whether a string is hex color description.
Taken from https://stackoverflow.com/questions/42876366/check-if-a-string-defines-a-color
Parameters
----------
input_string : str
String which may contain hex color description
Returns
-------
bool
True if the string is a hex format definition, False otherwise.
Examples
--------
>>> is_hex_color('notahex')
False
>>> is_hex_color('#FF0000')
True
"""
HEX_COLOR_REGEX = r'^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$'
regexp = re.compile(HEX_COLOR_REGEX)
if regexp.search(input_string):
return True
return False
def getID(nameKeyword, argList, keywordDict):
"""The function returns 1 string argument from a general list or arguments
The argument can be named with nameKeyword
Parameters
----------
nameKeyword : str
The keyword of the desired argument if named
argList : list
*args passed to this function
keywordDict : dict
**kwargs passed to this function
Returns
-------
str
The found string argument
"""
foundArg = None
if len(argList) == 1 and len(keywordDict) == 0:
foundArg = argList[0]
elif len(argList) == 0 and len(keywordDict) == 1 and nameKeyword in keywordDict:
foundArg = keywordDict[nameKeyword]
if foundArg is not None and isinstance(foundArg, str):
return foundArg
raise ValueError('expected 1 argument: '+nameKeyword+' string')
class Material(object):
"""A class used to represent a Material.
Parameters
----------
matID : str
ID of the material
Attributes
----------
matID : str
ID of the material
density : float
density of material in (g/cm3)
path : str
path to attenuation coefficient file
color : str
color of material when plotting
"""
_idName = 'matID'
def __init__(self, *args, **kwargs):
self._density = None
self._path = None
self._color = None
self._id = getID(self._idName, args, kwargs)
def __repr__(self):
return "Material(matID=%s)" % (self._id)
@property
def density(self):
return self._density
@property
def path(self):
return self._path
@property
def color(self):
return self._color
def set_density(self, density=None):
"""The function to set the density of the Material
Parameters
----------
density : float
density of material in g/cm2
"""
if isFloat(density):
self._density=density
else:
raise ValueError('density has to be float for Material ID="{}"'.format(self._id))
def set_path(self, path=None):
"""The function to set the path to the attenuation data of the Material.
Parameters
----------
path : tuple (str,int)
the path of the file, and the column which contains the data.
"""
if isinstance(path, tuple) and len(path)==2 and isinstance(path[0], str) and isinstance(path[1], int):
self._path=path
else:
raise ValueError(('Path has to be (str,int) tuple for Material ID="{}"'.format(self._id)))
def set_color(self, color=None):
"""The function to set the color of Material in case the geometry is plotted.
Parameters
----------
color : str
color of the material in hex format
"""
if isinstance(color, str) and is_hex_color(color):
self._color=color
else:
raise ValueError(('Color has to be hex str for Material ID="{}"'.format(self._id)))
class Pin(object):
"""A class used to represent a Pin.
With :meth:`Pin.add_region()` coaxial circles can be added to describe
the content (eg. fuel pellet, helium gap, clad).
In case no region is added, the Pin() object will behave as an empty channel
filled with the coolant material.
Parameters
----------
pinID : str
ID of the pin
Attributes
----------
pinID : str
ID of the pin
regions : list of tuples
(Material, radius) pairs to describe coaxial regions within pin, radius in cm.
materials : list of str
list of :attr:`Material.matID` identifiers within the pin
radii : list of floats
list of radii of regions within the pin, radii in cm
"""
_idName = 'pinID'
def __init__(self, *args, **kwargs):
self._regions=[]
self._materials=[]
self._radii=[]
self._id = getID(self._idName, args, kwargs)
def __repr__(self):
return "Pin(pinID=%s)" % (self._id)
@property
def regions(self):
return self._regions
@property
def materials(self):
return self._materials
@property
def radii(self):
return self._radii
def add_region(self,material=None,radius=None):
"""The function to add coaxial circles and rings to a pin.
In case of consecutive calls (ie. more regions added), the radii has to
increase.
Parameters
----------
material : Material
material filled into new region
radius :
radius of new region
Examples
--------
>>> uo2 = Material('1')
>>> he = Material('2')
>>> zr = Material('3')
>>> fuel = Pin('1')
>>> fuel.add_region(uo2,0.41)
>>> fuel.add_region(he,0.42)
>>> fuel.add_region(zr,0.48)
>>> fuel.regions
[(Material(matID=1), 0.41),
(Material(matID=2), 0.42),
(Material(matID=3), 0.48)]
"""
if isinstance(material,Material):
self._materials.append(material._id)
else:
raise TypeError('Material() object is expected')
if isFloat(radius):
if len(self._radii)>0 and self._radii[-1]>=radius:
raise ValueError('Radii are not increasing in pin #{}'.format(self._id))
else:
self._radii.append(radius)
self._regions.append((material,radius))
def checkArgvConsistency(*argv):
if len(argv) >= 2:
for arg in argv[1:]:
if not isinstance(arg, type(argv[0])):
raise TypeError('Inconsistent input objects: '+str(type(arg))+' != '+str(type(argv[0])))
def addIDsToDict(objectDict, *argv):
checkArgvConsistency(*argv)
#add new elements
for arg in argv:
if arg._id in objectDict:
raise ValueError('ID {} is duplicated'.format(arg._id))
else:
objectDict[arg._id]=arg
def delIDsFromDict(objectDict, *argv):
checkArgvConsistency(*argv)
for arg in argv:
if objectDict is None:
raise TypeError('No objects added yet.')
elif arg._id not in objectDict:
print('ID {} is not in dict yet'.format(arg._id))
else:
del objectDict[arg._id]
class Assembly(object):
"""A class used to represent a rectangular Assembly.
Parameters
----------
N : int
number of positions in y direction
M : int
number of positions in x direction
Attributes
----------
N : int
number of positions in y direction
M : int
number of positions in x direction
pitch : float
pitch size of the lattice in cm
pins: Pins()
pins in the assembly
fuelmap: 2D array
fuelmap to describe which pins are filled in the positions
coolant : str
matID of the coolant (ie. materal filled between pins)
pool : Rectangle() (optional)
pool in which the assembly is placed. Within the pool coolant material is
filled, outside the pool surrounding material is filled.
surrounding : str (mandatory if pool is present)
matID of the surrounding material (ie. material filled around pool)
source : list of str
:attr:`Material.matID` identifiers of material emitting gamma particles
"""
def __init__(self,N,M):
try:
self.N=int(N)
self.M=int(M)
except ValueError:
raise ValueError('N,M has to be decimal')
except TypeError:
raise TypeError('N,M has to be int')
self._pitch=None
self._pins=None
self._fuelmap=None
self._coolant=None
self._surrounding=None
self._source=None #TODO what if more materials emit from same pin?
self._pool=None
def __repr__(self):
return "Assembly(N=%d,M=%d)" % (self.N,self.M)
@property
def pitch(self):
return self._pitch
@property
def pool(self):
return self._pool
@property
def pins(self):
return self._pins
@property
def fuelmap(self):
return self._fuelmap
@property
def coolant(self):
return self._coolant
@property
def surrounding(self):
return self._surrounding
@property
def source(self):
return self._source
def set_pitch(self,pitch=None):
"""The function to set the pitch of the lattice of Assembly
Parameters
----------
pitch : float
pitch of lattice in cm
"""
if isFloat(pitch):
self._pitch=pitch
else:
raise TypeError('Pitch has to be float')
def set_pins(self,*argv):
"""The function to include Pin objects in an Assembly
Parameters
----------
*argv : Pin() or more Pin() objects
Pin() objects to be included in the Assembly
Examples
--------
>>> fuel=Pin('1')
>>> guide=Pin('2')
>>> assembly=Assembly(2,2)
>>> assembly.pins
>>> assembly.set_pins(fuel,guide)
>>> assembly.pins
{'1': Pin(pinID=1), '2': Pin(pinID=2)}
Raises
------
TypeError
if the parameter is not Pin()
ValueError
if the Pin is already included
"""
self._pins={}
self.add_pin(*argv)
def add_pin(self,*argv):
"""The function to add Pin objects to an Assembly, which may have
already included pins. If one wants to rewrite the existing pins,
then the :meth:`Assembly.set_pins()` has to be called.
Parameters
----------
*argv : Pin() or more Pin() objects
Pin() objects to be added in the Assembly
Examples
--------
>>> fuel=Pin('1')
>>> guide=Pin('2')
>>> assembly=Assembly(2,2)
>>> assembly.set_pins()
>>> assembly.pins
{}
>>> assembly.add_pin(fuel)
>>> assembly.add_pin(guide)
>>> assembly.pins
{'1': Pin(pinID=1), '2': Pin(pinID=2)}
Raises
------
TypeError
if the parameter is not Pin()
ValueError
if the Pin is already included
"""
if len(argv) > 0 and not isinstance(argv[0],Pin):
raise TypeError('Inputs need to be Pin() objects')
addIDsToDict(self.pins, *argv)
def remove_pin(self,*argv):
"""The function to remove Pin objects from an Assembly which
already has previously included pins.
Parameters
----------
*argv : Pin() or more Pin() objects
Pin() objects to be added in the Assembly
Examples
--------
>>> fuel=Pin('1')
>>> guide=Pin('2')
>>> assembly=Assembly(2,2)
>>> assembly.set_pins(fuel,guide)
>>> assembly.pins
{'1': Pin(pinID=1), '2': Pin(pinID=2)}
>>> assembly.remove_pin(guide)
>>> assembly.pins
{'1': Pin(pinID=1)}
>>> assembly.remove_pin(guide)
ID 2 is not in dict yet
Raises
------
TypeError
if the parameter is not Pin()
ValueError
if the Pin is already included
TypeError
if :attr:`pins` is None.
"""
if len(argv) > 0 and not isinstance(argv[0],Pin):
raise TypeError('Inputs need to be Pin() objects')
delIDsFromDict(self._pins, *argv)
def set_fuelmap(self,fuelmap=None):
"""The function to set the fuelmap of the Assembly
Parameters
----------
fuelmap : 2D array (NxM shape)
fuelmap of the lattice
Example
-------
>>> fuel=Pin('1')
>>> fuel.add_region(uo2,0.5)
>>> fuel.add_region(he,0.51)
>>> fuel.add_region(zr,0.61)
>>> fuelmap=[['1','1'],
['1','1']]
>>> assy=Assembly(2,2)
>>> assy.set_fuelmap(fuelmap)
"""
fuelmap=np.array(fuelmap)
if fuelmap.shape[0] != self.N or fuelmap.shape[1] != self.M:
raise ValueError('Fuelmap has wrong size')
else:
self._fuelmap=fuelmap
def set_coolant(self, coolant=None):
"""The function to set the coolant material in the Assembly
Parameters
----------
coolant : Material()
the coolant material
"""
if isinstance(coolant, Material):
self._coolant=coolant._id
else:
raise TypeError('Material() is expected')
def set_surrounding(self, surrounding=None):
"""The function to set the surrounding material around the Assembly
Parameters
----------
surrounding : Material()
the surrounding material
"""
if isinstance(surrounding, Material):
self._surrounding=surrounding._id
else:
raise TypeError('Material() is expected')
def set_source(self, *args):
"""The function to set the source material(s) in the Assembly
Parameters
----------
*args : Material() instances
the source material(s)
"""
self._source=[]
for arg in args:
if isinstance(arg,Material):
self._source.append(arg._id)
def set_pool(self,pool=None):
"""The function to set the pool around the Assembly
Parameters
----------
pool : Rectangle()
the shape of the pool
"""
if isinstance(pool,Rectangle):
self._pool=pool
else:
raise TypeError('Pool has to be a Rectangle() object')
def checkComplete(self):
"""
The function to check whether everything is defined correctly in an
Assembly() object. Prints messages indicating any problem.
- checks whether any attribute is not defined (pool does not need
to be defined)
- checks whether any pin contains any region with radius greater
than the pitch
- checks whether all the pins in the fuelmap are attributed to
the assembly
- in case a pool is defined, it is checked whether the pool is
around the assembly.
Returns
-------
bool
True if everything is correct and complete, False otherwise
"""
if self.pins is None or self.pitch is None or \
self.coolant is None or self.fuelmap is None or \
self.source is None:
print('ERROR: Assembly is not complete.')
return False
if False in [r<=self.pitch/2 for pin in self.pins.values() for r in pin._radii]:
print('ERROR: in a Pin() a radius is greater than the pitch')
return False
if [] in [pin._radii for pin in self.pins.values()]:
print('Warning: a pin has no regions, considered as coolant channel')
if False in [self.fuelmap[i][j] in self.pins for i in range(self.N) for j in range(self.M)]:
print('ERROR: Assembly().fuelmap contains pin not included in Assembly.Pins()')
return False
if self.pool is None:
print('Warning: no pool in the problem, the surrounding of the Assembly is filled with coolant material')
self._surrounding=self._coolant
return True
if self.surrounding is None:
print('ERROR: Surrounding material has to be defined if pool is defined')
return False
#Check that the pool is around the fuel assembly
pooldummy=Rectangle(Point(self.N*self.pitch/2,self.M*self.pitch/2),
Point(self.N*self.pitch/2,-self.M*self.pitch/2),
Point(-self.N*self.pitch/2,-self.M*self.pitch/2),
Point(-self.N*self.pitch/2,self.M*self.pitch/2))
for corner in [self.pool.p1,self.pool.p2,self.pool.p3,self.pool.p4]:
if pooldummy.encloses_point(corner): #TODO use corners
print('ERROR: Pool is inside fuel')
return False
if len(pooldummy.intersection(self.pool.p1p2))>1 or \
len(pooldummy.intersection(self.pool.p2p3))>1 or \
len(pooldummy.intersection(self.pool.p3p4))>1 or \
len(pooldummy.intersection(self.pool.p4p1))>1:
print('ERROR: Assembly does not fit in pool')
return False
return True
class Detector(object):
"""A class used to represent a Detector.
Parameters
----------
detID : str
ID of the detector
Attributes
----------
detID : str
ID of the detector
location : Point()
location of the detector
collimator : Collimator(), optional
Collimator placed between the source and the detector
"""
_idName = 'detID'
def __init__(self, *args, **kwargs):
self._location=None
self._collimator=None
self._id = getID(self._idName, args, kwargs)
def __repr__(self):
return "Detector(detID=%s)" % (self._id)
@property
def location(self):
return self._location
@property
def collimator(self):
return self._collimator
def set_location(self,location=None):
"""The function to set the location of Detector
Parameters
----------
location : Point()
location of the Detector
"""
if isinstance(location,Point):
self._location=location
else:
raise TypeError('Detector location has to be Point() object')
def set_collimator(self,collimator=None):
"""The function to set the Collimator of Detector
Parameters
----------
collimator : Collimator()
Collimator between source and Detector
"""
if isinstance(collimator,Collimator):
self._collimator=collimator
else:
raise TypeError('Collimator has to be Collimator() object')
class Absorber(object):
"""A class used to represent an Absorber.
An absorber can be thought of any element around (or within) the assembly,
which attenuates gamma radiation.
Parameters
----------
absID : str
ID of the absorber
Attributes
----------
absID : str
ID of the absorber
form : Rectangle() or Circle()
the shape of the absorber
material : str
matID of the Material the absorber is made of
accommat : str
matID of the Material the absorber is surrounded with (Note: the program
has no capabilities to decide which material is around the absorber, thus
the user has to set this)
"""
_idName = 'absID'
def __init__(self, *args, **kwargs):
self._form=None
self._material=None
self._accommat=None
self._id = getID(self._idName, args, kwargs)
def __repr__(self):
return "Absorber(absID=%s)" % (self._id)
@property
def form(self):
return self._form
@property
def material(self):
return self._material
@property
def accommat(self):
return self._accommat
def set_form(self,form=None):
"""The function to set the shape of Absorber
Parameters
----------
form : Rectangle() or Circle()
shape of the absorber
"""
if isinstance(form,Rectangle) or isinstance(form,Circle):
self._form=form
else:
raise TypeError('Absorber has to be a Rectangle or Circle object')
def set_material(self, material=None):
"""The function to set the material of Absorber
Parameters
----------
material : Material()
Material the Absorber is made of
"""
if isinstance(material, Material):
self._material=material._id
else:
raise TypeError('Material() is expected')
def set_accommat(self, accommat=None):
"""The function to set the accommodating material of Absorber
Parameters
----------
accommat : Material()
Material the Absorber is surrounded with.
"""
if isinstance(accommat, Material):
self._accommat=accommat._id
else:
raise TypeError('Material() is expected')
class Collimator(object):
"""A class used to represent a Collimator.
Any gamma ray not passing through the Collimator will be rejected. Collimators
have an impact only if they are attributed to Detector objects with
:meth:`Detector.set_collimator()`.
The front and the back of the collimator cannot intersect.
Parameters
----------
collID : str (optional)
ID of the collimator
Attributes
----------
collID : str (optional)
ID of the collimator
front : Segment()
First ppening of the collimator slit
back : Segment()
Second opening of the collimator slit
color : str
color of the collimator in case of plotting the geometry.
"""
_idName = 'collID'
def __init__(self, *args, **kwargs):
self._front=None
self._back=None
self._color=None
self._id = getID(self._idName, args, kwargs)
def __repr__(self):
return "Collimator()"
@property
def front(self):
return self._front
@property
def back(self):
return self._back
@property
def color(self):
return self._color
def set_front(self,front=None):
"""The function to set the front of the Collimator.
Intersecting front and back is not accepted.
Parameters
----------
front : Segment()
Opening of the collimator slit
Examples
----------
>>> c1=Collimator()
>>> c1.set_back(Segment(Point(0,0),Point(1,0)))
>>> c1.set_front(Segment(Point(0.5,-1),Point(0.5,1)))
ValueError('Collimator back and front should not intersect')
"""
if not isinstance(front,Segment):
raise TypeError('Collimator front has to be a Segment object')
if self._back is None:
self._front=front
elif len(self._back.intersection(front))>0:
raise ValueError('Collimator back and front should not intersect')
else:
self._front=front
def set_back(self,back=None):
"""The function to set the back of the Collimator.
Intersecting front and back is not accepted.
Parameters
----------
back : Segment()
Opening of the collimator slit
"""
if not isinstance(back,Segment):
raise TypeError('Collimator back has to be a Segment object')
if self._front is None:
self._back=back
elif len(self._front.intersection(back))>0:
raise ValueError('Collimator back and front should not intersect')
else:
self._back=back
def set_color(self, color=None):
"""The function to set the color of the Collimator in case of plotting.
Parameters
----------
color : str
color definition of Collimator in hex format.
"""
if isinstance(color, str) and is_hex_color(color):
self._color=color
else:
raise ValueError(('Color has to be hex str for Material ID="{}"'.format(self._id)))
class Experiment(object):
"""A class used to represent an Experiment. An experiment is a complete passive
gamma spectroscopy measurment setup with an assembly and detectors (absorbers
and collimators are optional).
Attributes
----------
assembly : Assembly()
The Assembly containing the source
pins : dict
Dictionary containing the available pin types.
materials : dict
Dictionary containing the available materials
detectors : dict
Dictionary containing the detectors in the problem
absorbers : dict, optional
Dictionary containing the absorbers in the problem
elines : list of float, optional
Energy lines (in MeV) at which the geometric efficiency is computed (in case missing,
only the distance travelled in various material is computed)
mu : dict
The total attenuation coefficients for all the energies in elines, and for
each material in the problem.
sourcePoints : list
List of pin-wise source point locations for each random sample.
dTmap : dict of dictionaries of 2D numpy arrays
The average distance travelled by a gamma-ray from a lattice position to a detector
given for each material in the problem. Outer keys are :attr:`Detector._id` identifiers,
inner keys are :attr:`Material._id` identifiers. It is an average of all
random samples (which are kept track in :attr:`Experiment.dTmaps`)
dTmapErr : dict of dictionaries of 2D numpy arrays
The standard deviation of distance travelled by a gamma-ray from a lattice position to a detector
given for each material in the problem. Outer keys are :attr:`Detector._id` identifiers,
inner keys are :attr:`Material._id` identifiers. It is an standard deviation of all
random samples (which are kept track in :attr:`Experiment.dTmaps`)
dTmaps : list of dictionaries of 2D numpy arrays
All random samples of distance travelled by a gamma-ray from a lattice position
to a detector. Source point for each sample are stored in :attr:`Experiment.sourcePoints`
contributionMap : dict
Dictionary to store the rod-wise contributions averaged over random samples
to each detector at each energy.
Outer keys are detector :attr:`Detector.detID` identifiers.
Inner keys are energy lines (as given in :meth:`Experiment.set_elines()`)
contributionMap[detID][eline] is an NxM shaped numpy array, where
N is :attr:`Assembly.N` and M is :attr:`Assembly.M`
contributionMapErr : dict
Dictionary to store the standard deviation of rod-wise contributions averaged over
random samples to each detector at each energy.
Outer keys are detector :attr:`Detector.detID` identifiers.
Inner keys are energy lines (as given in :meth:`Experiment.set_elines()`)
contributionMapErr[detID][eline] is an NxM shaped numpy array, where
N is :attr:`Assembly.N` and M is :attr:`Assembly.M`
contributionMaps : list
All random samples of contribution maps to each detector at each energy.
contributionMapAve : dict
Dictionary to store the rod-wise contribution averaged over all detectors at each energy
averaged over all random samples.
Keys are energy lines (as given in :meth:`Experiment.set_elines()`)
contributionMapAve[eline] is an NxM shaped numpy array, where
N is :attr:`Assembly.N` and M is :attr:`Assembly.M`
contributionMapAveErr : dict
Dictionary to store the standard deviation of the pin-wise contribution averaged over
all detectors at each energy averaged over all random samples.
Keys are energy lines (as given in :meth:`Experiment.set_elines()`)
contributionMapAveErr[eline] is an NxM shaped numpy array, where
N is :attr:`Assembly.N` and M is :attr:`Assembly.M`
contributionMapAves : list
All random samples of the pin-wise contribution averaged over
all detectors at each energy.
geomEff : dict
Dictionary to store the geometric efficiency at each detector location averaged over
each random sample.
Keys are detector :attr:`Detector._id` identifiers.
geomEff[detID] is E long numpy array, where E is the length of :attr:`Experiment.elines`
geomEffErr : dict
Dictionary to store the standard deviation of the geometric efficiency
at each detector location averaged over each random sample.
Keys are detector :attr:`Detector._id` identifiers.
geomEff[detID] is E long numpy array, where E is the length of :attr:`Experiment.elines`
geomEffs : list
All random samples of the geometric efficiency at each detector location.
geomEffAve : numpy.ndarray
Geometric efficiency of the Experiment averaged over all detectors averaged over each
random sample.
The length is of :attr:`Experiment.elines`
geomEffAveErr : numpy.ndarray
Standard deviation of the geometric efficiency of the Experiment averaged over all
detectors averaged over each random sample.
The length is of :attr:`Experiment.elines`
geomEffAves : list
All random samples of the geometric efficiency of the Experiment averaged over all
detectors.
output : str, optional
filename (and path) where to print the geometric efficiency
Note
----
While computing the travelled distance, if the ray does not pass through the
collimator, np.Inf is set in the given traveled distance map for the given position. This is useful,
because the the probability of travelling infinite distance is zero, thus in the related
contribution map, at the same location 0.0 will be found.
If the geometry is so that rays emitted from any location from a pin will not pass through
the collimator, than the mean traveled map (:attr:`Experiment.dTmap`) will have np.Inf at
that location (which is correct since the mean of many infinities is infinity) and the
the standard deviation will be 0.0 (which is again correct).
However, in cases when rays emitted from some location in a pin pass through the collimator, whereas
from some other locations in a pin they do not pass through, the mean traveled distance
(:attr:`Experiment.dTmap`) and the standard deviation of the travelled distance (:attr:`Experiment.dTmapErr`)
become meaningless at such pin positions. (This could be a situation when the collimator slit is
narrower than the size of the pins). The reason is that the mean of something and infinity will become
infinity as well. Also, for the standard deviation calculation the np.Inf values are set to 0.0,
otherwise the map location would be filled with NaN.
For these cases one might analyse the list of travelled distances (:attr:`Experiment.dTmap`) and
the list of source locations (:attr:`Experiment.sourcePoints`).
Nevertheless, the contribution maps and the geometric efficiency is correctly calculated even in
these situations!
Examples
--------
Examples of plotting attributes can be found at https://github.com/ezsolti/feign/blob/master/examples/ex1_2x2fuel.ipynb
"""
def __init__(self):
self._output=None
self._assembly=None
self._pins=None
self._materials=None
self._detectors=None
self._absorbers=None
self._elines=None
self._mu=None
self._sourcePoints=None
self._dTmap=None
self._dTmapErr=None
self._dTmaps=None
self._contributionMap=None
self._contributionMapErr=None
self._contributionMaps=None
self._contributionMapAve=None
self._contributionMapAveErr=None
self._contributionMapAves=None
self._geomEff=None
self._geomEffErr=None
self._geomEffs=None
self._geomEffAve=None
self._geomEffAveErr=None
self._geomEffAves=None
self._randomNum=1
def __repr__(self):
return "Experiment()"
@property
def output(self):
return self._output
@property
def assembly(self):
return self._assembly
@property
def materials(self):
return self._materials
@property
def pins(self):
return self._pins
@property
def detectors(self):
return self._detectors
@property
def absorbers(self):
return self._absorbers
@property
def elines(self):
return np.array(self._elines).astype(float) #TODO, i want the strings for later, but for plotting float is better. Is this a correct way to do it?
#probably not because I may want the strings in processing as well. but this can be done while processing
@property
def sourcePoints(self):
return self._sourcePoints
@property
def dTmap(self):
return self._dTmap
@property
def dTmapErr(self):
return self._dTmapErr
@property
def dTmaps(self):
return self._dTmaps
@property
def contributionMap(self):
return self._contributionMap
@property
def contributionMapErr(self):
return self._contributionMapErr
@property
def contributionMaps(self):
return self._contributionMaps
@property
def contributionMapAve(self):
return self._contributionMapAve
@property
def contributionMapAveErr(self):
return self._contributionMapAveErr
@property
def contributionMapAves(self):
return self._contributionMapAves
@property
def mu(self):
return self._mu
@property
def geomEff(self):
return self._geomEff
@property
def geomEffErr(self):
return self._geomEffErr
@property
def geomEffs(self):
return self._geomEffs
@property
def geomEffAve(self):
return self._geomEffAve
@property
def geomEffAveErr(self):
return self._geomEffAveErr
@property
def geomEffAves(self):
return self._geomEffAves
@property
def randomNum(self):
return self._randomNum
def set_random(self,randomNum=1):
"""The function to set number of random source locations per pin.
Parameters
----------
randomNum : int
number of random source locations in each pin.
"""
if isinstance(randomNum, int):
self._randomNum=randomNum
else:
raise TypeError('Has to be int')
def set_output(self,output='output.dat'):
"""The function to set the output file for printing the geometric efficiency
Parameters
----------
output : str
filename and path where to print the geometric efficiency.
"""
if isinstance(output, str):
self._output=output
else:
raise TypeError('Output filename has to be str')
def set_materials(self,*argv):
"""The function to include Material objects in an Experiment
Parameters
----------
*argv : Material() or more Material() objects
Material() objects to be included in the Experiment
Examples
--------
>>> uox=Material('1')
>>> zr=Material('2')
>>> experiment=Experiment()
>>> experiment.materials
>>> experiment.set_materials(uox,zr)
>>> experiment.materials
{'1': Material(matID=1), '2': Material(matID=2)}
Raises
------
TypeError
if the parameter is not Material()
ValueError
if the Material is already included
"""
self._materials={}
self.add_material(*argv)
def add_material(self,*argv):
"""The function to add Material objects to an Experiment, which may have
already included materials. If one wants to rewrite the existing materials,
then the :meth:`Experiment.set_materials()` has to be called.
Parameters
----------
*argv : Material() or more Material() objects
Material() objects to be added in the Experiment
Examples
--------
>>> uox=Material('1')
>>> zr=Material('2')
>>> experiment=Experiment()
>>> experiment.set_materials()
>>> experiment.materials
{}
>>> experiment.add_material(uox)
>>> experiment.add_material(zr)
>>> experiment.materials
{'1': Material(matID=1), '2': Material(matID=2)}
Raises
------
TypeError
if the parameter is not Material()
ValueError
if the Material is already included
"""
if len(argv) > 0 and not isinstance(argv[0],Material):
raise TypeError('Inputs need to be Material() objects')
addIDsToDict(self._materials, *argv)
def remove_material(self,*argv):
"""The function to remove Material objects from an Experiment which
already has previously included materials.
Parameters
----------
*argv : Material() or more Material() objects
Material() objects to be added in the Experiment
Examples
--------
>>> uox=Material('1')
>>> zr=Material('2')
>>> experiment=Experiment()
>>> experiment.set_materials(uox,zr)
>>> experiment.materials
{'1': Material(matID=1), '2': Material(matID=2)}
>>> experiment.remove_material(zr)
>>> experiment.materials
{'1': Material(matID=1)}
>>> experiment.remove_material(zr)
ID 2 is not in dict yet
Raises
------
TypeError
if the parameter is not Material()
TypeError
if :attr:`materials` is None.
"""
if len(argv) > 0 and not isinstance(argv[0],Material):
raise TypeError('Inputs need to be Material() objects')
delIDsFromDict(self._materials, *argv)
def set_absorbers(self,*argv):
"""The function to include Absorber objects in an Experiment
Parameters
----------
*argv : Absorber() or more Absorber() objects
Absorber() objects to be included in the Experiment
Examples
--------
>>> leadsheet=Absorber('leadsheet')
>>> alusheet=Absorber('alusheet')
>>> experiment=Experiment()
>>> experiment.absorbers
>>> experiment.set_absorbers(leadsheet,alusheet)
>>> experiment.absorbers
{'leadsheet': Absorber(absID=leadsheet), 'alusheet': Absorber(absID=alusheet)}
Raises
------
TypeError
if the parameter is not Absorber()
ValueError
if the Absorber is already included
"""
self._absorbers={}
self.add_absorber(*argv)
def add_absorber(self,*argv):
"""The function to add Absorber objects to an Experiment, which may have
already included absorbers. If one wants to rewrite the existing absorbers,
then the :meth:`Experiment.set_absorbers()` has to be called.
Parameters
----------
*argv : Absorber() or more Absorber() objects
Absorber() objects to be added in the Experiment
Examples
--------
>>> leadsheet=Absorber('leadsheet')
>>> alusheet=Absorber('alusheet')
>>> experiment=Experiment()
>>> experiment.set_absorbers()
>>> experiment.absorbers
{}
>>> experiment.add_absorber(leadsheet)
>>> experiment.add_absorber(alusheet)
>>> experiment.absorbers
{'leadsheet': Absorber(absID=leadsheet), 'alusheet': Absorber(absID=alusheet)}
Raises
------
TypeError
if the parameter is not Absorber()
ValueError
if the Absorber is already included
"""
if len(argv) > 0 and not isinstance(argv[0],Absorber):
raise TypeError('Inputs need to be Absorber() objects')
addIDsToDict(self._absorbers, *argv)
def remove_absorber(self,*argv):
"""The function to remove Absorber objects from an Experiment which
already has previously included absorbers.
Parameters
----------
*argv : Absorber() or more Absorber() objects
Absorber() objects to be added in the Experiment
Examples
--------
>>> leadsheet=Absorber('leadsheet')
>>> alusheet=Absorber('alusheet')
>>> experiment=Experiment()
>>> experiment.set_absorbers(leadsheet,alusheet)
>>> experiment.absorbers
{'leadsheet': Absorber(absID=leadsheet), 'alusheet': Absorber(absID=alusheet)}
>>> experiment.remove_absorber(alusheet)
>>> experiment.absorbers
{'leadsheet': Absorber(absID=leadsheet)}
>>> experiment.remove_absorber(alusheet)
ID alusheet is not in dict yet
Raises
------
TypeError
if the parameter is not Absorber()
TypeError
if :attr:`absorbers` is None.
"""
if len(argv) > 0 and not isinstance(argv[0],Absorber):
raise TypeError('Inputs need to be Absorber() objects')
delIDsFromDict(self._absorbers, *argv)
def set_detectors(self,*argv):
"""The function to include Detector objects in an Experiment
Parameters
----------
*argv : Detector() or more Detector() objects
Detector() objects to be included in the Experiment
Examples
--------
>>> F5=Detector('F5')
>>> F15=Detector('F15')
>>> experiment=Experiment()
>>> experiment.detectors
>>> experiment.set_detectors(F5,F15)
>>> experiment.detectors
{'F5': Detector(detID=F5), 'F15': Detector(detID=F15)}
Raises
------
TypeError
if the parameter is not Detector()
ValueError
if the Detector is already included
"""
self._detectors={}
self.add_detector(*argv)
def add_detector(self,*argv):
"""The function to add Detector objects to an Experiment, which may have
already included detectors. If one wants to rewrite the existing detectors,
then the :meth:`Experiment.set_detectors()` has to be called.
Parameters
----------
*argv : Detector() or more Detector() objects
Detector() objects to be added in the Experiment
Examples
--------
>>> F5=Detector('F5')
>>> F15=Detector('F15')
>>> experiment=Experiment()
>>> experiment.set_detectors()
>>> experiment.detectors
{}
>>> experiment.add_detector(F5)
>>> experiment.add_detector(F15)
>>> experiment.detectors
{'F5': Detector(detID=F5), 'F15': Detector(detID=F15)}
Raises
------
TypeError
if the parameter is not Detector()
ValueError
if the Detector is already included
"""
if len(argv) > 0 and not isinstance(argv[0],Detector):
raise TypeError('Inputs need to be Detector() objects')
addIDsToDict(self._detectors, *argv)
def remove_detector(self,*argv):
"""The function to remove Detector objects from an Experiment which
already has previously included detectors.
Parameters
----------
*argv : Detector() or more Detector() objects
Detector() objects to be added in the Experiment
Examples
--------
>>> F5=Detector('F5')
>>> F15=Detector('F15')
>>> experiment=Experiment()
>>> experiment.set_detectors(F5,F15)
>>> experiment.detectors
{'F5': Detector(detID=F5), 'F15': Detector(detID=F15)}
>>> experiment.remove_detector(F15)
>>> experiment.detectors
{'F5': Detector(detID=F5)}
>>> experiment.remove_detector(F15)
ID F15 is not in dict yet
Raises
------
TypeError
if the parameter is not Detector()
TypeError
if :attr:`detectors` is None.
"""
if len(argv) > 0 and not isinstance(argv[0],Detector):
raise TypeError('Inputs need to be Detector() objects')
delIDsFromDict(self._detectors, *argv)
def set_assembly(self,assembly=None):
"""The function to include Assembly in an Experiment
Parameters
----------
assembly : Assembly()
Assembly to be included in Experiment
"""
if isinstance(assembly,Assembly):
self._assembly=assembly
self._pins=self._assembly.pins
else:
raise ValueError('Assembly has to be an Assembly() object')
def set_elines(self,elines=None):
"""The function to set energy lines at which the geometric efficiency is
calculated
Parameters
----------
elines : list of str
Energy lines (in MeV) at which the geometric efficiency is calculated.
Note
----
values of elines are strings, because they will be keys of :attr:`mu`
"""
if isinstance(elines, list) and (False not in [isinstance(e, str) for e in elines]) and (False not in [isFloat(e) for e in elines]):
self._elines=elines
else:
raise ValueError('elines has to be a list of str MeV values')
def get_MuTable(self):
"""The function to create a nested dictionary to store the total
attenuation coefficients.
Returns
-------
dict
Dictionary to store the attenuation coefficients.
Outer keys are energies as defined in :attr:`elines`,
inner keys are :attr:`Material.matID` identifiers.
"""
mu={e: {m: 0 for m in self.materials} for e in self._elines}
for m in self.materials:
mum=readMu(self.materials[m].path[0],self.materials[m].path[1],self.elines)
for ei,mui in zip(self._elines,mum):
mu[ei][m]=mui
self._mu=mu
# OLD, nicer but more file reading.
# for e in self._elines:
# mu[e]={key: readMu(self.materials[key].path[0],self.materials[key].path[1],float(e)) for key in self.materials}
# self._mu=mu
def distanceTravelled(self,detector):
"""The function to calculate the distanced travelled in any material
by a gamma ray emitted from any pin positions of the Assembly to a detector
Parameters
----------
detector : Detector()
Returns
-------
dTmap : dict
The travelled distance in various materials. Keys are material identifiers,
values are pin-wise distance values.
sourcePoint : numpy array
Pin-wise source location in the given calculation.
"""
dTmap={key: np.zeros((self.assembly.N,self.assembly.M)) for key in self.materials}
#sourcePoint=np.array([[0 for i in range(self.assembly.N)] for j in range(self.assembly.M)])
sourcePoint=np.empty((self.assembly.N,self.assembly.M),dtype=object)
#create distance seen maps for each material
p=self.assembly.pitch/2
N=self.assembly.N
M=self.assembly.M
for i in range(N):
for j in range(M):
sourceIn=[s in self.pins[self.assembly.fuelmap[i][j]]._materials for s in self.assembly.source]
if True in sourceIn:
dT={key: 0 for key in self.materials} #dict to track distances travelled in each material for a given pin
#TODO get a random number is the source material?!
#if source is the inner most pin randomly center in circle
#else: randomly in that and reject the things within
if self.randomNum == 1:
centerSource=Point(-p*(M-1)+j*2*p,p*(N-1)-i*2*p)
else:
length = self.pins[self.assembly.fuelmap[i][j]]._radii[0]*np.sqrt(np.random.uniform(0, 1)) #TODO, if second ring is the source?
angle = np.pi * np.random.uniform(0, 2)
xnoise = length * np.cos(angle)
ynoise = length * np.sin(angle)
centerSource=Point(-p*(M-1)+j*2*p,p*(N-1)-i*2*p).translate(xnoise,ynoise)
sourcePoint[i][j]=centerSource
segmentSourceDetector=Segment(centerSource,detector.location)
#Only track rays which pass through the collimator
if detector.collimator is None or (len(detector.collimator.front.intersection(segmentSourceDetector))==1 and
len(detector.collimator.back.intersection(segmentSourceDetector))==1):
###Distances traveled in other pin positions
for ii in range(N):
for jj in range(M):
centerShield=Point(-p*(M-1)+jj*2*p,p*(N-1)-ii*2*p)
pinChannel=Rectangle(centerShield.translate(-p,p),centerShield.translate(p,p),
centerShield.translate(p,-p),centerShield.translate(-p,-p))
# print('------')
# print(pinChannel)
# print(segmentSourceDetector)
# print('------')
if len(pinChannel.intersection(segmentSourceDetector))>=1: #check only pins in between Source and Detector
if ii==i and jj==j: #pinChannel.encloses_point(centerSource): #in that case, only one intersection
Dprev=0
for r,mat in zip(self.pins[self.assembly.fuelmap[ii][jj]]._radii, self.pins[self.assembly.fuelmap[ii][jj]]._materials):
intersects = Circle(centerShield,r).intersection(segmentSourceDetector)
D=Point.distance(intersects[0],centerSource)
dT[mat]=dT[mat]+(D-Dprev)
Dprev=D
else:
Dprev=0
for r,mat in zip(self.pins[self.assembly.fuelmap[ii][jj]]._radii, self.pins[self.assembly.fuelmap[ii][jj]]._materials):
intersects = Circle(centerShield,r).intersection(segmentSourceDetector)
if len(intersects)>1: #if len()==1, it is tangent, no distance traveled
D=Point.distance(intersects[0],intersects[1])
dT[mat]=dT[mat]+(D-Dprev)
Dprev=D
###Distance traveled outside the pool = distance of ray-pool intersect and detector
if self.assembly.pool is not None:
dT[self.assembly.surrounding]=dT[self.assembly.surrounding]+Point.distance(self.assembly.pool.intersection(segmentSourceDetector)[0],detector.location)
###Distance traveled in coolantMat = total source-detector distance - everything else
dT[self.assembly.coolant]=dT[self.assembly.coolant]+Point.distance(centerSource,detector.location)-sum([dT[k] for k in dT.keys()]) #in case there is a ring filled with the coolent, eg an empty control rod guide, we need keep that
###Distance traveled in absorbers
###Absorber can be Circle() or Rectangular, the syntax
###is the same regarding .intersection(), thus the code
###handles both as it is.
for absorber in self.absorbers.values():
intersects=absorber.form.intersection(segmentSourceDetector)
if len(intersects)>1:
dabs=Point.distance(intersects[0],intersects[1])
elif len(intersects)==1: #if the detector or source is within absorber.
if absorber.form.encloses_point(detector.location):
dabs=Point.distance(intersects[0],detector.location)
elif absorber.form.encloses_point(centerSource):
dabs=Point.distance(intersects[0],centerSource)
print('Warning: absorber #%s is around source at %.2f,%.2f'%(absorber._id,centerSource.x,centerSource.y))
else:
raise ValueError('Ray has only one intersection with Absorber \n and the detector neither the source is enclosed by it.')
else:
dabs=0
dT[absorber.material]=dT[absorber.material]+dabs
dT[absorber.accommat]=dT[absorber.accommat]-dabs
#Update the map
for key in dT:
dTmap[key][i][j]=dT[key]
else: #not through collimator
for key in dT:
dTmap[key][i][j]=np.Inf
return dTmap, sourcePoint
def attenuation(self,dTmap,mue,detector,sourcePoint):
"""The function to calculate the pin-wise contribution to the detector
at a given energy. That is the probablity that a gamma-ray emitted from
a pin will reach the detector point.
Parameters
----------
dTmap : dict
The travelled distance in various materials. Keys are material identifiers,
values are pin-wise distance values. Shape as created by :meth:`Experiment.distanceTravelled()`
mue : dict
Total attenuation coefficients at the given energy. Keys are materials,
values are the total attenuation coefficient values.
detector : Detector()
sourcePoint : numpy array
Pin-wise source locations, as created by :meth:`Experiment.distanceTravelled()`.
Returns
-------
contribmap : numpy array
Pin-wise probabilities that a gamma-ray emitted from a given pin hits the detector.
"""
p=self.assembly.pitch/2
N=self.assembly.N
M=self.assembly.M
contribmap=np.zeros((N,M))
for i in range(N):
for j in range(M):
center=sourcePoint[i][j]
sourceIn=[s in self.pins[self.assembly.fuelmap[i][j]]._materials for s in self.assembly.source]
if True in sourceIn:
contrib=1 #TODO might be a place to include a pre-known emission weight map. Or to provide a function which multiplies the contribution with some weight matrix
for key in self.materials.keys():
contrib=contrib*math.exp(-1*mue[key]*dTmap[key][i][j])
contribmap[i][j]=contrib/(4*math.pi*(Point.distance(center,detector.location))**2)
return contribmap
def checkComplete(self):
"""Function to check whether everything is defined correctly in an
Experiment() object.
- checks whether assembly is complete
- checks whether any pin contains any region with radius greater than the pitch
- checks whether all the pins in the fuelmap are attributed to the assembly
- in case a pool is defined, it is checked whether the pool is around the assembly.
Returns
----------
bool
True if everything is correct and complete, False otherwise
"""
errors=[]
if self.materials is None:
print('ERROR: Materials are not defined')
return False #otherwise the following checks cannot be done.
if self.assembly is None:
print('ERROR: Assembly is missing')
errors.append(False)
else:
if not self.assembly.checkComplete():
errors.append(False)
else:
if False in [mat in self.materials for pin in self.pins.values() for mat in pin._materials]:
print('ERROR: pin material is missing from materials')
errors.append(False)
if False in [source in self.materials for source in self.assembly.source]:
print('ERROR: source material is not in Materials')
errors.append(False)
if self.detectors is None:
print('ERROR: no detector is defined.')
errors.append(False)
else:
if True in [det.location is None for det in self.detectors.values()]:
print('ERROR: Detector location is not defined')
errors.append(False)
if True in [det.collimator.back is None or det.collimator.front is None for det in self.detectors.values() if det.collimator is not None]:
print('ERROR: One collimator is not fully defined')
errors.append(False)
if self.absorbers is None:
self.set_absorbers()
print('No absorbers in the problem')
else:
if self.absorbers is not None and False in [absorber.material in self.materials for absorber in self.absorbers.values()]:
print('ERROR: absorber material is missing from materials')
errors.append(False)
if self.absorbers is not None and False in [absorber.accommat in self.materials for absorber in self.absorbers.values()]:
print('ERROR: Absorber accommodating material is missing from materials')
errors.append(False)
if self._elines is None:
print('Warning: elines missing; only distance travelled in various materials will be computed')
else:
if True in [mat.density is None for mat in self.materials.values()]:
print('ERROR: Material density is missing')
errors.append(False)
if True in [mat.path is None for mat in self.materials.values()]:
print('ERROR: Path for attenuation file missing')
errors.append(False)
if len(errors)!=0:
print('%d errors encountered.'%(len(errors)))
return False
return True
def Plot(self,out=None,dpi=600,xl=[-100,100],yl=[-100,100],detectorSize=0.4):
"""Function to plot the geometry of an Experiment() object.
The function will randomly set colors to Material() objects for which colors
were previously not defined.
Parameters
----------
out : str (default=None)
name of output file
dpi : int (default=600)
dpi of the saved plot
xl : list of float (default=[-100,100])
x-direction limits of region of the geometry to plot (in cm)
yl : list of float (default=[-100,100])
y-direction limits of region of the geometry to plot (in cm)
detectorSize : float (default=400)
radius of white circle to illustrate the detector points
"""
if self.checkComplete() is False:
raise ValueError('ERROR')
import random
for mat in self.materials:
if self.materials[mat].color is None:
self.materials[mat].set_color("#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)]))
pool=self.assembly.pool
N=self.assembly.N
M=self.assembly.M
p=self.assembly.pitch/2
fig, ax = plt.subplots()
ax.patch.set_facecolor(self.materials[self.assembly.surrounding].color)
if self.assembly.pool is not None:
pool=self.assembly.pool
polygon = plt.Polygon([[pool.p1.x,pool.p1.y],[pool.p2.x,pool.p2.y],[pool.p3.x,pool.p3.y],[pool.p4.x,pool.p4.y]], True,color=self.materials[self.assembly.coolant].color)
ax.add_artist(polygon)
#fuelmap
for i in range(N):
for j in range(M):
center=[-p*(M-1)+j*2*p,p*(N-1)-i*2*p]
for r,m in zip(reversed(self.pins[self.assembly.fuelmap[i][j]]._radii),reversed(self.pins[self.assembly.fuelmap[i][j]]._materials)):
circle1 = plt.Circle((center[0], center[1]), r, color=self.materials[m].color)
ax.add_artist(circle1)
for a in self.absorbers:
absorber=self.absorbers[a]
if isinstance(absorber.form,Rectangle):
polygon = plt.Polygon([[absorber.form.p1.x,absorber.form.p1.y],[absorber.form.p2.x,absorber.form.p2.y],[absorber.form.p3.x,absorber.form.p3.y],[absorber.form.p4.x,absorber.form.p4.y]], True,color=self.materials[absorber.material].color)
ax.add_artist(polygon)
else:
circle1 = plt.Circle((absorber.form.c.x,absorber.form.c.y),absorber.form.r,color=self.materials[absorber.material].color)
ax.add_artist(circle1)
for d in self.detectors:
circle1= plt.Circle((self.detectors[d].location.x,self.detectors[d].location.y),detectorSize,color='white')
ax.add_artist(circle1)
if self.detectors[d].collimator is not None:
if self.detectors[d].collimator.color is None:
self.detectors[d].collimator.set_color('#C2C5CC')
#the "orientation" of back and front is not know, so I plot two ways.
polygon=plt.Polygon([[self.detectors[d].collimator.front.p.x,self.detectors[d].collimator.front.p.y],[self.detectors[d].collimator.front.q.x, self.detectors[d].collimator.front.q.y],[self.detectors[d].collimator.back.p.x,self.detectors[d].collimator.back.p.y],[self.detectors[d].collimator.back.q.x,self.detectors[d].collimator.back.q.y]],True,color=self.detectors[d].collimator.color)
ax.add_artist(polygon)
polygon=plt.Polygon([[self.detectors[d].collimator.front.p.x,self.detectors[d].collimator.front.p.y],[self.detectors[d].collimator.front.q.x, self.detectors[d].collimator.front.q.y],[self.detectors[d].collimator.back.q.x,self.detectors[d].collimator.back.q.y],[self.detectors[d].collimator.back.p.x,self.detectors[d].collimator.back.p.y]],True,color=self.detectors[d].collimator.color)
ax.add_artist(polygon)
plt.xlim(xl[0],xl[1])
plt.ylim(yl[0],yl[1])
plt.gca().set_aspect('equal', adjustable='box')
if out is not None:
plt.savefig(out,dpi=dpi)
plt.show()
def Run(self):
"""The function to run an Experiment. It will update the dTmap, the
contributionMap and the geomEff attributes.
"""
if self.checkComplete() is False:
raise ValueError('ERROR')
sourceNorm=0
for i in range(self.assembly.N):
for j in range(self.assembly.M):
sourceIn=[s in self.pins[self.assembly.fuelmap[i][j]]._materials for s in self.assembly.source]
if True in sourceIn:
sourceNorm=sourceNorm+1
dTmaps=[]
contributionMaps=[]
contributionMapAves=[]
geomefficiencies=[]
geomefficiencyAves=[]
sourcePoints=[]
for k in range(self.randomNum):
print('#%d is being calculated'%(k)) #TODO RUN-ba
dTmap={}
for name in self.detectors:
print("Distance travelled to detector "+name+" is being calculated")
dTmap[name],sourcePoint=self.distanceTravelled(self.detectors[name])
dTmaps.append(dTmap)
sourcePoints.append(sourcePoint)
if self._elines is not None:
if k==0:
self.get_MuTable()
geomefficiency={}
geomefficiencyAve=np.zeros(len(self._elines))
contributionMapAve={e: np.zeros((self.assembly.N,self.assembly.M)) for e in self._elines}
contributionMap={}
for name in self.detectors:
print('Contribution to detector %s is calculated...'%(name))
contributionMap[name]={}
geomefficiency[name]=np.zeros(len(self._elines))
for e in self._elines:
print('...for gamma energy %s MeV'%(e))
mue=self._mu[e]
muem={key: mue[key]*self.materials[key].density for key in mue.keys()}
contributionMap[name][e]=self.attenuation(dTmap[name],muem,self.detectors[name],sourcePoint)
contributionMapAve[e]=contributionMapAve[e]+contributionMap[name][e]/len(self.detectors)
geomefficiency[name]=np.array([np.sum(contribution) for contribution in contributionMap[name].values()])/sourceNorm
geomefficiencyAve=geomefficiencyAve+geomefficiency[name]/len(self.detectors)
contributionMaps.append(contributionMap)
contributionMapAves.append(contributionMapAve)
geomefficiencies.append(geomefficiency)
geomefficiencyAves.append(geomefficiencyAve)
self._sourcePoints=sourcePoints
#Various Numpy manipulations to restructure the "plural" lists containing data for
#each random sample. Then the mean and the std of the "plural" lists is calculated.
#restructuring dTmaps: from the list of dictionaries, make a dictionary of lists
#then take the mean and std of the maps in the inner list
dTmapsRe={det: {mat: [dmap[det][mat] for dmap in dTmaps] for mat in self.materials} for det in self.detectors}
dTmap={} #will be the average
dTmapErr={} #will be the std
for det in dTmapsRe:
dTmap[det]={}
dTmapErr[det]={}
for mat in dTmapsRe[det]:
dTmapToAve=np.array([np.ravel(dT) for dT in dTmapsRe[det][mat]])
dTmap[det][mat]=np.mean(dTmapToAve,axis=0).reshape((self.assembly.N,self.assembly.M))
#dTmap elements may be np.Inf if the ray did not pass through the collimator
#this is useful to get 0 in attenuation() for those locations
#and it makes std calculation impossible, thus we set it to 0. see not in docstring!
dTmapToAve=np.where(dTmapToAve==np.Inf,0.0,dTmapToAve)
dTmapErr[det][mat]=np.std(dTmapToAve,axis=0).reshape((self.assembly.N,self.assembly.M))
self._dTmap=dTmap
self._dTmapErr=dTmapErr
self._dTmaps=dTmaps
if self._elines is not None:
#restructuring contributionMaps
contributionMapsRe={det: {e: [cmap[det][e] for cmap in contributionMaps] for e in self._elines} for det in self.detectors}
contributionMap={} #will be the average
contributionMapErr={} #will be the stdcontributionMapAves
for det in contributionMapsRe:
contributionMap[det]={}
contributionMapErr[det]={}
for e in contributionMapsRe[det]:
cMapToAve=np.array([np.ravel(cm) for cm in contributionMapsRe[det][e]])
contributionMap[det][e]=np.mean(cMapToAve,axis=0).reshape((self.assembly.N,self.assembly.M))
contributionMapErr[det][e]=np.std(cMapToAve,axis=0).reshape((self.assembly.N,self.assembly.M))
self._contributionMap=contributionMap
self._contributionMapErr=contributionMapErr
self._contributionMaps=contributionMaps
#restructuring contributionMapAves
contributionMapAvesRe={e: [cmap[e] for cmap in contributionMapAves] for e in self._elines}
contributionMapAve={} #will be the average
contributionMapAveErr={} #will be the std
for e in contributionMapAvesRe:
cMapToAve=np.array([np.ravel(cm) for cm in contributionMapAvesRe[e]])
contributionMapAve[e]=np.mean(cMapToAve,axis=0).reshape((self.assembly.N,self.assembly.M))
contributionMapAveErr[e]=np.std(cMapToAve,axis=0).reshape((self.assembly.N,self.assembly.M))
self._contributionMapAve=contributionMapAve
self._contributionMapAveErr=contributionMapAveErr
self._contributionMapAves=contributionMapAves
#restructuring geomefficiencies
geomefficienciesRe={det: [geff[det] for geff in geomefficiencies] for det in self._detectors}
geomefficiency={} #will be the average
geomefficiencyErr={} #will be the std
for det in geomefficienciesRe:
geffToAve=np.array([geff for geff in geomefficienciesRe[det]])
geomefficiency[det]=np.mean(geffToAve,axis=0)
geomefficiencyErr[det]=np.std(geffToAve,axis=0)
self._geomEff=geomefficiency
self._geomEffErr=geomefficiencyErr
self._geomEffs=geomefficiencies
#restructuring geomefficiencyAves
geomefficiencyAve=np.mean(np.array([geff for geff in geomefficiencyAves]),axis=0)
geomefficiencyAveErr=np.std(np.array([geff for geff in geomefficiencyAves]),axis=0)
self._geomEffAve=geomefficiencyAve
self._geomEffAveErr=geomefficiencyAveErr
self._geomEffAves=geomefficiencyAves
if self.output is not None:
output=open(self.output,'w')
for e,c in zip(self._elines,self._geomEffAve):
output.write(e+'\t'+str(c)+'\n')
output.close()
|
[
"numpy.sum",
"numpy.ravel",
"numpy.empty",
"numpy.mean",
"numpy.sin",
"matplotlib.pyplot.gca",
"numpy.interp",
"numpy.std",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.Circle",
"numpy.cos",
"matplotlib.pyplot.Polygon",
"re.compile",
"matplotlib.pyplot.xlim",
"numpy.random.uniform",
"math.exp",
"os.getcwd",
"numpy.zeros",
"random.choice",
"numpy.where",
"numpy.array",
"matplotlib.pyplot.savefig"
] |
[((1225, 1250), 'numpy.interp', 'np.interp', (['energy', 'en', 'mu'], {}), '(energy, en, mu)\n', (1234, 1250), True, 'import numpy as np\n'), ((1853, 1880), 're.compile', 're.compile', (['HEX_COLOR_REGEX'], {}), '(HEX_COLOR_REGEX)\n', (1863, 1880), False, 'import re\n'), ((14130, 14147), 'numpy.array', 'np.array', (['fuelmap'], {}), '(fuelmap)\n', (14138, 14147), True, 'import numpy as np\n'), ((48972, 49030), 'numpy.empty', 'np.empty', (['(self.assembly.N, self.assembly.M)'], {'dtype': 'object'}), '((self.assembly.N, self.assembly.M), dtype=object)\n', (48980, 49030), True, 'import numpy as np\n'), ((56869, 56885), 'numpy.zeros', 'np.zeros', (['(N, M)'], {}), '((N, M))\n', (56877, 56885), True, 'import numpy as np\n'), ((62164, 62178), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (62176, 62178), True, 'import matplotlib.pyplot as plt\n'), ((64939, 64961), 'matplotlib.pyplot.xlim', 'plt.xlim', (['xl[0]', 'xl[1]'], {}), '(xl[0], xl[1])\n', (64947, 64961), True, 'import matplotlib.pyplot as plt\n'), ((64969, 64991), 'matplotlib.pyplot.ylim', 'plt.ylim', (['yl[0]', 'yl[1]'], {}), '(yl[0], yl[1])\n', (64977, 64991), True, 'import matplotlib.pyplot as plt\n'), ((65120, 65130), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (65128, 65130), True, 'import matplotlib.pyplot as plt\n'), ((48780, 48824), 'numpy.zeros', 'np.zeros', (['(self.assembly.N, self.assembly.M)'], {}), '((self.assembly.N, self.assembly.M))\n', (48788, 48824), True, 'import numpy as np\n'), ((62360, 62535), 'matplotlib.pyplot.Polygon', 'plt.Polygon', (['[[pool.p1.x, pool.p1.y], [pool.p2.x, pool.p2.y], [pool.p3.x, pool.p3.y], [\n pool.p4.x, pool.p4.y]]', '(True)'], {'color': 'self.materials[self.assembly.coolant].color'}), '([[pool.p1.x, pool.p1.y], [pool.p2.x, pool.p2.y], [pool.p3.x,\n pool.p3.y], [pool.p4.x, pool.p4.y]], True, color=self.materials[self.\n assembly.coolant].color)\n', (62371, 62535), True, 'import matplotlib.pyplot as plt\n'), ((63639, 63744), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(self.detectors[d].location.x, self.detectors[d].location.y)', 'detectorSize'], {'color': '"""white"""'}), "((self.detectors[d].location.x, self.detectors[d].location.y),\n detectorSize, color='white')\n", (63649, 63744), True, 'import matplotlib.pyplot as plt\n'), ((65087, 65112), 'matplotlib.pyplot.savefig', 'plt.savefig', (['out'], {'dpi': 'dpi'}), '(out, dpi=dpi)\n', (65098, 65112), True, 'import matplotlib.pyplot as plt\n'), ((34198, 34220), 'numpy.array', 'np.array', (['self._elines'], {}), '(self._elines)\n', (34206, 34220), True, 'import numpy as np\n'), ((63124, 63372), 'matplotlib.pyplot.Polygon', 'plt.Polygon', (['[[absorber.form.p1.x, absorber.form.p1.y], [absorber.form.p2.x, absorber.\n form.p2.y], [absorber.form.p3.x, absorber.form.p3.y], [absorber.form.p4\n .x, absorber.form.p4.y]]', '(True)'], {'color': 'self.materials[absorber.material].color'}), '([[absorber.form.p1.x, absorber.form.p1.y], [absorber.form.p2.x,\n absorber.form.p2.y], [absorber.form.p3.x, absorber.form.p3.y], [\n absorber.form.p4.x, absorber.form.p4.y]], True, color=self.materials[\n absorber.material].color)\n', (63135, 63372), True, 'import matplotlib.pyplot as plt\n'), ((63434, 63553), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(absorber.form.c.x, absorber.form.c.y)', 'absorber.form.r'], {'color': 'self.materials[absorber.material].color'}), '((absorber.form.c.x, absorber.form.c.y), absorber.form.r, color=\n self.materials[absorber.material].color)\n', (63444, 63553), True, 'import matplotlib.pyplot as plt\n'), ((64073, 64482), 'matplotlib.pyplot.Polygon', 'plt.Polygon', (['[[self.detectors[d].collimator.front.p.x, self.detectors[d].collimator.\n front.p.y], [self.detectors[d].collimator.front.q.x, self.detectors[d].\n collimator.front.q.y], [self.detectors[d].collimator.back.p.x, self.\n detectors[d].collimator.back.p.y], [self.detectors[d].collimator.back.q\n .x, self.detectors[d].collimator.back.q.y]]', '(True)'], {'color': 'self.detectors[d].collimator.color'}), '([[self.detectors[d].collimator.front.p.x, self.detectors[d].\n collimator.front.p.y], [self.detectors[d].collimator.front.q.x, self.\n detectors[d].collimator.front.q.y], [self.detectors[d].collimator.back.\n p.x, self.detectors[d].collimator.back.p.y], [self.detectors[d].\n collimator.back.q.x, self.detectors[d].collimator.back.q.y]], True,\n color=self.detectors[d].collimator.color)\n', (64084, 64482), True, 'import matplotlib.pyplot as plt\n'), ((64514, 64923), 'matplotlib.pyplot.Polygon', 'plt.Polygon', (['[[self.detectors[d].collimator.front.p.x, self.detectors[d].collimator.\n front.p.y], [self.detectors[d].collimator.front.q.x, self.detectors[d].\n collimator.front.q.y], [self.detectors[d].collimator.back.q.x, self.\n detectors[d].collimator.back.q.y], [self.detectors[d].collimator.back.p\n .x, self.detectors[d].collimator.back.p.y]]', '(True)'], {'color': 'self.detectors[d].collimator.color'}), '([[self.detectors[d].collimator.front.p.x, self.detectors[d].\n collimator.front.p.y], [self.detectors[d].collimator.front.q.x, self.\n detectors[d].collimator.front.q.y], [self.detectors[d].collimator.back.\n q.x, self.detectors[d].collimator.back.q.y], [self.detectors[d].\n collimator.back.p.x, self.detectors[d].collimator.back.p.y]], True,\n color=self.detectors[d].collimator.color)\n', (64525, 64923), True, 'import matplotlib.pyplot as plt\n'), ((64999, 65008), 'matplotlib.pyplot.gca', 'plt.gca', ([], {}), '()\n', (65006, 65008), True, 'import matplotlib.pyplot as plt\n'), ((68975, 69022), 'numpy.where', 'np.where', (['(dTmapToAve == np.Inf)', '(0.0)', 'dTmapToAve'], {}), '(dTmapToAve == np.Inf, 0.0, dTmapToAve)\n', (68983, 69022), True, 'import numpy as np\n'), ((71332, 71384), 'numpy.array', 'np.array', (['[geff for geff in geomefficienciesRe[det]]'], {}), '([geff for geff in geomefficienciesRe[det]])\n', (71340, 71384), True, 'import numpy as np\n'), ((71421, 71447), 'numpy.mean', 'np.mean', (['geffToAve'], {'axis': '(0)'}), '(geffToAve, axis=0)\n', (71428, 71447), True, 'import numpy as np\n'), ((71486, 71511), 'numpy.std', 'np.std', (['geffToAve'], {'axis': '(0)'}), '(geffToAve, axis=0)\n', (71492, 71511), True, 'import numpy as np\n'), ((71740, 71787), 'numpy.array', 'np.array', (['[geff for geff in geomefficiencyAves]'], {}), '([geff for geff in geomefficiencyAves])\n', (71748, 71787), True, 'import numpy as np\n'), ((71836, 71883), 'numpy.array', 'np.array', (['[geff for geff in geomefficiencyAves]'], {}), '([geff for geff in geomefficiencyAves])\n', (71844, 71883), True, 'import numpy as np\n'), ((62862, 62930), 'matplotlib.pyplot.Circle', 'plt.Circle', (['(center[0], center[1])', 'r'], {'color': 'self.materials[m].color'}), '((center[0], center[1]), r, color=self.materials[m].color)\n', (62872, 62930), True, 'import matplotlib.pyplot as plt\n'), ((66495, 66539), 'numpy.zeros', 'np.zeros', (['(self.assembly.N, self.assembly.M)'], {}), '((self.assembly.N, self.assembly.M))\n', (66503, 66539), True, 'import numpy as np\n'), ((68530, 68542), 'numpy.ravel', 'np.ravel', (['dT'], {}), '(dT)\n', (68538, 68542), True, 'import numpy as np\n'), ((68606, 68633), 'numpy.mean', 'np.mean', (['dTmapToAve'], {'axis': '(0)'}), '(dTmapToAve, axis=0)\n', (68613, 68633), True, 'import numpy as np\n'), ((69055, 69081), 'numpy.std', 'np.std', (['dTmapToAve'], {'axis': '(0)'}), '(dTmapToAve, axis=0)\n', (69061, 69081), True, 'import numpy as np\n'), ((70566, 70578), 'numpy.ravel', 'np.ravel', (['cm'], {}), '(cm)\n', (70574, 70578), True, 'import numpy as np\n'), ((70654, 70680), 'numpy.mean', 'np.mean', (['cMapToAve'], {'axis': '(0)'}), '(cMapToAve, axis=0)\n', (70661, 70680), True, 'import numpy as np\n'), ((70764, 70789), 'numpy.std', 'np.std', (['cMapToAve'], {'axis': '(0)'}), '(cMapToAve, axis=0)\n', (70770, 70789), True, 'import numpy as np\n'), ((987, 998), 'os.getcwd', 'os.getcwd', ([], {}), '()\n', (996, 998), False, 'import os\n'), ((50100, 50123), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2)'], {}), '(0, 2)\n', (50117, 50123), True, 'import numpy as np\n'), ((50166, 50179), 'numpy.cos', 'np.cos', (['angle'], {}), '(angle)\n', (50172, 50179), True, 'import numpy as np\n'), ((50222, 50235), 'numpy.sin', 'np.sin', (['angle'], {}), '(angle)\n', (50228, 50235), True, 'import numpy as np\n'), ((57407, 57449), 'math.exp', 'math.exp', (['(-1 * mue[key] * dTmap[key][i][j])'], {}), '(-1 * mue[key] * dTmap[key][i][j])\n', (57415, 57449), False, 'import math\n'), ((69776, 69788), 'numpy.ravel', 'np.ravel', (['cm'], {}), '(cm)\n', (69784, 69788), True, 'import numpy as np\n'), ((69872, 69898), 'numpy.mean', 'np.mean', (['cMapToAve'], {'axis': '(0)'}), '(cMapToAve, axis=0)\n', (69879, 69898), True, 'import numpy as np\n'), ((69988, 70013), 'numpy.std', 'np.std', (['cMapToAve'], {'axis': '(0)'}), '(cMapToAve, axis=0)\n', (69994, 70013), True, 'import numpy as np\n'), ((49998, 50021), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1)'], {}), '(0, 1)\n', (50015, 50021), True, 'import numpy as np\n'), ((61974, 62007), 'random.choice', 'random.choice', (['"""0123456789ABCDEF"""'], {}), "('0123456789ABCDEF')\n", (61987, 62007), False, 'import random\n'), ((67359, 67379), 'numpy.sum', 'np.sum', (['contribution'], {}), '(contribution)\n', (67365, 67379), True, 'import numpy as np\n')]
|
import numpy as np
import numpy_financial as npf
import numpy.linalg as linalg
from datetime import date
from workalendar.america import Brazil
cal = Brazil()
class Titulos:
def __init__(self, taxa, start, end, c=0):
"""
:param fv: Face Value
:param c: coupon
:param start: settlement date
:param end: Maturity date
"""
self.fv = 1000
self.taxa = taxa
self.coupon = c
self.start = start
self.end = end
def ltn(self):
"""
:param taxa: taxa contratada
:param DU: Número de dias úteis
:return:
"""
DU = cal.get_working_days_delta(self.start, self.end)
# Lidando com possível erro de entrada do usuário
if self.taxa < 1:
taxa = self.taxa
elif self.taxa > 1:
taxa = self.taxa / 100
price = self.fv / (1 + taxa) ** (DU / 252)
return price
def ntn_f(self):
"""
compute log returns for each ticker.
parameters
----------
taxa : scalar
taxa contratada da ltn
DU: list
Dias úteis do pagamento de cada cupon
returns
-------
preço : escalar
preço de uma NTN-F
"""
taxa = self.taxa
# Lidando com possível erro de entrada do usuário
if taxa < 1:
taxa = taxa
elif taxa > 1:
taxa = taxa / 100
# O Valor de Face sempre será 1000
fv = 1000
#Solucionar para as datas gerando cupons
start = self.start
end_year = date(start.year, 12, 31)
start_next_year = date(start.year + 1, 1, 1)
maturity = self.end
#days é o restante do ano e days2 o restante do contrato após o ano seguinte
days = cal.get_working_days_delta(start, end_year)
days2 = cal.get_working_days_delta(start_next_year, maturity)
if days < 252 / 2:
coupon = 1
else:
coupon = 2
number_coupons = int((days2 / 252) * 2) + coupon
# Criamos uma np.array para facilitar manipulação
DU = np.zeros(number_coupons)
for i in range(1, number_coupons):
DU[0] = days
DU[i] = DU[i - 1] + 252 / 2
# O valor do cupom é fixo e é melhor aproximado por essa conta
c = fv * ((1 + 0.1) ** (1 / 2) - 1)
# Manipulação para a criação do fluxo de caixa
terminal = fv + c
fluxo_caixa = np.full(len(DU), fill_value=c)
fluxo_caixa[-1] = terminal
dcf = np.full(len(DU), fill_value=taxa)
price = sum(fluxo_caixa / (1 + dcf) ** (DU / 252))
return price
def ntn_b_principal(self, VNA, IPCA):
"""
Essa função retorna o preço de uma NTN-B
:param taxa: Na hora da negociação
:param VNA: VNA na hora da negociação
:param DU = Dias úteis até o vencimento
:param IPCA: IPCA projetado. Deve estar em percentual
:param date: Data em que a negociação será feita
:return: preço da NTN-B
"""
DU = self.end - self.start
DU = DU.days
my_date = self.start
taxa = self.taxa
# Lidando com possível erro de entrada do usuário
if taxa < 1:
taxa = taxa
elif taxa > 1:
taxa = taxa / 100
IPCA = IPCA / 100
# Lidando com o tempo e seus casos extremos
# Esse é um ponto crítico no cálculo da NTN-B
if my_date.month == 1:
last = datetime.date(my_date.year - 1, 12, 15)
else:
last = datetime.date(my_date.year, my_date.month - 1, 15)
if my_date.day < 15:
this_month = datetime.date(my_date.year, my_date.month, 15)
else:
this_month = my_date
if my_date.month == 12:
next_month = datetime.date(my_date.year + 1, 1, 15)
else:
next_month = datetime.date(my_date.year, my_date.month + 1, 15)
# A partir daqui come;a o real cálculo da ntn-b
# Se o cálculo é para o DIA 15, o VNA náo precisa ser calculado
if my_date.day == 15:
VNA_p = VNA
else:
pr = (my_date - last) / (next_month - this_month)
VNA_p = VNA * (1 + IPCA) ** (pr)
#Calculando a cotação
cotacao = 1 / (1 + taxa) ** (DU / 252)
#preço de compra da NTN-B
valor = VNA_p * cotacao
return valor
def ntn_b(self, VNA, DU, IPCA, date):
"""
Essa função retorna o preço de uma NTN-B
:param taxa: Na hora da negociação
:param VNA: VNA na hora da negociação
:param DU = Lista de dias úteis de cada cupom
:param IPCA: IPCA projetado. Deve estar em percentual
:param date: Data em que a negociação será feita
:return: preço da NTN-B
"""
taxa = self.taxa
# Lidando com possível erro de entrada do usuário
if taxa < 1:
taxa = taxa
elif taxa > 1:
taxa = taxa / 100
# Criamos uma np.array para facilitar manipulação
DU = np.array(DU)
# Temos que normalizar o IPCa
IPCA = IPCA / 100
# Lidando com o tempo e seus casos extremos
# Esse é um ponto crítico no cálculo da NTN-B
my_date = date
if my_date.month == 1:
last = datetime.date(my_date.year - 1, 12, 15)
else:
last = datetime.date(my_date.year, my_date.month - 1, 15)
if my_date.day < 15:
this_month = datetime.date(my_date.year, my_date.month, 15)
else:
this_month = my_date
if my_date.month == 12:
next_month = datetime.date(my_date.year + 1, 1, 15)
else:
next_month = datetime.date(my_date.year, my_date.month + 1, 15)
# A partir daqui começa o real cálculo da ntn-b
pr = (my_date - last) / (next_month - this_month)
# Calculando e controlando o VNA projetado
if my_date.day == 15:
VNA_p = VNA
else:
VNA_p = VNA * (1 + IPCA) ** (pr)
#Calculando a cotação que inclui os cupons
c = ((1 + 0.06) ** (1 / 2) - 1)
terminal = 1
fluxo_caixa = np.full(len(DU), fill_value=c)
fluxo_caixa[-1] = fluxo_caixa[-1] + terminal
dcf = np.full(len(DU), fill_value=taxa)
cotacao = sum(fluxo_caixa / (1 + dcf) ** (DU / 252))
#preço de compra da NTN-B
valor_final = VNA_p * cotacao
return valor_final
def lft(self, taxa, DU, VNA, selic):
"""
Retorna o preço de compra de uma LFT
:param taxa: taxa contratada com ágio ou deságio
:param DU: dias úteis
:param VNA: VNA corrigido pela SELIC
:param selic: Taxa Selic projetada e anualizada
:return:
"""
if selic < 1:
selic = selic
elif taxa > 1:
selic = selic / 100
VNA_p = VNA * (1 + selic) ** (1 / 252)
cotacao = 1 / (1 + taxa) ** (DU / 252)
return VNA_p * cotacao
def bondPrice(self, ttm: int , ytm):
"""
param:
ttm = Time to maturity
ytm = Yield to Maturity
"""
c = self.coupon
fv = self.fv
cashFlow = []
if c < 0:
c = c
else:
c = c/100
if ytm < 0:
ytm = ytm
else:
ytm = ytm/100
[cashFlow.append((fv*c)/(1+ytm)**(i)) for i in range(1,ttm)]
cashFlow.append((fv+(fv*c))/(1+ytm)**(ttm))
price = sum(cashFlow)
return price
def ytm(self, r):
"""
This function return the prices of each path.
:param fv: Bonds Face Value
:param rates: a list of interest rates
:param c: coupon rate
:return: Bond Yield to Maturity and Price
"""
#Setting ttm = Time to maturity
ttm = len(r)
fv = self.fv
c = self.coupon
if c > 1:
c = c/100
else:
c = c
ttm1 = ttm-1
#Creating a coupon array
cashF = np.array([fv*c]*ttm1)
cashF = np.append(cashF,(fv*c)+fv)
#Create a array with zeros to fill with discounted factors
dcf = np.zeros(ttm, dtype=np.double)
for i in range(0,ttm):
dcf[i] = cashF[i] * (1/(1+r[i])**(i+1))
# Fiding prices
price = np.sum(dcf)
#Creating cash flow structure to calculate YTM
cashF = np.insert(cashF, 0, -price)
ytm = npf.irr(cashF)
Bond_Characteristics = { "Bond price": price,
"Bond Yield":round(ytm*100, 3),
}
return Bond_Characteristics
def bondPriceElasticity(self, rates, delta):
"""
:param fv: Bonds Face Value
:param rates: a list of interest rates
:param c: coupon rate
:param delta: change in Yield to Maturity
:return: Bond Yield to Maturity and Price
"""
fv = self.fv
c = self.coupon
ttm = len(rates)
values = ytm(rates)
price = values['Bond price']
rates = np.array(rates)
rates = rates*(1/100)
c = c/100
delta = delta/100
ttm1 = ttm-1
cashF = np.vstack([fv*c]*ttm1)
cashF = np.append(cashF,(fv*c)+fv)
dcf = np.array([])
for i in range(0,ttm):
dcf = np.append(dcf,cashF[i]*(i+1)/(1+rates[i])**(i+2) )
pe_factor = np.sum(dcf)
b = -1/price
price_elasticity = b*pe_factor
delta_bond = -price*abs(price_elasticity)*delta
bond_elasticity = {'Bond Price': price,
'Bond new price': price+delta_bond,
'Bond Elasticity':price_elasticity,
'Price Change': delta_bond,
}
return bond_elasticity
def convexity(self, r):
"""
param:
fv = Face Value
ttm = Time to maturity
c = coupon
ytm = Yield to Maturity
"""
fv = self.fv
c = self.coupon
ytm = ytm(r)
ttm = len(r)
price = bondPrice(fv, ttm, c, ytm)
c = c/100
ytm = ytm/100
x = []
[x.append((fv*c)/(1+ytm)**(i)) for i in range(1,ttm)]
x.append((fv+(fv*c))/(1+ytm)**(ttm))
y = []
[y.append(x[i] * (i+1) * (i+2) ) for i in range(0,ttm)]
dfc = sum(y)
cx = (dfc*0.5)/(((1+ytm)**2)*price)
return cx
def mac_mod_cx_duration(self, r):
"""
param:
fv = Face Value
ttm = Time to maturity; If the bond is a perpetuity, ttm =0
c = coupon
ytm = Yield to Maturity
"""
fv = self.fv
c = self.coupon
ytm = ytm(r)
ttm = len(r)
price = bondPrice(fv, ttm, c, ytm)
cx = convexity(fv,ttm,c, ytm)
c = c/100
ytm = ytm/100
x =[]
if ttm == 0:
modD = 1/ytm
D = modD*(1+ytm)
else:
if c == 0:
D = ttm
else:
[x.append((fv*c)/(1+ytm)**(i) *i) for i in range(1,ttm)]
x.append((fv+(fv*c))/(1+ytm)**(ttm) * ttm)
d = sum(x)
D = d/price
modD = D/(1+ytm)
bond_cara = {'Price': price,
'Bond Macauly Duration':D,
'Modified Duration': modD,
'Convexity': cx,
}
return bond_cara
def bondRisk(self, r, delta):
"""
param:
fv = Face Value
ttm = Time to maturity; If the bond is a perpetuity, ttm =0
c = coupon
ytm = Yield to Maturity
delta = change in yield to maturity
"""
fv = self.fv
ttm = len(r)
c = self.coupon
ytm = ytm(r)
delta = delta/100
values = mac_mod_cx_duration(fv,ttm,c,ytm)
price = values['Price']
D = values['Bond Macauly Duration']
modD = values['Modified Duration']
cx = values['Convexity']
"""Now we calculate the change in price of this bond.
delta_price = is the approximation only with modifie duration
delta_price2 = is the approximation with modifie duration and convexity
"""
delta_price = -price*modD*delta
delta_price2 = price*(-modD*delta + cx*delta**2)
""" Now we use the change to see what is the new price in these two cases. l
"""
newprice = price + delta_price
newprice2 = price + delta_price2
bond_risks = {'Bond Macauly Duration':D,
'Bond Modified Duration':modD,
'first order change in price': delta_price,
'Second order change in price':delta_price2,
'Original Price':price,
'New price Mod Duration': newprice,
'New price Mod and Convexity': newprice2,
}
return bond_risks
def arbitrageEstrategy(fv, price, c, ttm):
"""
param:
fv = Face Value
ttm = List with Time to Maturity.
c = List with Coupon interest;
ytm = List with Yield to Maturity.
"""
price = np.array(price)
price = price * (-1)
fv = np.array(fv)
c = np.array(c)
c = c/100
ttm = np.array(ttm)
# The shape of the Matrix. This will depend of the bond with the higher time to maturity.
mformat = np.max(ttm)
ttmz = ttm-1
# Manipulação das constantes para a estratégia
cons = np.array([])
len = mformat
cons = np.vstack([0]*(len))
cons = np.insert(cons, 0, 100)
#creating a Matrix
Matrix = np.zeros((price.size, mformat))
# Setting the Matrix
#Setting the o coupon bonds
for i in range(0, price.size):
if (c[i] == 0):
Matrix[i][ttmz[i]] = fv
else:
pass
#Setting the coupon payment
for i in range(0, price.size):
if (np.max(Matrix[i][:]) == 0):
for j in range(0, mformat):
Matrix[i][j] = (fv*c[i])
#Setting the principal payment
for i in range(0, price.size):
for j in range(0, mformat):
if(c[i] != 0 and j == ttmz[i]):
Matrix[i][j] = fv+(fv*c[i])
#Cleaning the Matrix
for i in range(0, price.size):
for j in range(0, mformat):
if(c[i] != 0 and j > ttmz[i]):
Matrix[i][j] = 0
#Get together prices array and matrix
matrix = np.column_stack((price, Matrix))
#Transposing the Matrix
matrix = np.transpose(matrix)
#Solving the Matrix. Maybe another function for non-quadratic matrix
answer = linalg.solve(matrix, cons)
return answer
|
[
"workalendar.america.Brazil",
"numpy.sum",
"numpy_financial.irr",
"numpy.zeros",
"datetime.date",
"numpy.transpose",
"numpy.insert",
"numpy.append",
"numpy.max",
"numpy.array",
"numpy.column_stack",
"numpy.linalg.solve",
"numpy.vstack"
] |
[((150, 158), 'workalendar.america.Brazil', 'Brazil', ([], {}), '()\n', (156, 158), False, 'from workalendar.america import Brazil\n'), ((1621, 1645), 'datetime.date', 'date', (['start.year', '(12)', '(31)'], {}), '(start.year, 12, 31)\n', (1625, 1645), False, 'from datetime import date\n'), ((1672, 1698), 'datetime.date', 'date', (['(start.year + 1)', '(1)', '(1)'], {}), '(start.year + 1, 1, 1)\n', (1676, 1698), False, 'from datetime import date\n'), ((2159, 2183), 'numpy.zeros', 'np.zeros', (['number_coupons'], {}), '(number_coupons)\n', (2167, 2183), True, 'import numpy as np\n'), ((5156, 5168), 'numpy.array', 'np.array', (['DU'], {}), '(DU)\n', (5164, 5168), True, 'import numpy as np\n'), ((8190, 8215), 'numpy.array', 'np.array', (['([fv * c] * ttm1)'], {}), '([fv * c] * ttm1)\n', (8198, 8215), True, 'import numpy as np\n'), ((8228, 8257), 'numpy.append', 'np.append', (['cashF', '(fv * c + fv)'], {}), '(cashF, fv * c + fv)\n', (8237, 8257), True, 'import numpy as np\n'), ((8338, 8368), 'numpy.zeros', 'np.zeros', (['ttm'], {'dtype': 'np.double'}), '(ttm, dtype=np.double)\n', (8346, 8368), True, 'import numpy as np\n'), ((8493, 8504), 'numpy.sum', 'np.sum', (['dcf'], {}), '(dcf)\n', (8499, 8504), True, 'import numpy as np\n'), ((8577, 8604), 'numpy.insert', 'np.insert', (['cashF', '(0)', '(-price)'], {}), '(cashF, 0, -price)\n', (8586, 8604), True, 'import numpy as np\n'), ((8619, 8633), 'numpy_financial.irr', 'npf.irr', (['cashF'], {}), '(cashF)\n', (8626, 8633), True, 'import numpy_financial as npf\n'), ((9239, 9254), 'numpy.array', 'np.array', (['rates'], {}), '(rates)\n', (9247, 9254), True, 'import numpy as np\n'), ((9366, 9392), 'numpy.vstack', 'np.vstack', (['([fv * c] * ttm1)'], {}), '([fv * c] * ttm1)\n', (9375, 9392), True, 'import numpy as np\n'), ((9405, 9434), 'numpy.append', 'np.append', (['cashF', '(fv * c + fv)'], {}), '(cashF, fv * c + fv)\n', (9414, 9434), True, 'import numpy as np\n'), ((9446, 9458), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (9454, 9458), True, 'import numpy as np\n'), ((9579, 9590), 'numpy.sum', 'np.sum', (['dcf'], {}), '(dcf)\n', (9585, 9590), True, 'import numpy as np\n'), ((13415, 13430), 'numpy.array', 'np.array', (['price'], {}), '(price)\n', (13423, 13430), True, 'import numpy as np\n'), ((13474, 13486), 'numpy.array', 'np.array', (['fv'], {}), '(fv)\n', (13482, 13486), True, 'import numpy as np\n'), ((13499, 13510), 'numpy.array', 'np.array', (['c'], {}), '(c)\n', (13507, 13510), True, 'import numpy as np\n'), ((13544, 13557), 'numpy.array', 'np.array', (['ttm'], {}), '(ttm)\n', (13552, 13557), True, 'import numpy as np\n'), ((13675, 13686), 'numpy.max', 'np.max', (['ttm'], {}), '(ttm)\n', (13681, 13686), True, 'import numpy as np\n'), ((13779, 13791), 'numpy.array', 'np.array', (['[]'], {}), '([])\n', (13787, 13791), True, 'import numpy as np\n'), ((13829, 13849), 'numpy.vstack', 'np.vstack', (['([0] * len)'], {}), '([0] * len)\n', (13838, 13849), True, 'import numpy as np\n'), ((13865, 13888), 'numpy.insert', 'np.insert', (['cons', '(0)', '(100)'], {}), '(cons, 0, 100)\n', (13874, 13888), True, 'import numpy as np\n'), ((13934, 13965), 'numpy.zeros', 'np.zeros', (['(price.size, mformat)'], {}), '((price.size, mformat))\n', (13942, 13965), True, 'import numpy as np\n'), ((14860, 14892), 'numpy.column_stack', 'np.column_stack', (['(price, Matrix)'], {}), '((price, Matrix))\n', (14875, 14892), True, 'import numpy as np\n'), ((14943, 14963), 'numpy.transpose', 'np.transpose', (['matrix'], {}), '(matrix)\n', (14955, 14963), True, 'import numpy as np\n'), ((15059, 15085), 'numpy.linalg.solve', 'linalg.solve', (['matrix', 'cons'], {}), '(matrix, cons)\n', (15071, 15085), True, 'import numpy.linalg as linalg\n'), ((9508, 9570), 'numpy.append', 'np.append', (['dcf', '(cashF[i] * (i + 1) / (1 + rates[i]) ** (i + 2))'], {}), '(dcf, cashF[i] * (i + 1) / (1 + rates[i]) ** (i + 2))\n', (9517, 9570), True, 'import numpy as np\n'), ((14272, 14292), 'numpy.max', 'np.max', (['Matrix[i][:]'], {}), '(Matrix[i][:])\n', (14278, 14292), True, 'import numpy as np\n')]
|
# Plot (and write to table?) autocorrelation and ESS for samplers with different
# stepsizes on some standard functions (no noise?). See also MCMCVisualizer
# plots and pymc3 plots.
# Plot the following:
# vs NUTS with different initial stepsizes
# vs HMC with different initial stepsizes
# vs SGHMC with different initial stepsizes
# vs SGLD with different initial stepsizes
# other plots definitely should go in appendix unless they have some super-unexpected results
# => show table with all results (what is a reasonable table format?)
# List of samplers:
# - SGHMC (sgmcmc, theano) [x]
# - SGHMCHD (pysgmcmc, keras) [x]
# - SGLD (pysgmcmc, tensorflow) [x] <- from tensorflow_probability
# - HMC(pymc3) [x]
# - NUTS (pymc3, pymc3) <- compare to NUTS here as well! [x]
# - slice/metropolis (pymc3) [x]
# Left to add:
# - SVGD (?)
# - RelSGHMC (re-implement as optimizer in pysgmcmc)
# -
import sys
from os.path import dirname, join as path_join
sys.path.insert(0, path_join(dirname(__file__), ".."))
sys.path.insert(0, path_join(dirname(__file__), "robo"))
sys.path.insert(0, path_join(dirname(__file__), "pysgmcmc_development"))
import numpy as np
from keras import backend as K
from collections import OrderedDict
from itertools import islice, product
from pysgmcmc.diagnostics import PYSGMCMCTrace
from pysgmcmc.samplers.energy_functions import (
to_negative_log_likelihood,
Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC,
StandardNormal,
Donut, Squiggle,
)
from pysgmcmc.samplers.sghmc import SGHMCSampler
from pysgmcmc.samplers.sghmchd import SGHMCHDSampler
from pysgmcmc.samplers.sgld import SGLDSampler
from pysgmcmc_experiments.experiment_wrapper import to_experiment
import pymc3 as pm
import dill
# XXX: Handle variable naming properly.
EXPERIMENT_NAME = "energy_functions"
def init_hmc(model, stepsize, init="jitter+adapt_diag", chains=1):
from pymc3.step_methods.hmc import quadpotential
if init == 'jitter+adapt_diag':
start = []
for _ in range(chains):
mean = {var: val.copy() for var, val in model.test_point.items()}
for val in mean.values():
val[...] += 2 * np.random.rand(*val.shape) - 1
start.append(mean)
mean = np.mean([model.dict_to_array(vals) for vals in start], axis=0)
var = np.ones_like(mean)
potential = quadpotential.QuadPotentialDiagAdapt(
model.ndim, mean, var, 10)
return pm.step_methods.HamiltonianMC(
step_scale=stepsize,
potential=potential,
path_length=1
)
else:
raise NotImplementedError()
ENERGY_FUNCTIONS = OrderedDict((
("banana",
(Banana(), lambda: [K.random_normal_variable(mean=0., scale=1., shape=(1,)),
K.random_normal_variable(mean=0., scale=1., shape=(1,))])),
("gmm1",
(Gmm1(), lambda: [K.variable(K.random_normal((1,)), name="x", dtype=K.floatx())],)),
("gmm2", (
Gmm2(),
lambda: [K.variable(K.random_normal((1,)), name="x", dtype=K.floatx())],
)),
("gmm3",
(Gmm3(), lambda: [K.variable(K.random_normal((1,)), name="x", dtype=K.floatx())],)
),
("mogl2hmc",
(MoGL2HMC(), lambda: [K.variable(K.random_normal((1,)), name="x", dtype=K.floatx())],)
),
("standard_normal",
(StandardNormal(), lambda: [K.variable(K.random_normal((1,)), name="x", dtype=K.floatx())],)
),
("donut",
(Donut(), lambda: [K.random_normal_variable(mean=0., scale=1., shape=(1,)),
K.random_normal_variable(mean=0., scale=1., shape=(1,))])),
("squiggle",
(Squiggle(), lambda: [K.random_normal_variable(mean=0., scale=1., shape=(1,)),
K.random_normal_variable(mean=0., scale=1., shape=(1,))])),
))
PYMC3_SAMPLERS = ("NUTS", "HMC", "Metropolis", "Slice",)
SAMPLERS = OrderedDict((
("SGHMC", SGHMCSampler),
("SGHMCHD", SGHMCHDSampler),
("SGLD", SGLDSampler),
("NUTS", pm.step_methods.NUTS),
("HMC", pm.step_methods.HamiltonianMC),
("Metropolis", pm.step_methods.Metropolis),
("Slice", pm.step_methods.Slice),
))
STEPSIZES = tuple((
1e-12, 1e-10, 1e-8, 1e-6, 1e-4, 1e-2, 0.25, 0.5, 1.0,
))
CONFIGURATIONS = [
{"energy_function": energy_function, "sampler": sampler, "stepsize": stepsize}
for energy_function, sampler, stepsize in
product(ENERGY_FUNCTIONS, SAMPLERS, STEPSIZES)
if sampler not in ("Metropolis", "Slice")
]
CONFIGURATIONS.extend([
{"energy_function": energy_function, "sampler": sampler, "stepsize": None}
for energy_function, sampler in
product(ENERGY_FUNCTIONS, ("Metropolis", "Slice"))
])
def get_trace(sampler, stepsize, energy_function, _run, burn_in_steps=3000, sampling_steps=10 ** 4, num_chains=10):
energy_function_, initial_guess = ENERGY_FUNCTIONS[energy_function]
initial_sample = initial_guess()
sampler_cls = SAMPLERS[sampler]
if sampler in PYMC3_SAMPLERS:
def draw_trace(chain_id):
with pm.Model() as model:
energy_function_.to_pymc3()
if sampler == "NUTS":
from pymc3.sampling import init_nuts
start, step = init_nuts(
init="auto",
n_init=200000,
model=model,
progressbar=True
)
trace = pm.sample(
sampling_steps,
tune=burn_in_steps,
step=step,
chains=1,
chain_idx=chain_id,
start=start,
discard_tuned_samples=False
)
elif sampler == "HMC":
step = init_hmc(stepsize=stepsize, model=model)
trace = pm.sample(sampling_steps, tune=burn_in_steps, step=step, chains=1, discard_tuned_samples=False, chain_idx=chain_id)
else:
step = SAMPLERS[sampler]()
trace = pm.sample(
sampling_steps,
tune=burn_in_steps,
step=step,
chains=1,
chain_idx=chain_id,
discard_tuned_samples=False
)
return trace
def combine_traces(multitraces):
base_trace = multitraces[0]
for multitrace in multitraces[1:]:
for chain, strace in multitrace._straces.items():
if chain in base_trace._straces:
raise ValueError("Chains are not unique.")
base_trace._straces[chain] = strace
return base_trace
multitrace = combine_traces(
[draw_trace(chain_id=chain_id) for chain_id in range(num_chains)]
)
else:
def loss_for(sampler, energy_function):
def loss_fun(sample):
loss_tensor = to_negative_log_likelihood(energy_function)(sample)
for param in sample:
param.hypergradient = K.gradients(loss_tensor, param)
return loss_tensor
return loss_fun
def draw_chain():
loss = loss_for(sampler_cls, energy_function_)(initial_sample)
sampler_ = sampler_cls(params=initial_sample, loss=loss, lr=stepsize)
samples = np.asarray([
sample for _, sample in islice(sampler_, burn_in_steps + sampling_steps)
])
if np.isnan(samples).any():
print("Had nans.. iterating")
return draw_chain()
return np.squeeze(samples, 2)
multitrace = pm.backends.base.MultiTrace([PYSGMCMCTrace(draw_chain(), chain_id=id) for id in range(num_chains)])
output_filename = path_join(
dirname(__file__),
"../results/{}/{}/trace.pkl".format(EXPERIMENT_NAME, _run._id)
)
with open(output_filename, "wb") as trace_buffer:
dill.dump(multitrace, trace_buffer)
return True
experiment = to_experiment(
experiment_name=EXPERIMENT_NAME,
function=get_trace,
configurations=CONFIGURATIONS,
)
|
[
"pymc3.sample",
"pysgmcmc.samplers.energy_functions.Gmm1",
"numpy.isnan",
"numpy.random.rand",
"os.path.dirname",
"keras.backend.random_normal_variable",
"itertools.product",
"pymc3.step_methods.HamiltonianMC",
"pymc3.sampling.init_nuts",
"pysgmcmc.samplers.energy_functions.MoGL2HMC",
"keras.backend.gradients",
"pysgmcmc.samplers.energy_functions.Donut",
"numpy.ones_like",
"pymc3.Model",
"pysgmcmc.samplers.energy_functions.Squiggle",
"keras.backend.random_normal",
"itertools.islice",
"numpy.squeeze",
"dill.dump",
"pysgmcmc_experiments.experiment_wrapper.to_experiment",
"pysgmcmc.samplers.energy_functions.Banana",
"keras.backend.floatx",
"pysgmcmc.samplers.energy_functions.to_negative_log_likelihood",
"pysgmcmc.samplers.energy_functions.Gmm2",
"pymc3.step_methods.hmc.quadpotential.QuadPotentialDiagAdapt",
"pysgmcmc.samplers.energy_functions.Gmm3",
"collections.OrderedDict",
"pysgmcmc.samplers.energy_functions.StandardNormal"
] |
[((3859, 4112), 'collections.OrderedDict', 'OrderedDict', (["(('SGHMC', SGHMCSampler), ('SGHMCHD', SGHMCHDSampler), ('SGLD', SGLDSampler\n ), ('NUTS', pm.step_methods.NUTS), ('HMC', pm.step_methods.\n HamiltonianMC), ('Metropolis', pm.step_methods.Metropolis), ('Slice',\n pm.step_methods.Slice))"], {}), "((('SGHMC', SGHMCSampler), ('SGHMCHD', SGHMCHDSampler), ('SGLD',\n SGLDSampler), ('NUTS', pm.step_methods.NUTS), ('HMC', pm.step_methods.\n HamiltonianMC), ('Metropolis', pm.step_methods.Metropolis), ('Slice',\n pm.step_methods.Slice)))\n", (3870, 4112), False, 'from collections import OrderedDict\n'), ((8152, 8253), 'pysgmcmc_experiments.experiment_wrapper.to_experiment', 'to_experiment', ([], {'experiment_name': 'EXPERIMENT_NAME', 'function': 'get_trace', 'configurations': 'CONFIGURATIONS'}), '(experiment_name=EXPERIMENT_NAME, function=get_trace,\n configurations=CONFIGURATIONS)\n', (8165, 8253), False, 'from pysgmcmc_experiments.experiment_wrapper import to_experiment\n'), ((983, 1000), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (990, 1000), False, 'from os.path import dirname, join as path_join\n'), ((1038, 1055), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (1045, 1055), False, 'from os.path import dirname, join as path_join\n'), ((1095, 1112), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (1102, 1112), False, 'from os.path import dirname, join as path_join\n'), ((2312, 2330), 'numpy.ones_like', 'np.ones_like', (['mean'], {}), '(mean)\n', (2324, 2330), True, 'import numpy as np\n'), ((2351, 2414), 'pymc3.step_methods.hmc.quadpotential.QuadPotentialDiagAdapt', 'quadpotential.QuadPotentialDiagAdapt', (['model.ndim', 'mean', 'var', '(10)'], {}), '(model.ndim, mean, var, 10)\n', (2387, 2414), False, 'from pymc3.step_methods.hmc import quadpotential\n'), ((2444, 2534), 'pymc3.step_methods.HamiltonianMC', 'pm.step_methods.HamiltonianMC', ([], {'step_scale': 'stepsize', 'potential': 'potential', 'path_length': '(1)'}), '(step_scale=stepsize, potential=potential,\n path_length=1)\n', (2473, 2534), True, 'import pymc3 as pm\n'), ((4366, 4412), 'itertools.product', 'product', (['ENERGY_FUNCTIONS', 'SAMPLERS', 'STEPSIZES'], {}), '(ENERGY_FUNCTIONS, SAMPLERS, STEPSIZES)\n', (4373, 4412), False, 'from itertools import islice, product\n'), ((7927, 7944), 'os.path.dirname', 'dirname', (['__file__'], {}), '(__file__)\n', (7934, 7944), False, 'from os.path import dirname, join as path_join\n'), ((8085, 8120), 'dill.dump', 'dill.dump', (['multitrace', 'trace_buffer'], {}), '(multitrace, trace_buffer)\n', (8094, 8120), False, 'import dill\n'), ((4605, 4655), 'itertools.product', 'product', (['ENERGY_FUNCTIONS', "('Metropolis', 'Slice')"], {}), "(ENERGY_FUNCTIONS, ('Metropolis', 'Slice'))\n", (4612, 4655), False, 'from itertools import islice, product\n'), ((7740, 7762), 'numpy.squeeze', 'np.squeeze', (['samples', '(2)'], {}), '(samples, 2)\n', (7750, 7762), True, 'import numpy as np\n'), ((2679, 2687), 'pysgmcmc.samplers.energy_functions.Banana', 'Banana', ([], {}), '()\n', (2685, 2687), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((2859, 2865), 'pysgmcmc.samplers.energy_functions.Gmm1', 'Gmm1', ([], {}), '()\n', (2863, 2865), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((2966, 2972), 'pysgmcmc.samplers.energy_functions.Gmm2', 'Gmm2', ([], {}), '()\n', (2970, 2972), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((3082, 3088), 'pysgmcmc.samplers.energy_functions.Gmm3', 'Gmm3', ([], {}), '()\n', (3086, 3088), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((3195, 3205), 'pysgmcmc.samplers.energy_functions.MoGL2HMC', 'MoGL2HMC', ([], {}), '()\n', (3203, 3205), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((3319, 3335), 'pysgmcmc.samplers.energy_functions.StandardNormal', 'StandardNormal', ([], {}), '()\n', (3333, 3335), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((3439, 3446), 'pysgmcmc.samplers.energy_functions.Donut', 'Donut', ([], {}), '()\n', (3444, 3446), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((3621, 3631), 'pysgmcmc.samplers.energy_functions.Squiggle', 'Squiggle', ([], {}), '()\n', (3629, 3631), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((5008, 5018), 'pymc3.Model', 'pm.Model', ([], {}), '()\n', (5016, 5018), True, 'import pymc3 as pm\n'), ((5202, 5270), 'pymc3.sampling.init_nuts', 'init_nuts', ([], {'init': '"""auto"""', 'n_init': '(200000)', 'model': 'model', 'progressbar': '(True)'}), "(init='auto', n_init=200000, model=model, progressbar=True)\n", (5211, 5270), False, 'from pymc3.sampling import init_nuts\n'), ((5418, 5550), 'pymc3.sample', 'pm.sample', (['sampling_steps'], {'tune': 'burn_in_steps', 'step': 'step', 'chains': '(1)', 'chain_idx': 'chain_id', 'start': 'start', 'discard_tuned_samples': '(False)'}), '(sampling_steps, tune=burn_in_steps, step=step, chains=1,\n chain_idx=chain_id, start=start, discard_tuned_samples=False)\n', (5427, 5550), True, 'import pymc3 as pm\n'), ((7047, 7090), 'pysgmcmc.samplers.energy_functions.to_negative_log_likelihood', 'to_negative_log_likelihood', (['energy_function'], {}), '(energy_function)\n', (7073, 7090), False, 'from pysgmcmc.samplers.energy_functions import to_negative_log_likelihood, Banana, Gmm1, Gmm2, Gmm3, MoGL2HMC, StandardNormal, Donut, Squiggle\n'), ((7178, 7209), 'keras.backend.gradients', 'K.gradients', (['loss_tensor', 'param'], {}), '(loss_tensor, param)\n', (7189, 7209), True, 'from keras import backend as K\n'), ((7613, 7630), 'numpy.isnan', 'np.isnan', (['samples'], {}), '(samples)\n', (7621, 7630), True, 'import numpy as np\n'), ((2158, 2184), 'numpy.random.rand', 'np.random.rand', (['*val.shape'], {}), '(*val.shape)\n', (2172, 2184), True, 'import numpy as np\n'), ((2698, 2755), 'keras.backend.random_normal_variable', 'K.random_normal_variable', ([], {'mean': '(0.0)', 'scale': '(1.0)', 'shape': '(1,)'}), '(mean=0.0, scale=1.0, shape=(1,))\n', (2722, 2755), True, 'from keras import backend as K\n'), ((2780, 2837), 'keras.backend.random_normal_variable', 'K.random_normal_variable', ([], {'mean': '(0.0)', 'scale': '(1.0)', 'shape': '(1,)'}), '(mean=0.0, scale=1.0, shape=(1,))\n', (2804, 2837), True, 'from keras import backend as K\n'), ((3457, 3514), 'keras.backend.random_normal_variable', 'K.random_normal_variable', ([], {'mean': '(0.0)', 'scale': '(1.0)', 'shape': '(1,)'}), '(mean=0.0, scale=1.0, shape=(1,))\n', (3481, 3514), True, 'from keras import backend as K\n'), ((3538, 3595), 'keras.backend.random_normal_variable', 'K.random_normal_variable', ([], {'mean': '(0.0)', 'scale': '(1.0)', 'shape': '(1,)'}), '(mean=0.0, scale=1.0, shape=(1,))\n', (3562, 3595), True, 'from keras import backend as K\n'), ((3642, 3699), 'keras.backend.random_normal_variable', 'K.random_normal_variable', ([], {'mean': '(0.0)', 'scale': '(1.0)', 'shape': '(1,)'}), '(mean=0.0, scale=1.0, shape=(1,))\n', (3666, 3699), True, 'from keras import backend as K\n'), ((3726, 3783), 'keras.backend.random_normal_variable', 'K.random_normal_variable', ([], {'mean': '(0.0)', 'scale': '(1.0)', 'shape': '(1,)'}), '(mean=0.0, scale=1.0, shape=(1,))\n', (3750, 3783), True, 'from keras import backend as K\n'), ((5872, 5991), 'pymc3.sample', 'pm.sample', (['sampling_steps'], {'tune': 'burn_in_steps', 'step': 'step', 'chains': '(1)', 'discard_tuned_samples': '(False)', 'chain_idx': 'chain_id'}), '(sampling_steps, tune=burn_in_steps, step=step, chains=1,\n discard_tuned_samples=False, chain_idx=chain_id)\n', (5881, 5991), True, 'import pymc3 as pm\n'), ((6085, 6204), 'pymc3.sample', 'pm.sample', (['sampling_steps'], {'tune': 'burn_in_steps', 'step': 'step', 'chains': '(1)', 'chain_idx': 'chain_id', 'discard_tuned_samples': '(False)'}), '(sampling_steps, tune=burn_in_steps, step=step, chains=1,\n chain_idx=chain_id, discard_tuned_samples=False)\n', (6094, 6204), True, 'import pymc3 as pm\n'), ((7533, 7581), 'itertools.islice', 'islice', (['sampler_', '(burn_in_steps + sampling_steps)'], {}), '(sampler_, burn_in_steps + sampling_steps)\n', (7539, 7581), False, 'from itertools import islice, product\n'), ((2887, 2908), 'keras.backend.random_normal', 'K.random_normal', (['(1,)'], {}), '((1,))\n', (2902, 2908), True, 'from keras import backend as K\n'), ((3002, 3023), 'keras.backend.random_normal', 'K.random_normal', (['(1,)'], {}), '((1,))\n', (3017, 3023), True, 'from keras import backend as K\n'), ((3110, 3131), 'keras.backend.random_normal', 'K.random_normal', (['(1,)'], {}), '((1,))\n', (3125, 3131), True, 'from keras import backend as K\n'), ((3227, 3248), 'keras.backend.random_normal', 'K.random_normal', (['(1,)'], {}), '((1,))\n', (3242, 3248), True, 'from keras import backend as K\n'), ((3357, 3378), 'keras.backend.random_normal', 'K.random_normal', (['(1,)'], {}), '((1,))\n', (3372, 3378), True, 'from keras import backend as K\n'), ((2926, 2936), 'keras.backend.floatx', 'K.floatx', ([], {}), '()\n', (2934, 2936), True, 'from keras import backend as K\n'), ((3041, 3051), 'keras.backend.floatx', 'K.floatx', ([], {}), '()\n', (3049, 3051), True, 'from keras import backend as K\n'), ((3149, 3159), 'keras.backend.floatx', 'K.floatx', ([], {}), '()\n', (3157, 3159), True, 'from keras import backend as K\n'), ((3266, 3276), 'keras.backend.floatx', 'K.floatx', ([], {}), '()\n', (3274, 3276), True, 'from keras import backend as K\n'), ((3396, 3406), 'keras.backend.floatx', 'K.floatx', ([], {}), '()\n', (3404, 3406), True, 'from keras import backend as K\n')]
|
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="PUCCR"
)
mycursor = mydb.cursor()
#mycursor.execute("SELECT * FROM users")
#myresult = mycursor.fetchall()
#for x in myresult:
# print(x)
import sys, os, dlib, glob, numpy
import cv2
from skimage import io
#取得預設的臉部偵測器
detector = dlib.get_frontal_face_detector()
# 人臉68特徵點模型路徑
predictor_path = "shape_predictor_68_face_landmarks.dat"
# 人臉辨識模型路徑
face_rec_model_path = "dlib_face_recognition_resnet_model_v1.dat"
# 比對人臉圖片資料夾
faces_folder_path = "./memberPic"
#載入人臉68特徵點檢測器
sp = dlib.shape_predictor(predictor_path)
#載入人臉辨識檢測器
facerec = dlib.face_recognition_model_v1(face_rec_model_path)
### 處理資料夾裡每張圖片
### 建議
### descriptors, candidate 存入資料庫,後續直接讀取使用
#比對人臉描述子列表
descriptors = []
#比對人臉名稱列表
candidate = []
#針對比對資料夾裡每張圖片做比對:
#1.人臉偵測
#2.特徵點偵測
#3.取得描述子
for f in glob.glob(os.path.join(faces_folder_path, "*.jpg")):
base = os.path.basename(f).split('.')[0] # 檔名
#依序取得圖片檔案人名
#candidate.append(base)
img = io.imread(f)
#1.人臉偵測
dets = detector(img, 1)
#2.特徵點偵測
for k, d in enumerate(dets):
shape = sp(img, d)
#3.取得描述子,68維特徵量
face_descriptor = facerec.compute_face_descriptor(img, shape)
#轉換numpy array格式
v = numpy.array(face_descriptor)
#將值放入descriptors
print(face_descriptor)
#descriptors.append(v)
sql = "INSERT INTO user (name, 68_face_landmark) VALUES (%s, %s)"
str1 = ' '.join(str(e) for e in face_descriptor)
val = (base, str1)
print(val)
mycursor.execute(sql, val)
mydb.commit()
|
[
"os.path.basename",
"dlib.face_recognition_model_v1",
"numpy.array",
"dlib.get_frontal_face_detector",
"dlib.shape_predictor",
"os.path.join",
"skimage.io.imread"
] |
[((354, 386), 'dlib.get_frontal_face_detector', 'dlib.get_frontal_face_detector', ([], {}), '()\n', (384, 386), False, 'import sys, os, dlib, glob, numpy\n'), ((602, 638), 'dlib.shape_predictor', 'dlib.shape_predictor', (['predictor_path'], {}), '(predictor_path)\n', (622, 638), False, 'import sys, os, dlib, glob, numpy\n'), ((661, 712), 'dlib.face_recognition_model_v1', 'dlib.face_recognition_model_v1', (['face_rec_model_path'], {}), '(face_rec_model_path)\n', (691, 712), False, 'import sys, os, dlib, glob, numpy\n'), ((898, 938), 'os.path.join', 'os.path.join', (['faces_folder_path', '"""*.jpg"""'], {}), "(faces_folder_path, '*.jpg')\n", (910, 938), False, 'import sys, os, dlib, glob, numpy\n'), ((1047, 1059), 'skimage.io.imread', 'io.imread', (['f'], {}), '(f)\n', (1056, 1059), False, 'from skimage import io\n'), ((1308, 1336), 'numpy.array', 'numpy.array', (['face_descriptor'], {}), '(face_descriptor)\n', (1319, 1336), False, 'import sys, os, dlib, glob, numpy\n'), ((952, 971), 'os.path.basename', 'os.path.basename', (['f'], {}), '(f)\n', (968, 971), False, 'import sys, os, dlib, glob, numpy\n')]
|
# --------------------------------------------------------
# Flow-Guided Feature Aggregation
# Copyright (c) 2017 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by <NAME>
# --------------------------------------------------------
"""
given a imagenet vid imdb, compute mAP
"""
import numpy as np
import os
import cPickle
def parse_vid_rec(filename, classhash, img_ids, defaultIOUthr=0.5, pixelTolerance=10):
"""
parse imagenet vid record into a dictionary
:param filename: xml file path
:return: list of dict
"""
import xml.etree.ElementTree as ET
tree = ET.parse(filename)
objects = []
for obj in tree.findall('object'):
obj_dict = dict()
obj_dict['label'] = classhash[obj.find('name').text]
bbox = obj.find('bndbox')
obj_dict['bbox'] = [float(bbox.find('xmin').text),
float(bbox.find('ymin').text),
float(bbox.find('xmax').text),
float(bbox.find('ymax').text)]
gt_w = obj_dict['bbox'][2] - obj_dict['bbox'][0] + 1
gt_h = obj_dict['bbox'][3] - obj_dict['bbox'][1] + 1
thr = (gt_w*gt_h)/((gt_w+pixelTolerance)*(gt_h+pixelTolerance))
obj_dict['thr'] = np.min([thr, defaultIOUthr])
objects.append(obj_dict)
return {'bbox' : np.array([x['bbox'] for x in objects]),
'label': np.array([x['label'] for x in objects]),
'thr' : np.array([x['thr'] for x in objects]),
'img_ids': img_ids}
def vid_ap(rec, prec):
"""
average precision calculations
[precision integrated to recall]
:param rec: recall
:param prec: precision
:return: average precision
"""
# append sentinel values at both ends
mrec = np.concatenate(([0.], rec, [1.]))
mpre = np.concatenate(([0.], prec, [0.]))
# compute precision integration ladder
for i in range(mpre.size - 1, 0, -1):
mpre[i - 1] = np.maximum(mpre[i - 1], mpre[i])
# look for recall value changes
i = np.where(mrec[1:] != mrec[:-1])[0]
# sum (\delta recall) * prec
ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1])
return ap
def vid_eval(multifiles, detpath, annopath, imageset_file, classname_map, annocache, ovthresh=0.5):
"""
imagenet vid evaluation
:param detpath: detection results detpath.format(classname)
:param annopath: annotations annopath.format(classname)
:param imageset_file: text file containing list of images
:param annocache: caching annotations
:param ovthresh: overlap threshold
:return: rec, prec, ap
"""
with open(imageset_file, 'r') as f:
lines = [x.strip().split(' ') for x in f.readlines()]
img_basenames = [x[0] for x in lines]
gt_img_ids = [int(x[1]) for x in lines]
classhash = dict(zip(classname_map, range(0,len(classname_map))))
# load annotations from cache
if not os.path.isfile(annocache):
recs = []
for ind, image_filename in enumerate(img_basenames):
recs.append(parse_vid_rec(annopath.format('VID/' + image_filename), classhash, gt_img_ids[ind]))
if ind % 100 == 0:
print('reading annotations for {:d}/{:d}'.format(ind + 1, len(img_basenames)))
print('saving annotations cache to {:s}'.format(annocache))
with open(annocache, 'wb') as f:
cPickle.dump(recs, f, protocol=cPickle.HIGHEST_PROTOCOL)
else:
with open(annocache, 'rb') as f:
recs = cPickle.load(f)
# extract objects in :param classname:
npos = np.zeros(len(classname_map))
for rec in recs:
rec_labels = rec['label']
for x in rec_labels:
npos[x] += 1
# read detections
splitlines = []
if (multifiles == False):
with open(detpath, 'r') as f:
lines = f.readlines()
splitlines = [x.strip().split(' ') for x in lines]
else:
for det in detpath:
with open(det, 'r') as f:
lines = f.readlines()
splitlines += [x.strip().split(' ') for x in lines]
img_ids = np.array([int(x[0]) for x in splitlines])
obj_labels = np.array([int(x[1]) for x in splitlines])
obj_confs = np.array([float(x[2]) for x in splitlines])
obj_bboxes = np.array([[float(z) for z in x[3:]] for x in splitlines])
# sort by confidence
if obj_bboxes.shape[0] > 0:
sorted_inds = np.argsort(img_ids)
img_ids = img_ids[sorted_inds]
obj_labels = obj_labels[sorted_inds]
obj_confs = obj_confs[sorted_inds]
obj_bboxes = obj_bboxes[sorted_inds, :]
num_imgs = max(max(gt_img_ids),max(img_ids)) + 1
obj_labels_cell = [None] * num_imgs
obj_confs_cell = [None] * num_imgs
obj_bboxes_cell = [None] * num_imgs
start_i = 0
id = img_ids[0]
for i in range(0, len(img_ids)):
if i == len(img_ids)-1 or img_ids[i+1] != id:
conf = obj_confs[start_i:i+1]
label = obj_labels[start_i:i+1]
bbox = obj_bboxes[start_i:i+1, :]
sorted_inds = np.argsort(-conf)
obj_labels_cell[id] = label[sorted_inds]
obj_confs_cell[id] = conf[sorted_inds]
obj_bboxes_cell[id] = bbox[sorted_inds, :]
if i < len(img_ids)-1:
id = img_ids[i+1]
start_i = i+1
# go down detections and mark true positives and false positives
tp_cell = [None] * num_imgs
fp_cell = [None] * num_imgs
for rec in recs:
id = rec['img_ids']
gt_labels = rec['label']
gt_bboxes = rec['bbox']
gt_thr = rec['thr']
num_gt_obj = len(gt_labels)
gt_detected = np.zeros(num_gt_obj)
labels = obj_labels_cell[id]
bboxes = obj_bboxes_cell[id]
num_obj = 0 if labels is None else len(labels)
tp = np.zeros(num_obj)
fp = np.zeros(num_obj)
for j in range(0,num_obj):
bb = bboxes[j, :]
ovmax = -1
kmax = -1
for k in range(0,num_gt_obj):
if labels[j] != gt_labels[k]:
continue
if gt_detected[k] > 0:
continue
bbgt = gt_bboxes[k, :]
bi=[np.max((bb[0],bbgt[0])), np.max((bb[1],bbgt[1])), np.min((bb[2],bbgt[2])), np.min((bb[3],bbgt[3]))]
iw=bi[2]-bi[0]+1
ih=bi[3]-bi[1]+1
if iw>0 and ih>0:
# compute overlap as area of intersection / area of union
ua = (bb[2] - bb[0] + 1.) * (bb[3] - bb[1] + 1.) + \
(bbgt[2] - bbgt[0] + 1.) * \
(bbgt[3] - bbgt[1] + 1.) - iw*ih
ov=iw*ih/ua
# makes sure that this object is detected according
# to its individual threshold
if ov >= gt_thr[k] and ov > ovmax:
ovmax=ov
kmax=k
if kmax >= 0:
tp[j] = 1
gt_detected[kmax] = 1
else:
fp[j] = 1
tp_cell[id] = tp
fp_cell[id] = fp
tp_all = np.concatenate([x for x in np.array(tp_cell)[gt_img_ids] if x is not None])
fp_all = np.concatenate([x for x in np.array(fp_cell)[gt_img_ids] if x is not None])
obj_labels = np.concatenate([x for x in np.array(obj_labels_cell)[gt_img_ids] if x is not None])
confs = np.concatenate([x for x in np.array(obj_confs_cell)[gt_img_ids] if x is not None])
sorted_inds = np.argsort(-confs)
tp_all = tp_all[sorted_inds]
fp_all = fp_all[sorted_inds]
obj_labels = obj_labels[sorted_inds]
ap = np.zeros(len(classname_map))
for c in range(1, len(classname_map)):
# compute precision recall
fp = np.cumsum(fp_all[obj_labels == c])
tp = np.cumsum(tp_all[obj_labels == c])
rec = tp / float(npos[c])
# avoid division by zero in case first detection matches a difficult ground ruth
prec = tp / np.maximum(tp + fp, np.finfo(np.float64).eps)
ap[c] = vid_ap(rec, prec)
ap = ap[1:]
return ap
|
[
"xml.etree.ElementTree.parse",
"numpy.sum",
"numpy.maximum",
"numpy.zeros",
"cPickle.load",
"numpy.argsort",
"numpy.cumsum",
"numpy.min",
"numpy.where",
"numpy.array",
"os.path.isfile",
"cPickle.dump",
"numpy.max",
"numpy.finfo",
"numpy.concatenate"
] |
[((619, 637), 'xml.etree.ElementTree.parse', 'ET.parse', (['filename'], {}), '(filename)\n', (627, 637), True, 'import xml.etree.ElementTree as ET\n'), ((1799, 1834), 'numpy.concatenate', 'np.concatenate', (['([0.0], rec, [1.0])'], {}), '(([0.0], rec, [1.0]))\n', (1813, 1834), True, 'import numpy as np\n'), ((1844, 1880), 'numpy.concatenate', 'np.concatenate', (['([0.0], prec, [0.0])'], {}), '(([0.0], prec, [0.0]))\n', (1858, 1880), True, 'import numpy as np\n'), ((2143, 2188), 'numpy.sum', 'np.sum', (['((mrec[i + 1] - mrec[i]) * mpre[i + 1])'], {}), '((mrec[i + 1] - mrec[i]) * mpre[i + 1])\n', (2149, 2188), True, 'import numpy as np\n'), ((7628, 7646), 'numpy.argsort', 'np.argsort', (['(-confs)'], {}), '(-confs)\n', (7638, 7646), True, 'import numpy as np\n'), ((1271, 1299), 'numpy.min', 'np.min', (['[thr, defaultIOUthr]'], {}), '([thr, defaultIOUthr])\n', (1277, 1299), True, 'import numpy as np\n'), ((1354, 1392), 'numpy.array', 'np.array', (["[x['bbox'] for x in objects]"], {}), "([x['bbox'] for x in objects])\n", (1362, 1392), True, 'import numpy as np\n'), ((1416, 1455), 'numpy.array', 'np.array', (["[x['label'] for x in objects]"], {}), "([x['label'] for x in objects])\n", (1424, 1455), True, 'import numpy as np\n'), ((1479, 1516), 'numpy.array', 'np.array', (["[x['thr'] for x in objects]"], {}), "([x['thr'] for x in objects])\n", (1487, 1516), True, 'import numpy as np\n'), ((1987, 2019), 'numpy.maximum', 'np.maximum', (['mpre[i - 1]', 'mpre[i]'], {}), '(mpre[i - 1], mpre[i])\n', (1997, 2019), True, 'import numpy as np\n'), ((2065, 2096), 'numpy.where', 'np.where', (['(mrec[1:] != mrec[:-1])'], {}), '(mrec[1:] != mrec[:-1])\n', (2073, 2096), True, 'import numpy as np\n'), ((2951, 2976), 'os.path.isfile', 'os.path.isfile', (['annocache'], {}), '(annocache)\n', (2965, 2976), False, 'import os\n'), ((4462, 4481), 'numpy.argsort', 'np.argsort', (['img_ids'], {}), '(img_ids)\n', (4472, 4481), True, 'import numpy as np\n'), ((5728, 5748), 'numpy.zeros', 'np.zeros', (['num_gt_obj'], {}), '(num_gt_obj)\n', (5736, 5748), True, 'import numpy as np\n'), ((5893, 5910), 'numpy.zeros', 'np.zeros', (['num_obj'], {}), '(num_obj)\n', (5901, 5910), True, 'import numpy as np\n'), ((5924, 5941), 'numpy.zeros', 'np.zeros', (['num_obj'], {}), '(num_obj)\n', (5932, 5941), True, 'import numpy as np\n'), ((7884, 7918), 'numpy.cumsum', 'np.cumsum', (['fp_all[obj_labels == c]'], {}), '(fp_all[obj_labels == c])\n', (7893, 7918), True, 'import numpy as np\n'), ((7932, 7966), 'numpy.cumsum', 'np.cumsum', (['tp_all[obj_labels == c]'], {}), '(tp_all[obj_labels == c])\n', (7941, 7966), True, 'import numpy as np\n'), ((3413, 3469), 'cPickle.dump', 'cPickle.dump', (['recs', 'f'], {'protocol': 'cPickle.HIGHEST_PROTOCOL'}), '(recs, f, protocol=cPickle.HIGHEST_PROTOCOL)\n', (3425, 3469), False, 'import cPickle\n'), ((3540, 3555), 'cPickle.load', 'cPickle.load', (['f'], {}), '(f)\n', (3552, 3555), False, 'import cPickle\n'), ((5115, 5132), 'numpy.argsort', 'np.argsort', (['(-conf)'], {}), '(-conf)\n', (5125, 5132), True, 'import numpy as np\n'), ((6297, 6321), 'numpy.max', 'np.max', (['(bb[0], bbgt[0])'], {}), '((bb[0], bbgt[0]))\n', (6303, 6321), True, 'import numpy as np\n'), ((6322, 6346), 'numpy.max', 'np.max', (['(bb[1], bbgt[1])'], {}), '((bb[1], bbgt[1]))\n', (6328, 6346), True, 'import numpy as np\n'), ((6347, 6371), 'numpy.min', 'np.min', (['(bb[2], bbgt[2])'], {}), '((bb[2], bbgt[2]))\n', (6353, 6371), True, 'import numpy as np\n'), ((6372, 6396), 'numpy.min', 'np.min', (['(bb[3], bbgt[3])'], {}), '((bb[3], bbgt[3]))\n', (6378, 6396), True, 'import numpy as np\n'), ((7275, 7292), 'numpy.array', 'np.array', (['tp_cell'], {}), '(tp_cell)\n', (7283, 7292), True, 'import numpy as np\n'), ((7364, 7381), 'numpy.array', 'np.array', (['fp_cell'], {}), '(fp_cell)\n', (7372, 7381), True, 'import numpy as np\n'), ((7457, 7482), 'numpy.array', 'np.array', (['obj_labels_cell'], {}), '(obj_labels_cell)\n', (7465, 7482), True, 'import numpy as np\n'), ((7553, 7577), 'numpy.array', 'np.array', (['obj_confs_cell'], {}), '(obj_confs_cell)\n', (7561, 7577), True, 'import numpy as np\n'), ((8130, 8150), 'numpy.finfo', 'np.finfo', (['np.float64'], {}), '(np.float64)\n', (8138, 8150), True, 'import numpy as np\n')]
|
# lshash/lshash.py
# Copyright 2012 <NAME> (a.k.a <NAME>) and contributors (see CONTRIBUTORS.txt)
#
# This module is part of lshash and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
# wiki:https://yongyuan.name/blog/ann-search.html
import os
import json
import numpy as np
from storage import storage
try:
from bitarray import bitarray
except ImportError:
bitarray = None
class LSHash(object):
""" LSHash implments locality sensitive hashing using random projection for
input vectors of dimension `input_dim`.
Attributes:
:param hash_size:
The length of the resulting binary hash in integer. E.g., 32 means the
resulting binary hash will be 32-bit long.
:param input_dim:
The dimension of the input vector. E.g., a grey-scale picture of 30x30
pixels will have an input dimension of 900.
:param num_hashtables:
(optional) The number of hash tables used for multiple lookups.
:param storage_config:
(optional) A dictionary of the form `{backend_name: config}` where
`backend_name` is the either `dict` or `redis`, and `config` is the
configuration used by the backend. For `redis` it should be in the
format of `{"redis": {"host": hostname, "port": port_num}}`, where
`hostname` is normally `localhost` and `port` is normally 6379.
:param matrices_filename:
(optional) Specify the path to the compressed numpy file ending with
extension `.npz`, where the uniform random planes are stored, or to be
stored if the file does not exist yet.
:param overwrite:
(optional) Whether to overwrite the matrices file if it already exist
"""
def __init__(self, hash_size, input_dim, num_hashtables=1,
storage_config=None, matrices_filename=None, overwrite=False):
self.hash_size = hash_size
self.input_dim = input_dim
self.num_hashtables = num_hashtables
if storage_config is None:
storage_config = {'dict': None}
self.storage_config = storage_config
if matrices_filename and not matrices_filename.endswith('.npz'):
raise ValueError("The specified file name must end with .npz")
self.matrices_filename = matrices_filename
self.overwrite = overwrite
self._init_uniform_planes()
self._init_hashtables()
def _init_uniform_planes(self):
""" Initialize uniform planes used to calculate the hashes
if file `self.matrices_filename` exist and `self.overwrite` is
selected, save the uniform planes to the specified file.
if file `self.matrices_filename` exist and `self.overwrite` is not
selected, load the matrix with `np.load`.
if file `self.matrices_filename` does not exist and regardless of
`self.overwrite`, only set `self.uniform_planes`.
"""
if "uniform_planes" in self.__dict__:
return
if self.matrices_filename:
file_exist = os.path.isfile(self.matrices_filename)
if file_exist and not self.overwrite:
try:
npzfiles = np.load(self.matrices_filename)
except IOError:
print("Cannot load specified file as a numpy array")
raise
else:
npzfiles = sorted(npzfiles.items(), key=lambda x: x[0])
self.uniform_planes = [t[1] for t in npzfiles]
else:
self.uniform_planes = [self._generate_uniform_planes()
for _ in range(self.num_hashtables)]
try:
np.savez_compressed(self.matrices_filename,
*self.uniform_planes)
except IOError:
print("IOError when saving matrices to specificed path")
raise
else:
# 生成num_hashtable个随机划分表,每个表维度:[hash_size, dim]
self.uniform_planes = [self._generate_uniform_planes()
for _ in range(self.num_hashtables)]
def _init_hashtables(self):
""" Initialize the hash tables such that each record will be in the
form of "[storage1, storage2, ...]" """
# 初始化num_hashtable个hash表
self.hash_tables = [storage(self.storage_config, i)
for i in range(self.num_hashtables)]
def _generate_uniform_planes(self):
""" Generate uniformly distributed hyperplanes and return it as a 2D
numpy array.
"""
# 随机矩阵[hash_size, input_dim], 矩阵每行代表一条直线的法向量,Ax>0即代表与所有平面的法向量的夹角<90的所有点x的集合
return np.random.randn(self.hash_size, self.input_dim)
def _hash(self, planes, input_point):
""" Generates the binary hash for `input_point` and returns it.
:param planes:
The planes are random uniform planes with a dimension of
`hash_size` * `input_dim`.
:param input_point:
A Python tuple or list object that contains only numbers.
The dimension needs to be 1 * `input_dim`.
"""
try:
input_point = np.array(input_point) # for faster dot product
# planes:[hash_size, dim]
# input_point:[dim], 亦可理解为input_point: [dim,1]
# projections:[hash_size] = planes*input_point
# 矩阵planes与input_points相乘的几何意义就是判断input_points是否与planes每行的直线法向量的乘积
projections = np.dot(planes, input_point)
except TypeError as e:
print("""The input point needs to be an array-like object with
numbers only elements""")
raise
except ValueError as e:
print("""The input point needs to be of the same dimension as
`input_dim` when initializing this LSHash instance""", e)
raise
else:
# 比如可能是'001'
return "".join(['1' if i > 0 else '0' for i in projections])
def _as_np_array(self, json_or_tuple):
""" Takes either a JSON-serialized data structure or a tuple that has
the original input points stored, and returns the original input point
in numpy array format.
"""
if isinstance(json_or_tuple, str):
# JSON-serialized in the case of Redis
try:
# Return the point stored as list, without the extra data
tuples = json.loads(json_or_tuple)[0]
except TypeError:
print("The value stored is not JSON-serilizable")
raise
else:
# If extra_data exists, `tuples` is the entire
# (point:tuple, extra_data). Otherwise (i.e., extra_data=None),
# return the point stored as a tuple
tuples = json_or_tuple
if isinstance(tuples[0], tuple):
# in this case extra data exists
return np.asarray(tuples[0])
elif isinstance(tuples, (tuple, list)):
try:
return np.asarray(tuples)
except ValueError as e:
print("The input needs to be an array-like object", e)
raise
else:
raise TypeError("query data is not supported")
def index(self, input_point, extra_data=None):
""" Index a single input point by adding it to the selected storage.
If `extra_data` is provided, it will become the value of the dictionary
{input_point: extra_data}, which in turn will become the value of the
hash table. `extra_data` needs to be JSON serializable if in-memory
dict is not used as storage.
:param input_point:
A list, or tuple, or numpy ndarray object that contains numbers
only. The dimension needs to be 1 * `input_dim`.
This object will be converted to Python tuple and stored in the
selected storage.
:param extra_data:
(optional) Needs to be a JSON-serializable object: list, dicts and
basic types such as strings and integers.
"""
if isinstance(input_point, np.ndarray):
input_point = input_point.tolist()
if extra_data:
value = (tuple(input_point), extra_data)
else:
value = tuple(input_point)
# 每个hash表均要存一下hash串+原始point
for i, table in enumerate(self.hash_tables):
# 生成num_hashtable个随机划分表,每个表维度:[hash_size, dim]
hash_code = self._hash(self.uniform_planes[i], input_point)
# 之所以有多个表,就是为了增大召回,即只要有一个划分方式一致就可以召回
table.append_val(key=hash_code, val=value)
def query(self, query_point, num_results=None, distance_func_for_hash=None):
""" Takes `query_point` which is either a tuple or a list of numbers,
returns `num_results` of results as a list of tuples that are ranked
based on the supplied metric function `distance_func`.
:param query_point:
A list, or tuple, or numpy ndarray that only contains numbers.
The dimension needs to be 1 * `input_dim`.
Used by :meth:`._hash`.
:param num_results:
(optional) Integer, specifies the max amount of results to be
returned. If not specified all candidates will be returned as a
list in ranked order.
:param distance_func_for_hash:
(optional) The distance function to be used. Currently it needs to
be one of ("hamming", "euclidean", "true_euclidean",
"centred_euclidean", "cosine", "l1norm"). By default "euclidean"
will used.
"""
candidates = set()
if not distance_func_for_hash:
distance_func_for_hash = "euclidean"
if distance_func_for_hash == "hamming": # 此时实际上就是multi-probe的方式进行探测
if not bitarray:
raise ImportError(" Bitarray is required for hamming distance")
for i, table in enumerate(self.hash_tables):
binary_hash_for_query = self._hash(self.uniform_planes[i], query_point)
for key in table.keys():
distance = LSHash.hamming_dist(key, binary_hash_for_query)
# 所有hamming距离<2的全都加入候选集合,注意,不一定是相同hash_key下的所有候选point
if distance < 2:
# 将该hash_key下所有的原始值全加入set
candidates.update(table.get_list(key))
d_func_for_rank = LSHash.euclidean_dist_square
else: # euclidean
if distance_func_for_hash == "euclidean":
d_func_for_rank = LSHash.euclidean_dist_square
elif distance_func_for_hash == "true_euclidean":
d_func_for_rank = LSHash.euclidean_dist
elif distance_func_for_hash == "centred_euclidean":
d_func_for_rank = LSHash.euclidean_dist_centred
elif distance_func_for_hash == "cosine":
d_func_for_rank = LSHash.cosine_dist
elif distance_func_for_hash == "l1norm":
d_func_for_rank = LSHash.l1norm_dist
else:
raise ValueError("The distance function name is invalid.")
# 只有hash值相同的才认为是候选集合,只要有一个hash表认为是候选就加入候选
for i, table in enumerate(self.hash_tables):
binary_hash_for_query = self._hash(self.uniform_planes[i], query_point)
candidates.update(table.get_list(binary_hash_for_query))
# rank candidates by distance function
# 计算query与每个候选集原始值的距离
# [(candidate_point, distance),... ]
candidates = [(candidate_point, d_func_for_rank(query_point, self._as_np_array(candidate_point)))
for candidate_point in candidates]
candidates.sort(key=lambda x: x[1]) # 按距离升序排序
# 选出距离最近的topK
return candidates[:num_results] if num_results else candidates
### distance functions
# 海明距离是直接异或么?直接数不同的位数的个数
@staticmethod
def hamming_dist(bitarray1, bitarray2):
xor_result = bitarray(bitarray1) ^ bitarray(bitarray2)
return xor_result.count()
@staticmethod
def euclidean_dist(x, y):
""" This is a hot function, hence some optimizations are made. """
return np.sqrt(LSHash.euclidean_dist_square(x,y))
@staticmethod
def euclidean_dist_square(x, y):
""" This is a hot function, hence some optimizations are made. """
diff = np.array(x) - y
return np.dot(diff, diff)
@staticmethod
def euclidean_dist_centred(x, y):
""" This is a hot function, hence some optimizations are made. """
diff = np.mean(x) - np.mean(y)
return np.dot(diff, diff)
@staticmethod
def l1norm_dist(x, y):
return sum(abs(x - y))
@staticmethod
def cosine_dist(x, y):
return 1 - np.dot(x, y) / ((np.dot(x, x) * np.dot(y, y)) ** 0.5)
if __name__ == '__main__':
lsh = LSHash(hash_size=6, input_dim=8, num_hashtables=3)
# 给数据建立hash索引
lsh.index(input_point=[1, 2, 3, 4, 5, 6, 7, 8])
lsh.index(input_point=[2, 3, 4, 5, 6, 7, 8, 9])
lsh.index(input_point=[1, 2, 3, 4, 4, 6, 7, 8])
lsh.index(input_point=[1, 2, 3, 3, 5, 6, 7, 8])
lsh.index(input_point=[1, 2, 3, 4, 5, 6, 7, 9])
lsh.index(input_point=[2, 2, 3, 4, 5, 6, 7, 9])
lsh.index(input_point=[2, -2, 3, 4, 5, 6, 7, 9])
lsh.index(input_point=[-1, 2, 3, 4, 5, 6, 7, 9])
lsh.index(input_point=[10, 12, 99, 1, 5, 31, 2, 3])
# 查询
res = lsh.query(query_point=[1, 2, 3, 4, 5, 6, 7, 7], num_results=4)
print(res)
|
[
"storage.storage",
"numpy.load",
"json.loads",
"numpy.random.randn",
"numpy.asarray",
"os.path.isfile",
"numpy.mean",
"numpy.array",
"numpy.savez_compressed",
"numpy.dot",
"bitarray.bitarray"
] |
[((4758, 4805), 'numpy.random.randn', 'np.random.randn', (['self.hash_size', 'self.input_dim'], {}), '(self.hash_size, self.input_dim)\n', (4773, 4805), True, 'import numpy as np\n'), ((12575, 12593), 'numpy.dot', 'np.dot', (['diff', 'diff'], {}), '(diff, diff)\n', (12581, 12593), True, 'import numpy as np\n'), ((12780, 12798), 'numpy.dot', 'np.dot', (['diff', 'diff'], {}), '(diff, diff)\n', (12786, 12798), True, 'import numpy as np\n'), ((3065, 3103), 'os.path.isfile', 'os.path.isfile', (['self.matrices_filename'], {}), '(self.matrices_filename)\n', (3079, 3103), False, 'import os\n'), ((4411, 4442), 'storage.storage', 'storage', (['self.storage_config', 'i'], {}), '(self.storage_config, i)\n', (4418, 4442), False, 'from storage import storage\n'), ((5258, 5279), 'numpy.array', 'np.array', (['input_point'], {}), '(input_point)\n', (5266, 5279), True, 'import numpy as np\n'), ((5567, 5594), 'numpy.dot', 'np.dot', (['planes', 'input_point'], {}), '(planes, input_point)\n', (5573, 5594), True, 'import numpy as np\n'), ((7015, 7036), 'numpy.asarray', 'np.asarray', (['tuples[0]'], {}), '(tuples[0])\n', (7025, 7036), True, 'import numpy as np\n'), ((12140, 12159), 'bitarray.bitarray', 'bitarray', (['bitarray1'], {}), '(bitarray1)\n', (12148, 12159), False, 'from bitarray import bitarray\n'), ((12162, 12181), 'bitarray.bitarray', 'bitarray', (['bitarray2'], {}), '(bitarray2)\n', (12170, 12181), False, 'from bitarray import bitarray\n'), ((12544, 12555), 'numpy.array', 'np.array', (['x'], {}), '(x)\n', (12552, 12555), True, 'import numpy as np\n'), ((12741, 12751), 'numpy.mean', 'np.mean', (['x'], {}), '(x)\n', (12748, 12751), True, 'import numpy as np\n'), ((12754, 12764), 'numpy.mean', 'np.mean', (['y'], {}), '(y)\n', (12761, 12764), True, 'import numpy as np\n'), ((12941, 12953), 'numpy.dot', 'np.dot', (['x', 'y'], {}), '(x, y)\n', (12947, 12953), True, 'import numpy as np\n'), ((3206, 3237), 'numpy.load', 'np.load', (['self.matrices_filename'], {}), '(self.matrices_filename)\n', (3213, 3237), True, 'import numpy as np\n'), ((3740, 3805), 'numpy.savez_compressed', 'np.savez_compressed', (['self.matrices_filename', '*self.uniform_planes'], {}), '(self.matrices_filename, *self.uniform_planes)\n', (3759, 3805), True, 'import numpy as np\n'), ((6529, 6554), 'json.loads', 'json.loads', (['json_or_tuple'], {}), '(json_or_tuple)\n', (6539, 6554), False, 'import json\n'), ((7126, 7144), 'numpy.asarray', 'np.asarray', (['tuples'], {}), '(tuples)\n', (7136, 7144), True, 'import numpy as np\n'), ((12958, 12970), 'numpy.dot', 'np.dot', (['x', 'x'], {}), '(x, x)\n', (12964, 12970), True, 'import numpy as np\n'), ((12973, 12985), 'numpy.dot', 'np.dot', (['y', 'y'], {}), '(y, y)\n', (12979, 12985), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import unittest
from network import TargetNetwork, Network
class TargetNetworkTest(unittest.TestCase):
def test_init(self):
np.random.seed(seed=0)
target_network = TargetNetwork()
for i in range(10):
input_values, target_values = target_network.get_training_pair()
self.assertEqual(input_values.shape, (30, ))
self.assertEqual(target_values.shape, (10, ))
print(target_values)
"""
def test_save(self):
np.random.seed(seed=0)
target_network = TargetNetwork()
target_network.save("tmp")
target_network.load("tmp")
"""
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"network.TargetNetwork",
"numpy.random.seed"
] |
[((829, 844), 'unittest.main', 'unittest.main', ([], {}), '()\n', (842, 844), False, 'import unittest\n'), ((292, 314), 'numpy.random.seed', 'np.random.seed', ([], {'seed': '(0)'}), '(seed=0)\n', (306, 314), True, 'import numpy as np\n'), ((340, 355), 'network.TargetNetwork', 'TargetNetwork', ([], {}), '()\n', (353, 355), False, 'from network import TargetNetwork, Network\n')]
|
from mpvr.datamodule.manager import Manager as dm
from mpvr.utils.process import *
from scipy.signal import savgol_filter
import numpy as np
import pandas as pd
dm = dm.from_config(dm.section_list()[1])
max_val = 0
for scenario in dm.get_scenarios():
dm.set_scenario(scenario)
df = dm.get_processed_data('mpe')
mpe = df['MPEntropy'].values
if np.max(np.abs(mpe)) > max_val:
max_val = np.max(np.abs(mpe))
print(max_val)
for scenario in dm.get_scenarios():
print(scenario)
dm.set_scenario(scenario)
df = dm.get_processed_data('mpe')
time, mpe = df['Time'].values, df['MPEntropy'].values
acr = absolute_category_rating(mpe, grid)
incidence = dm.get_incidence_data()
fig, axes = dm.fig_setup(2, ['ACR', 'Incidence'], np.arange(0, len(time)/3, 2), times = time, width = 3, height=3)
axes[0].plot(time, acr)
axes[1].bar(time, incidence, width=0.2)
axes[0].set_yticks(np.arange(1, 6, 1))
axes[1].set_yticks(np.arange(0, 5, 1))
dm.fig_finalize(tag='mpe', remark_dir='acr/')
|
[
"numpy.abs",
"mpvr.datamodule.manager.Manager.fig_finalize",
"mpvr.datamodule.manager.Manager.get_incidence_data",
"numpy.arange",
"mpvr.datamodule.manager.Manager.get_scenarios",
"mpvr.datamodule.manager.Manager.set_scenario",
"mpvr.datamodule.manager.Manager.section_list",
"mpvr.datamodule.manager.Manager.get_processed_data"
] |
[((233, 251), 'mpvr.datamodule.manager.Manager.get_scenarios', 'dm.get_scenarios', ([], {}), '()\n', (249, 251), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((463, 481), 'mpvr.datamodule.manager.Manager.get_scenarios', 'dm.get_scenarios', ([], {}), '()\n', (479, 481), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((257, 282), 'mpvr.datamodule.manager.Manager.set_scenario', 'dm.set_scenario', (['scenario'], {}), '(scenario)\n', (272, 282), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((292, 320), 'mpvr.datamodule.manager.Manager.get_processed_data', 'dm.get_processed_data', (['"""mpe"""'], {}), "('mpe')\n", (313, 320), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((507, 532), 'mpvr.datamodule.manager.Manager.set_scenario', 'dm.set_scenario', (['scenario'], {}), '(scenario)\n', (522, 532), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((543, 571), 'mpvr.datamodule.manager.Manager.get_processed_data', 'dm.get_processed_data', (['"""mpe"""'], {}), "('mpe')\n", (564, 571), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((692, 715), 'mpvr.datamodule.manager.Manager.get_incidence_data', 'dm.get_incidence_data', ([], {}), '()\n', (713, 715), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((999, 1044), 'mpvr.datamodule.manager.Manager.fig_finalize', 'dm.fig_finalize', ([], {'tag': '"""mpe"""', 'remark_dir': '"""acr/"""'}), "(tag='mpe', remark_dir='acr/')\n", (1014, 1044), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((182, 199), 'mpvr.datamodule.manager.Manager.section_list', 'dm.section_list', ([], {}), '()\n', (197, 199), True, 'from mpvr.datamodule.manager import Manager as dm\n'), ((932, 950), 'numpy.arange', 'np.arange', (['(1)', '(6)', '(1)'], {}), '(1, 6, 1)\n', (941, 950), True, 'import numpy as np\n'), ((975, 993), 'numpy.arange', 'np.arange', (['(0)', '(5)', '(1)'], {}), '(0, 5, 1)\n', (984, 993), True, 'import numpy as np\n'), ((368, 379), 'numpy.abs', 'np.abs', (['mpe'], {}), '(mpe)\n', (374, 379), True, 'import numpy as np\n'), ((417, 428), 'numpy.abs', 'np.abs', (['mpe'], {}), '(mpe)\n', (423, 428), True, 'import numpy as np\n')]
|
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
import cv2
import numpy as np
from PIL import Image
import math
class Erosion2d(nn.Layer):
"""
Erosion2d
"""
def __init__(self, m=1):
super(Erosion2d, self).__init__()
self.m = m
self.pad = [m, m, m, m]
def forward(self, x):
batch_size, c, h, w = x.shape
x_pad = F.pad(x, pad=self.pad, mode='constant', value=1e9)
channel = nn.functional.unfold(x_pad, 2 * self.m + 1, strides=1, paddings=0).reshape([batch_size, c, -1, h, w])
result = paddle.min(channel, axis=2)
return result
class Dilation2d(nn.Layer):
"""
Dilation2d
"""
def __init__(self, m=1):
super(Dilation2d, self).__init__()
self.m = m
self.pad = [m, m, m, m]
def forward(self, x):
batch_size, c, h, w = x.shape
x_pad = F.pad(x, pad=self.pad, mode='constant', value=-1e9)
channel = nn.functional.unfold(x_pad, 2 * self.m + 1, strides=1, paddings=0).reshape([batch_size, c, -1, h, w])
result = paddle.max(channel, axis=2)
return result
def param2stroke(param, H, W, meta_brushes):
"""
param2stroke
"""
b = param.shape[0]
param_list = paddle.split(param, 8, axis=1)
x0, y0, w, h, theta = [item.squeeze(-1) for item in param_list[:5]]
sin_theta = paddle.sin(math.pi * theta)
cos_theta = paddle.cos(math.pi * theta)
index = paddle.full((b,), -1, dtype='int64').numpy()
index[(h > w).numpy()] = 0
index[(h <= w).numpy()] = 1
meta_brushes_resize = F.interpolate(meta_brushes, (H, W)).numpy()
brush = paddle.to_tensor(meta_brushes_resize[index])
warp_00 = cos_theta / w
warp_01 = sin_theta * H / (W * w)
warp_02 = (1 - 2 * x0) * cos_theta / w + (1 - 2 * y0) * sin_theta * H / (W * w)
warp_10 = -sin_theta * W / (H * h)
warp_11 = cos_theta / h
warp_12 = (1 - 2 * y0) * cos_theta / h - (1 - 2 * x0) * sin_theta * W / (H * h)
warp_0 = paddle.stack([warp_00, warp_01, warp_02], axis=1)
warp_1 = paddle.stack([warp_10, warp_11, warp_12], axis=1)
warp = paddle.stack([warp_0, warp_1], axis=1)
grid = nn.functional.affine_grid(warp, [b, 3, H, W]) # paddle和torch默认值是反过来的
brush = nn.functional.grid_sample(brush, grid)
return brush
def read_img(img_path, img_type='RGB', h=None, w=None):
"""
read img
"""
img = Image.open(img_path).convert(img_type)
if h is not None and w is not None:
img = img.resize((w, h), resample=Image.NEAREST)
img = np.array(img)
if img.ndim == 2:
img = np.expand_dims(img, axis=-1)
img = img.transpose((2, 0, 1)) # 矩阵的维度由 (X, Y, Z) -> (Z, X, Y)
img = paddle.to_tensor(img).unsqueeze(0).astype('float32') / 255. # 矩阵变为归一化张量
return img
def preprocess(img, w=512, h=512):
image = cv2.resize(img, (w, h), cv2.INTER_NEAREST)
image = image.transpose((2, 0, 1))
image = paddle.to_tensor(image).unsqueeze(0).astype('float32') / 255.
return image
def pad(img, H, W):
b, c, h, w = img.shape
pad_h = (H - h) // 2
pad_w = (W - w) // 2
remainder_h = (H - h) % 2
remainder_w = (W - w) % 2
expand_img = nn.functional.pad(img, [pad_w, pad_w + remainder_w,
pad_h, pad_h + remainder_h])
return expand_img
|
[
"paddle.to_tensor",
"paddle.nn.functional.affine_grid",
"paddle.nn.functional.grid_sample",
"paddle.sin",
"paddle.stack",
"paddle.nn.functional.unfold",
"numpy.expand_dims",
"paddle.cos",
"PIL.Image.open",
"paddle.nn.functional.pad",
"paddle.min",
"paddle.full",
"numpy.array",
"paddle.max",
"paddle.nn.functional.interpolate",
"paddle.split",
"cv2.resize"
] |
[((1255, 1285), 'paddle.split', 'paddle.split', (['param', '(8)'], {'axis': '(1)'}), '(param, 8, axis=1)\n', (1267, 1285), False, 'import paddle\n'), ((1374, 1401), 'paddle.sin', 'paddle.sin', (['(math.pi * theta)'], {}), '(math.pi * theta)\n', (1384, 1401), False, 'import paddle\n'), ((1418, 1445), 'paddle.cos', 'paddle.cos', (['(math.pi * theta)'], {}), '(math.pi * theta)\n', (1428, 1445), False, 'import paddle\n'), ((1649, 1693), 'paddle.to_tensor', 'paddle.to_tensor', (['meta_brushes_resize[index]'], {}), '(meta_brushes_resize[index])\n', (1665, 1693), False, 'import paddle\n'), ((2009, 2058), 'paddle.stack', 'paddle.stack', (['[warp_00, warp_01, warp_02]'], {'axis': '(1)'}), '([warp_00, warp_01, warp_02], axis=1)\n', (2021, 2058), False, 'import paddle\n'), ((2072, 2121), 'paddle.stack', 'paddle.stack', (['[warp_10, warp_11, warp_12]'], {'axis': '(1)'}), '([warp_10, warp_11, warp_12], axis=1)\n', (2084, 2121), False, 'import paddle\n'), ((2133, 2171), 'paddle.stack', 'paddle.stack', (['[warp_0, warp_1]'], {'axis': '(1)'}), '([warp_0, warp_1], axis=1)\n', (2145, 2171), False, 'import paddle\n'), ((2183, 2228), 'paddle.nn.functional.affine_grid', 'nn.functional.affine_grid', (['warp', '[b, 3, H, W]'], {}), '(warp, [b, 3, H, W])\n', (2208, 2228), True, 'import paddle.nn as nn\n'), ((2264, 2302), 'paddle.nn.functional.grid_sample', 'nn.functional.grid_sample', (['brush', 'grid'], {}), '(brush, grid)\n', (2289, 2302), True, 'import paddle.nn as nn\n'), ((2564, 2577), 'numpy.array', 'np.array', (['img'], {}), '(img)\n', (2572, 2577), True, 'import numpy as np\n'), ((2855, 2897), 'cv2.resize', 'cv2.resize', (['img', '(w, h)', 'cv2.INTER_NEAREST'], {}), '(img, (w, h), cv2.INTER_NEAREST)\n', (2865, 2897), False, 'import cv2\n'), ((3203, 3288), 'paddle.nn.functional.pad', 'nn.functional.pad', (['img', '[pad_w, pad_w + remainder_w, pad_h, pad_h + remainder_h]'], {}), '(img, [pad_w, pad_w + remainder_w, pad_h, pad_h + remainder_h]\n )\n', (3220, 3288), True, 'import paddle.nn as nn\n'), ((395, 454), 'paddle.nn.functional.pad', 'F.pad', (['x'], {'pad': 'self.pad', 'mode': '"""constant"""', 'value': '(1000000000.0)'}), "(x, pad=self.pad, mode='constant', value=1000000000.0)\n", (400, 454), True, 'import paddle.nn.functional as F\n'), ((583, 610), 'paddle.min', 'paddle.min', (['channel'], {'axis': '(2)'}), '(channel, axis=2)\n', (593, 610), False, 'import paddle\n'), ((897, 957), 'paddle.nn.functional.pad', 'F.pad', (['x'], {'pad': 'self.pad', 'mode': '"""constant"""', 'value': '(-1000000000.0)'}), "(x, pad=self.pad, mode='constant', value=-1000000000.0)\n", (902, 957), True, 'import paddle.nn.functional as F\n'), ((1086, 1113), 'paddle.max', 'paddle.max', (['channel'], {'axis': '(2)'}), '(channel, axis=2)\n', (1096, 1113), False, 'import paddle\n'), ((2614, 2642), 'numpy.expand_dims', 'np.expand_dims', (['img'], {'axis': '(-1)'}), '(img, axis=-1)\n', (2628, 2642), True, 'import numpy as np\n'), ((1458, 1494), 'paddle.full', 'paddle.full', (['(b,)', '(-1)'], {'dtype': '"""int64"""'}), "((b,), -1, dtype='int64')\n", (1469, 1494), False, 'import paddle\n'), ((1593, 1628), 'paddle.nn.functional.interpolate', 'F.interpolate', (['meta_brushes', '(H, W)'], {}), '(meta_brushes, (H, W))\n', (1606, 1628), True, 'import paddle.nn.functional as F\n'), ((2418, 2438), 'PIL.Image.open', 'Image.open', (['img_path'], {}), '(img_path)\n', (2428, 2438), False, 'from PIL import Image\n'), ((464, 530), 'paddle.nn.functional.unfold', 'nn.functional.unfold', (['x_pad', '(2 * self.m + 1)'], {'strides': '(1)', 'paddings': '(0)'}), '(x_pad, 2 * self.m + 1, strides=1, paddings=0)\n', (484, 530), True, 'import paddle.nn as nn\n'), ((967, 1033), 'paddle.nn.functional.unfold', 'nn.functional.unfold', (['x_pad', '(2 * self.m + 1)'], {'strides': '(1)', 'paddings': '(0)'}), '(x_pad, 2 * self.m + 1, strides=1, paddings=0)\n', (987, 1033), True, 'import paddle.nn as nn\n'), ((2720, 2741), 'paddle.to_tensor', 'paddle.to_tensor', (['img'], {}), '(img)\n', (2736, 2741), False, 'import paddle\n'), ((2949, 2972), 'paddle.to_tensor', 'paddle.to_tensor', (['image'], {}), '(image)\n', (2965, 2972), False, 'import paddle\n')]
|
import numpy as np
import matplotlib.pyplot as plt
from newton_raphson import *
from random import uniform
import numpy.polynomial.legendre as L
###question 0
def E(X):
##Return the value of E(x1,...,xn)
E=0
N=len(X)
for i in range(N):
E+=np.log(abs(X[i]+1))+np.log(abs(X[i]-1))
for j in range(N):
if j!=i:
if X[i]!=X[j]:
E+=np.log(abs(X[i]-X[j]))
else:
return -7 ## To avoid a divsion by 0
return E
def grad_E(X):
## Return the vector grad E as it is described in the subject
n, m = np.shape(X)
assert (m == 1)
res = np.zeros([n,1])
for i in range(n):
s = 0
for j in range(n):
if (i != j):
s += 1. / (X[i, 0] - X[j, 0])
res[i, 0] = 1. / (1 + X[i]) + 1. / (X[i] - 1) + s
return res
def F(X):
return grad_E(X)
###quest1
def Jacobian_E(Y):
## Return the Jacobian matrix of delta_E
N = np.shape(Y)[0]
J=np.zeros((N,N))
for j in range(N):
for i in range(N):
if i==j:
J[j][i]=-1/(Y[i]+1)**2 - 1/(Y[i]-1)**2
for k in range(N):
if k!=j:
J[j][i]+=-1/(Y[i]-Y[k])**2
else:
J[i][j]=1/(Y[i]-Y[j])**2
return J
def J(X):
return Jacobian_E(X)
## Two global lists to the display of the curve
norme_F=[]
iterations=[]
def Newton_Raphson_curve(f, J, U0, N, eps):
## The Newton-Raphson algorithm modified to allow the display of the curve ||F(X)||
global norme_F
global iterations
norme_F=[]
iterations=[]
"""
Solve nonlinear system F=0 by Newton-Raphson's method.
J is the Jacobian of F. At input, U0 is the starting
position of the algorithm. The iteration continues
until ||F|| < eps or until N iterations are reached.
"""
F_value = f(U0)
U = U0
F_norm = np.linalg.norm(F_value, ord=2)
iteration_counter = 0
norme_F.append(F_norm)
iterations.append(iteration_counter)
while abs(F_norm) > eps and iteration_counter < N:
V = np.linalg.solve(J(U), -F_value)
U = U + V
F_value = f(U)
F_norm = np.linalg.norm(F_value, ord=2)
iteration_counter += 1
norme_F.append(F_norm)
iterations.append(iteration_counter)
# Here, either a solution is found, or too many iterations
if abs(F_norm) > eps:
iteration_counter = -1
return U, iteration_counter
def Newton_Raphson_backtracking_curve(f, J, U0, N, eps, alpha):
## The Newton-Raphson algorithm with backtracking modified to allow the display of the curve ||F(X)||
global norme_F
global iterations
norme_F=[]
iterations=[]
"""
Solve nonlinear system F=0 by Newton-Raphson's method.
J is the Jacobian of F. At input, U0 is the starting
position of the algorithm. The iteration continues
until ||F|| < eps or until N iterations are reached.
There is a backtracking to reach the solution faster.
"""
F_value, U = f(U0), U0
F_norm = np.linalg.norm(F_value, ord=2)
iteration_counter = 0
while abs(F_norm) > eps and iteration_counter < N:
V = np.linalg.lstsq(J(U), -F_value, rcond=None)[0]
nxt_F_norm = np.linalg.norm(f(U + V), ord=2)
i = 0
while nxt_F_norm >= F_norm :
print('BACKTRACKING')
i += 1
nxt_F_norm = np.linalg.norm(f(U + alpha ** i * V), ord=2)
U = U + alpha ** i * V
F_value = f(U)
F_norm = np.linalg.norm(F_value, ord=2)
iteration_counter += 1
norme_F.append(F_norm)
iterations.append(iteration_counter)
# Here, either a solution is found, or too many iterations
if abs(F_norm) > eps:
iteration_counter = -1
return U, iteration_counter
## Initialisation of Ten chosen charges
U0=np.zeros((10,1))
U0[0]=-0.86684278
U0[1]=0.86088026
U0[2]=0.80889216
U0[3]=-0.98098176
U0[4]=0.68707341
U0[5]=0.27329905
U0[6]=-0.07208807
U0[7]=0.6864963
U0[8]=-0.11970087
U0[9]=-0.1899953
#we could have imported the function from newton_raphson.py but this version allows to draw the curve
def Newton_Raphson_with_backtracking(f, J, U0, N, epsilon):
global norme_F
global iterations
norme_F=[]
iterations=[]
F_value, U = f(U0), U0
F_norm = np.linalg.norm(F_value, ord=2)
iteration_counter = 0
for i in range(N):
fu = f(U)
na = np.linalg.norm(fu)
if (na < epsilon):
return U
ju = J(U)
V = np.linalg.lstsq(ju,-fu)[0]
if (np.linalg.norm(f(U+V)) - na >= 0):
V = (1.0/3.0)*V
U = U + V
F_value = f(U)
F_norm = np.linalg.norm(F_value, ord=2)
iteration_counter += 1
norme_F.append(F_norm)
iterations.append(iteration_counter)
return U, iteration_counter
U,iteration_counter=Newton_Raphson_curve(F, J, U0, N=100, eps=1e-8)
def test_equilibrium():
#a function that shows the electrostatic equilibrium with 10 charges with and without backtracking
U,iteration_counter=Newton_Raphson_curve(F, J, U0, N=100, eps=1e-8)
print("Test with 10 charges, initialisation of U0 : ",U0.transpose())
print("Final positions of the charges : ",U.transpose())
plt.plot(iterations,norme_F,label="without backtracking")
plt.title("Electrostatic equilibrium with 10 charges")
Newton_Raphson_with_backtracking(F, J, U0, N=100, epsilon=1e-8)
#plt.plot(iterations,norme_F,label="using backtracking")
plt.xlabel("Number of iterations")
plt.ylabel("||F(X)||")
plt.title("Electrostatic equilibrium with 10 charges with and without backtracking")
plt.semilogy()
plt.legend()
plt.show()
def position_real_axis():
#a function that shows the final position ofthe charges on the real axis
plt.figure(num=2,figsize=(7,1.5))
print("Final positions on the real axis")
plt.title("Position of the charges")
plt.xlabel("x axis")
plt.plot([min(U),max(U)],[0,0],color="red",label="Real axis")
plt.plot(U,[0]*len(U),'o',color="yellow",label="Charge")
plt.legend()
plt.show()
def energy_one_charge_position():
## The plot of the curve for one charge
size=50
O=np.linspace(-0.99,0.99,size)
V=np.zeros((size,1))
for k in range(size):
V[k]=E([O[k]])
print("Graph describing the evolution the electrostatic energy of one charge")
plt.title("Electrostatic energy of one charge")
plt.ylabel("Energy")
plt.xlabel("Position of the charge")
plt.plot(O,V)
plt.show()
def mirror(A):
n = A.size
for i in range(n//2):
tmp = A[i]
A[i] = A[n-i-1]
A[n-i-1] = tmp
return A
#Plot Legendre polynomials and equilibrium positions
def add_plot(X, lbl, clr, type='o'):
Peq = Newton_Raphson(grad_E, Jacobian_E, X, 100, 1e-8)
n= Peq.size
for i in range(n):
plt.plot(Peq[i,0],0,type, color=clr)
c = [0]*(n+2)
c[n+1] = 1
d = L.legder(c)
P = L.leg2poly(d)
P = mirror(P)
Poly = np.poly1d(P)
x = np.linspace(-1,1,100)
y = Poly(x)
plt.plot(x, y, label=lbl, color=clr)
#Electrostatic Equilibrium Test
def elec_equ_test():
A = np.matrix([[0.2]])
B = np.matrix([[0.5],
[0.6]])
C = np.matrix([[0.4],
[-0.5],
[0.7]])
D = np.matrix([[0.4],
[-0.4],
[0.5],
[0.6]])
add_plot(A, 'n=1', 'r')
add_plot(B, 'n=2', 'y')
add_plot(C, 'n=3', 'b')
add_plot(D, 'n=4', 'g')
plt.plot([-1,1], [0,0], 'k')
plt.axis([-1,1,-4,4])
plt.xlabel("x")
plt.ylabel("y")
plt.legend()
plt.title("Legendre polynomials and equilibrium positions")
plt.show()
if __name__ == '__main__':
test_equilibrium()
position_real_axis()
energy_one_charge_position()
elec_equ_test()
|
[
"matplotlib.pyplot.title",
"numpy.poly1d",
"numpy.matrix",
"matplotlib.pyplot.show",
"numpy.linalg.lstsq",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"numpy.zeros",
"matplotlib.pyplot.axis",
"numpy.shape",
"matplotlib.pyplot.figure",
"numpy.polynomial.legendre.leg2poly",
"numpy.linalg.norm",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.semilogy",
"matplotlib.pyplot.xlabel",
"numpy.polynomial.legendre.legder"
] |
[((3963, 3980), 'numpy.zeros', 'np.zeros', (['(10, 1)'], {}), '((10, 1))\n', (3971, 3980), True, 'import numpy as np\n'), ((617, 628), 'numpy.shape', 'np.shape', (['X'], {}), '(X)\n', (625, 628), True, 'import numpy as np\n'), ((659, 675), 'numpy.zeros', 'np.zeros', (['[n, 1]'], {}), '([n, 1])\n', (667, 675), True, 'import numpy as np\n'), ((1021, 1037), 'numpy.zeros', 'np.zeros', (['(N, N)'], {}), '((N, N))\n', (1029, 1037), True, 'import numpy as np\n'), ((1957, 1987), 'numpy.linalg.norm', 'np.linalg.norm', (['F_value'], {'ord': '(2)'}), '(F_value, ord=2)\n', (1971, 1987), True, 'import numpy as np\n'), ((3129, 3159), 'numpy.linalg.norm', 'np.linalg.norm', (['F_value'], {'ord': '(2)'}), '(F_value, ord=2)\n', (3143, 3159), True, 'import numpy as np\n'), ((4434, 4464), 'numpy.linalg.norm', 'np.linalg.norm', (['F_value'], {'ord': '(2)'}), '(F_value, ord=2)\n', (4448, 4464), True, 'import numpy as np\n'), ((5382, 5441), 'matplotlib.pyplot.plot', 'plt.plot', (['iterations', 'norme_F'], {'label': '"""without backtracking"""'}), "(iterations, norme_F, label='without backtracking')\n", (5390, 5441), True, 'import matplotlib.pyplot as plt\n'), ((5444, 5498), 'matplotlib.pyplot.title', 'plt.title', (['"""Electrostatic equilibrium with 10 charges"""'], {}), "('Electrostatic equilibrium with 10 charges')\n", (5453, 5498), True, 'import matplotlib.pyplot as plt\n'), ((5632, 5666), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Number of iterations"""'], {}), "('Number of iterations')\n", (5642, 5666), True, 'import matplotlib.pyplot as plt\n'), ((5671, 5693), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""||F(X)||"""'], {}), "('||F(X)||')\n", (5681, 5693), True, 'import matplotlib.pyplot as plt\n'), ((5698, 5787), 'matplotlib.pyplot.title', 'plt.title', (['"""Electrostatic equilibrium with 10 charges with and without backtracking"""'], {}), "(\n 'Electrostatic equilibrium with 10 charges with and without backtracking')\n", (5707, 5787), True, 'import matplotlib.pyplot as plt\n'), ((5787, 5801), 'matplotlib.pyplot.semilogy', 'plt.semilogy', ([], {}), '()\n', (5799, 5801), True, 'import matplotlib.pyplot as plt\n'), ((5806, 5818), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (5816, 5818), True, 'import matplotlib.pyplot as plt\n'), ((5823, 5833), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5831, 5833), True, 'import matplotlib.pyplot as plt\n'), ((5942, 5977), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'num': '(2)', 'figsize': '(7, 1.5)'}), '(num=2, figsize=(7, 1.5))\n', (5952, 5977), True, 'import matplotlib.pyplot as plt\n'), ((6026, 6062), 'matplotlib.pyplot.title', 'plt.title', (['"""Position of the charges"""'], {}), "('Position of the charges')\n", (6035, 6062), True, 'import matplotlib.pyplot as plt\n'), ((6067, 6087), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x axis"""'], {}), "('x axis')\n", (6077, 6087), True, 'import matplotlib.pyplot as plt\n'), ((6219, 6231), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (6229, 6231), True, 'import matplotlib.pyplot as plt\n'), ((6236, 6246), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6244, 6246), True, 'import matplotlib.pyplot as plt\n'), ((6345, 6375), 'numpy.linspace', 'np.linspace', (['(-0.99)', '(0.99)', 'size'], {}), '(-0.99, 0.99, size)\n', (6356, 6375), True, 'import numpy as np\n'), ((6380, 6399), 'numpy.zeros', 'np.zeros', (['(size, 1)'], {}), '((size, 1))\n', (6388, 6399), True, 'import numpy as np\n'), ((6535, 6582), 'matplotlib.pyplot.title', 'plt.title', (['"""Electrostatic energy of one charge"""'], {}), "('Electrostatic energy of one charge')\n", (6544, 6582), True, 'import matplotlib.pyplot as plt\n'), ((6587, 6607), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Energy"""'], {}), "('Energy')\n", (6597, 6607), True, 'import matplotlib.pyplot as plt\n'), ((6612, 6648), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Position of the charge"""'], {}), "('Position of the charge')\n", (6622, 6648), True, 'import matplotlib.pyplot as plt\n'), ((6653, 6667), 'matplotlib.pyplot.plot', 'plt.plot', (['O', 'V'], {}), '(O, V)\n', (6661, 6667), True, 'import matplotlib.pyplot as plt\n'), ((6671, 6681), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (6679, 6681), True, 'import matplotlib.pyplot as plt\n'), ((7105, 7116), 'numpy.polynomial.legendre.legder', 'L.legder', (['c'], {}), '(c)\n', (7113, 7116), True, 'import numpy.polynomial.legendre as L\n'), ((7125, 7138), 'numpy.polynomial.legendre.leg2poly', 'L.leg2poly', (['d'], {}), '(d)\n', (7135, 7138), True, 'import numpy.polynomial.legendre as L\n'), ((7169, 7181), 'numpy.poly1d', 'np.poly1d', (['P'], {}), '(P)\n', (7178, 7181), True, 'import numpy as np\n'), ((7190, 7213), 'numpy.linspace', 'np.linspace', (['(-1)', '(1)', '(100)'], {}), '(-1, 1, 100)\n', (7201, 7213), True, 'import numpy as np\n'), ((7232, 7268), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y'], {'label': 'lbl', 'color': 'clr'}), '(x, y, label=lbl, color=clr)\n', (7240, 7268), True, 'import matplotlib.pyplot as plt\n'), ((7334, 7352), 'numpy.matrix', 'np.matrix', (['[[0.2]]'], {}), '([[0.2]])\n', (7343, 7352), True, 'import numpy as np\n'), ((7362, 7387), 'numpy.matrix', 'np.matrix', (['[[0.5], [0.6]]'], {}), '([[0.5], [0.6]])\n', (7371, 7387), True, 'import numpy as np\n'), ((7416, 7449), 'numpy.matrix', 'np.matrix', (['[[0.4], [-0.5], [0.7]]'], {}), '([[0.4], [-0.5], [0.7]])\n', (7425, 7449), True, 'import numpy as np\n'), ((7497, 7537), 'numpy.matrix', 'np.matrix', (['[[0.4], [-0.4], [0.5], [0.6]]'], {}), '([[0.4], [-0.4], [0.5], [0.6]])\n', (7506, 7537), True, 'import numpy as np\n'), ((7711, 7741), 'matplotlib.pyplot.plot', 'plt.plot', (['[-1, 1]', '[0, 0]', '"""k"""'], {}), "([-1, 1], [0, 0], 'k')\n", (7719, 7741), True, 'import matplotlib.pyplot as plt\n'), ((7744, 7768), 'matplotlib.pyplot.axis', 'plt.axis', (['[-1, 1, -4, 4]'], {}), '([-1, 1, -4, 4])\n', (7752, 7768), True, 'import matplotlib.pyplot as plt\n'), ((7770, 7785), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (7780, 7785), True, 'import matplotlib.pyplot as plt\n'), ((7790, 7805), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""y"""'], {}), "('y')\n", (7800, 7805), True, 'import matplotlib.pyplot as plt\n'), ((7810, 7822), 'matplotlib.pyplot.legend', 'plt.legend', ([], {}), '()\n', (7820, 7822), True, 'import matplotlib.pyplot as plt\n'), ((7827, 7886), 'matplotlib.pyplot.title', 'plt.title', (['"""Legendre polynomials and equilibrium positions"""'], {}), "('Legendre polynomials and equilibrium positions')\n", (7836, 7886), True, 'import matplotlib.pyplot as plt\n'), ((7891, 7901), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (7899, 7901), True, 'import matplotlib.pyplot as plt\n'), ((1000, 1011), 'numpy.shape', 'np.shape', (['Y'], {}), '(Y)\n', (1008, 1011), True, 'import numpy as np\n'), ((2239, 2269), 'numpy.linalg.norm', 'np.linalg.norm', (['F_value'], {'ord': '(2)'}), '(F_value, ord=2)\n', (2253, 2269), True, 'import numpy as np\n'), ((3616, 3646), 'numpy.linalg.norm', 'np.linalg.norm', (['F_value'], {'ord': '(2)'}), '(F_value, ord=2)\n', (3630, 3646), True, 'import numpy as np\n'), ((4545, 4563), 'numpy.linalg.norm', 'np.linalg.norm', (['fu'], {}), '(fu)\n', (4559, 4563), True, 'import numpy as np\n'), ((4802, 4832), 'numpy.linalg.norm', 'np.linalg.norm', (['F_value'], {'ord': '(2)'}), '(F_value, ord=2)\n', (4816, 4832), True, 'import numpy as np\n'), ((7017, 7056), 'matplotlib.pyplot.plot', 'plt.plot', (['Peq[i, 0]', '(0)', 'type'], {'color': 'clr'}), '(Peq[i, 0], 0, type, color=clr)\n', (7025, 7056), True, 'import matplotlib.pyplot as plt\n'), ((4642, 4666), 'numpy.linalg.lstsq', 'np.linalg.lstsq', (['ju', '(-fu)'], {}), '(ju, -fu)\n', (4657, 4666), True, 'import numpy as np\n')]
|
# coding: utf-8
import os
import sys
sys.path.append(os.pardir) # 为了导入父目录的文件而进行的设定
import numpy as np
import matplotlib.pyplot as plt
from dataset.mnist import load_mnist
from common.multi_layer_net import MultiLayerNet
from common.optimizer import SGD
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True)
# 为了再现过拟合,减少学习数据
x_train = x_train[:300]
t_train = t_train[:300]
# weight decay(权值衰减)的设定 =======================
#weight_decay_lambda = 0 # 不使用权值衰减的情况
weight_decay_lambda = 0.1
# ====================================================
network = MultiLayerNet(input_size=784, hidden_size_list=[100, 100, 100, 100, 100, 100], output_size=10,
weight_decay_lambda=weight_decay_lambda)
optimizer = SGD(lr=0.01)
max_epochs = 201
train_size = x_train.shape[0]
batch_size = 100
train_loss_list = []
train_acc_list = []
test_acc_list = []
iter_per_epoch = max(train_size / batch_size, 1)
epoch_cnt = 0
for i in range(1000000000):
batch_mask = np.random.choice(train_size, batch_size)
x_batch = x_train[batch_mask]
t_batch = t_train[batch_mask]
grads = network.gradient(x_batch, t_batch)
optimizer.update(network.params, grads)
if i % iter_per_epoch == 0:
train_acc = network.accuracy(x_train, t_train)
test_acc = network.accuracy(x_test, t_test)
train_acc_list.append(train_acc)
test_acc_list.append(test_acc)
# print("epoch:" + str(epoch_cnt) + ", train acc:" + str(train_acc) + ", test acc:" + str(test_acc))
epoch_cnt += 1
if epoch_cnt >= max_epochs:
break
# 3.绘制图形==========
markers = {'train': 'o', 'test': 's'}
x = np.arange(max_epochs)
plt.plot(x, train_acc_list, marker='o', label='train', markevery=10)
plt.plot(x, test_acc_list, marker='s', label='test', markevery=10)
plt.xlabel("epochs")
plt.ylabel("accuracy")
plt.ylim(0, 1.0)
plt.legend(loc='lower right')
plt.show()
|
[
"sys.path.append",
"numpy.random.choice",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.ylim",
"common.optimizer.SGD",
"matplotlib.pyplot.legend",
"dataset.mnist.load_mnist",
"numpy.arange",
"common.multi_layer_net.MultiLayerNet",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel"
] |
[((38, 64), 'sys.path.append', 'sys.path.append', (['os.pardir'], {}), '(os.pardir)\n', (53, 64), False, 'import sys\n'), ((295, 321), 'dataset.mnist.load_mnist', 'load_mnist', ([], {'normalize': '(True)'}), '(normalize=True)\n', (305, 321), False, 'from dataset.mnist import load_mnist\n'), ((567, 707), 'common.multi_layer_net.MultiLayerNet', 'MultiLayerNet', ([], {'input_size': '(784)', 'hidden_size_list': '[100, 100, 100, 100, 100, 100]', 'output_size': '(10)', 'weight_decay_lambda': 'weight_decay_lambda'}), '(input_size=784, hidden_size_list=[100, 100, 100, 100, 100, \n 100], output_size=10, weight_decay_lambda=weight_decay_lambda)\n', (580, 707), False, 'from common.multi_layer_net import MultiLayerNet\n'), ((739, 751), 'common.optimizer.SGD', 'SGD', ([], {'lr': '(0.01)'}), '(lr=0.01)\n', (742, 751), False, 'from common.optimizer import SGD\n'), ((1659, 1680), 'numpy.arange', 'np.arange', (['max_epochs'], {}), '(max_epochs)\n', (1668, 1680), True, 'import numpy as np\n'), ((1681, 1749), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'train_acc_list'], {'marker': '"""o"""', 'label': '"""train"""', 'markevery': '(10)'}), "(x, train_acc_list, marker='o', label='train', markevery=10)\n", (1689, 1749), True, 'import matplotlib.pyplot as plt\n'), ((1750, 1816), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'test_acc_list'], {'marker': '"""s"""', 'label': '"""test"""', 'markevery': '(10)'}), "(x, test_acc_list, marker='s', label='test', markevery=10)\n", (1758, 1816), True, 'import matplotlib.pyplot as plt\n'), ((1817, 1837), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""epochs"""'], {}), "('epochs')\n", (1827, 1837), True, 'import matplotlib.pyplot as plt\n'), ((1838, 1860), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""accuracy"""'], {}), "('accuracy')\n", (1848, 1860), True, 'import matplotlib.pyplot as plt\n'), ((1861, 1877), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(0)', '(1.0)'], {}), '(0, 1.0)\n', (1869, 1877), True, 'import matplotlib.pyplot as plt\n'), ((1878, 1907), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""lower right"""'}), "(loc='lower right')\n", (1888, 1907), True, 'import matplotlib.pyplot as plt\n'), ((1908, 1918), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1916, 1918), True, 'import matplotlib.pyplot as plt\n'), ((988, 1028), 'numpy.random.choice', 'np.random.choice', (['train_size', 'batch_size'], {}), '(train_size, batch_size)\n', (1004, 1028), True, 'import numpy as np\n')]
|
'''
FILENAME: pix2pix_data.py
AUTHORS: <NAME>
START DATE: Friday February 25th 2022
CONTACT: <EMAIL>
INFO: preparing data for training with pix2pix model
'''
import sys
from matplotlib.pyplot import bar_label
sys.path.append('/data1/shaohua/code/GANToy')
import glob
import os
import numpy as np
import torch
import torchvision
from torch.utils.data import Dataset
import torchvision.transforms as transforms
from PIL import Image
from options.train_options import args_option
class Pix2PixDataset(Dataset):
def __init__(self, args, transforms_=None, mode='train'):
self.transform = transforms_
self.args = args
self.filelist = sorted(glob.glob(os.path.join(args.dataroot, args.dataset, mode, '*.jpg')))
def __len__(self):
return len(self.filelist)
def __getitem__(self, index):
img = Image.open(self.filelist[index])
w, h = img.size
img_A = img.crop((0, 0, w // 2, h))
img_B = img.crop((w // 2, 0, w, h))
if self.args.which_direction != 'AtoB':
img_A, img_B = img_B, img_A
# data augmentation
if np.random.random() < 0.5:
img_A = Image.fromarray(np.array(img_A)[:, ::-1, :], 'RGB')
img_B = Image.fromarray(np.array(img_B)[:, ::-1, :], 'RGB')
img_A = self.transform(img_A)
img_B = self.transform(img_B)
return {'A': img_A, 'B': img_B}
if __name__ == '__main__':
from torch.utils.data import DataLoader
args = args_option()
trans = transforms.Compose([
transforms.Resize((args.image_size, args.image_size), Image.BICUBIC),
transforms.ToTensor(),
transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])
datasets = Pix2PixDataset(args, trans)
dataloader = DataLoader(datasets, batch_size=1)
for index, item in enumerate(dataloader):
img_A = item['A']
img_B = item['B']
torchvision.utils.save_image(img_A[0], 'img_A_{}.png'.format(index))
if index >= 10:
break
|
[
"sys.path.append",
"options.train_options.args_option",
"torch.utils.data.DataLoader",
"PIL.Image.open",
"torchvision.transforms.ToTensor",
"numpy.random.random",
"numpy.array",
"torchvision.transforms.Normalize",
"os.path.join",
"torchvision.transforms.Resize"
] |
[((249, 294), 'sys.path.append', 'sys.path.append', (['"""/data1/shaohua/code/GANToy"""'], {}), "('/data1/shaohua/code/GANToy')\n", (264, 294), False, 'import sys\n'), ((1533, 1546), 'options.train_options.args_option', 'args_option', ([], {}), '()\n', (1544, 1546), False, 'from options.train_options import args_option\n'), ((1821, 1855), 'torch.utils.data.DataLoader', 'DataLoader', (['datasets'], {'batch_size': '(1)'}), '(datasets, batch_size=1)\n', (1831, 1855), False, 'from torch.utils.data import DataLoader\n'), ((885, 917), 'PIL.Image.open', 'Image.open', (['self.filelist[index]'], {}), '(self.filelist[index])\n', (895, 917), False, 'from PIL import Image\n'), ((1160, 1178), 'numpy.random.random', 'np.random.random', ([], {}), '()\n', (1176, 1178), True, 'import numpy as np\n'), ((1589, 1657), 'torchvision.transforms.Resize', 'transforms.Resize', (['(args.image_size, args.image_size)', 'Image.BICUBIC'], {}), '((args.image_size, args.image_size), Image.BICUBIC)\n', (1606, 1657), True, 'import torchvision.transforms as transforms\n'), ((1667, 1688), 'torchvision.transforms.ToTensor', 'transforms.ToTensor', ([], {}), '()\n', (1686, 1688), True, 'import torchvision.transforms as transforms\n'), ((1698, 1752), 'torchvision.transforms.Normalize', 'transforms.Normalize', (['(0.5, 0.5, 0.5)', '(0.5, 0.5, 0.5)'], {}), '((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))\n', (1718, 1752), True, 'import torchvision.transforms as transforms\n'), ((718, 774), 'os.path.join', 'os.path.join', (['args.dataroot', 'args.dataset', 'mode', '"""*.jpg"""'], {}), "(args.dataroot, args.dataset, mode, '*.jpg')\n", (730, 774), False, 'import os\n'), ((1222, 1237), 'numpy.array', 'np.array', (['img_A'], {}), '(img_A)\n', (1230, 1237), True, 'import numpy as np\n'), ((1294, 1309), 'numpy.array', 'np.array', (['img_B'], {}), '(img_B)\n', (1302, 1309), True, 'import numpy as np\n')]
|
from collections import Counter
from io import BytesIO
import base64
from PIL import Image, ImageDraw
import numpy as np
from kmeans import KMeans
def rgb2hex(rgb):
return '#{:02x}{:02x}{:02x}'.format(*[int(x) for x in rgb])
def receive_image(buf):
return Image.open(BytesIO(buf))
def image_to_array(img, img_size):
denom = np.sqrt(np.product(img.size[:2]) / img_size**2)
im = np.asarray(img.resize(
(np.array(img.size) / denom).astype(int)), dtype='int32')
X = im.reshape((im.shape[0]*im.shape[1], 3))
return X, im.shape
def image_resize(img, img_size):
denom = np.sqrt(max(1, np.product(img.size[:2]) / img_size**2))
im = np.asarray(img.resize(
(np.array(img.size) / denom).astype(int)), dtype='int32')
img = img.resize((np.array(img.size) / denom).astype(int))
buf = BytesIO()
img.save(buf, format='jpeg')
return base64.b64encode(buf.getvalue()).decode('utf')
def get_clusters(X, algo, n_clusters):
if algo == 'KMeans':
clf = KMeans(n_clusters=n_clusters)
else:
clf = KMeans(n_clusters=n_clusters)
clf.fit(X)
return clf
def get_colors_from_clf(clf, X):
clf_labels = clf.predict(X)
colors = []
hist = []
items = sorted(Counter(clf_labels).items())
for k, v in items:
colors.append(X[clf_labels == k].mean(axis=0).astype(int).tolist())
hist.append(v)
return hist, colors
def get_image_from_clf(clf, colors, X, dims):
recoded = np.array([
[int(y) for y in colors[x]]
for x in clf.predict(X)]).reshape(dims)
buf = BytesIO()
Image.fromarray(np.uint8(recoded)).save(buf, format='jpeg')
return base64.b64encode(buf.getvalue()).decode('utf')
def generate_image(w, h, color):
img_io = BytesIO()
Image.new('RGB', (w, h), color).save(img_io, 'JPEG', quality=90)
img_io.seek(0)
return img_io
|
[
"io.BytesIO",
"PIL.Image.new",
"numpy.uint8",
"numpy.product",
"numpy.array",
"kmeans.KMeans",
"collections.Counter"
] |
[((838, 847), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (845, 847), False, 'from io import BytesIO\n'), ((1597, 1606), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (1604, 1606), False, 'from io import BytesIO\n'), ((1778, 1787), 'io.BytesIO', 'BytesIO', ([], {}), '()\n', (1785, 1787), False, 'from io import BytesIO\n'), ((281, 293), 'io.BytesIO', 'BytesIO', (['buf'], {}), '(buf)\n', (288, 293), False, 'from io import BytesIO\n'), ((1020, 1049), 'kmeans.KMeans', 'KMeans', ([], {'n_clusters': 'n_clusters'}), '(n_clusters=n_clusters)\n', (1026, 1049), False, 'from kmeans import KMeans\n'), ((1074, 1103), 'kmeans.KMeans', 'KMeans', ([], {'n_clusters': 'n_clusters'}), '(n_clusters=n_clusters)\n', (1080, 1103), False, 'from kmeans import KMeans\n'), ((352, 376), 'numpy.product', 'np.product', (['img.size[:2]'], {}), '(img.size[:2])\n', (362, 376), True, 'import numpy as np\n'), ((1792, 1823), 'PIL.Image.new', 'Image.new', (['"""RGB"""', '(w, h)', 'color'], {}), "('RGB', (w, h), color)\n", (1801, 1823), False, 'from PIL import Image, ImageDraw\n'), ((625, 649), 'numpy.product', 'np.product', (['img.size[:2]'], {}), '(img.size[:2])\n', (635, 649), True, 'import numpy as np\n'), ((1253, 1272), 'collections.Counter', 'Counter', (['clf_labels'], {}), '(clf_labels)\n', (1260, 1272), False, 'from collections import Counter\n'), ((1627, 1644), 'numpy.uint8', 'np.uint8', (['recoded'], {}), '(recoded)\n', (1635, 1644), True, 'import numpy as np\n'), ((787, 805), 'numpy.array', 'np.array', (['img.size'], {}), '(img.size)\n', (795, 805), True, 'import numpy as np\n'), ((433, 451), 'numpy.array', 'np.array', (['img.size'], {}), '(img.size)\n', (441, 451), True, 'import numpy as np\n'), ((707, 725), 'numpy.array', 'np.array', (['img.size'], {}), '(img.size)\n', (715, 725), True, 'import numpy as np\n')]
|
import numpy as np
from scipy import interpolate
def clean_ibi(events, samping_rate, n=2):
ibi = _ibi(events, samping_rate)
for _ in range(n):
# detect outlier and repalce with nan
outliers = signal_outliers(ibi, samping_rate)
time = np.cumsum(ibi)
# interpolate nan
f = interpolate.interp1d(
time[~outliers], ibi[~outliers], "cubic", fill_value="extrapolate"
)
ibi = f(time) # update
return ibi
def _ibi(events, samping_rate):
"""Inter beat interval at msec scale."""
return np.diff(events) / samping_rate * 1000
def signal_outliers(signal, samping_rate):
"""Number of outliers in Inter beat intervals."""
return _rolling_mad(signal, int(0.5 * samping_rate))
def _mad(arr):
"""Median Absolute Deviation."""
med = np.median(arr)
return med, np.median(np.abs(arr - med))
def _rolling_mad(arr, window):
"""Rolling window MAD outlier detection on 1d array."""
outliers = []
for i in range(window, len(arr)):
cur = arr[(i - window) : i]
med, cur_mad = _mad(cur)
cur_out = cur > (med + cur_mad * 3)
idx = list(np.arange((i - window), i)[cur_out])
outliers += idx
outliers = list(set(outliers))
# turn index into boolean
bool_outliers = np.zeros(arr.shape[0], dtype=bool)
bool_outliers[outliers] = True
return bool_outliers
|
[
"numpy.abs",
"numpy.median",
"numpy.zeros",
"numpy.cumsum",
"numpy.diff",
"numpy.arange",
"scipy.interpolate.interp1d"
] |
[((827, 841), 'numpy.median', 'np.median', (['arr'], {}), '(arr)\n', (836, 841), True, 'import numpy as np\n'), ((1315, 1349), 'numpy.zeros', 'np.zeros', (['arr.shape[0]'], {'dtype': 'bool'}), '(arr.shape[0], dtype=bool)\n', (1323, 1349), True, 'import numpy as np\n'), ((268, 282), 'numpy.cumsum', 'np.cumsum', (['ibi'], {}), '(ibi)\n', (277, 282), True, 'import numpy as np\n'), ((321, 414), 'scipy.interpolate.interp1d', 'interpolate.interp1d', (['time[~outliers]', 'ibi[~outliers]', '"""cubic"""'], {'fill_value': '"""extrapolate"""'}), "(time[~outliers], ibi[~outliers], 'cubic', fill_value=\n 'extrapolate')\n", (341, 414), False, 'from scipy import interpolate\n'), ((569, 584), 'numpy.diff', 'np.diff', (['events'], {}), '(events)\n', (576, 584), True, 'import numpy as np\n'), ((868, 885), 'numpy.abs', 'np.abs', (['(arr - med)'], {}), '(arr - med)\n', (874, 885), True, 'import numpy as np\n'), ((1168, 1192), 'numpy.arange', 'np.arange', (['(i - window)', 'i'], {}), '(i - window, i)\n', (1177, 1192), True, 'import numpy as np\n')]
|
import numpy as np
import matplotlib.pyplot as plt
def f(x):
decay = 10.0
period = decay
return (3.0+0.5*np.sin(2.*np.pi*x/period))*x*np.exp(-x/decay)
# read data from file
xdata, ydata, yerror = np.loadtxt('DecayOcsData.txt', skiprows=5, unpack=True)
# create theoretical fitting curve
x = np.linspace(0, 45, 128)
y = f(x)
# create plot
plt.figure(1, figsize = (7,4.5) )
plt.plot(x, y, 'b-', label="theory")
plt.errorbar(xdata, ydata, fmt='ro', label="data",
xerr=0.75, yerr=yerror, ecolor='k')
plt.xlabel('x')
plt.ylabel('transverse displacement')
plt.legend(loc='upper right')
# save plot to file
plt.savefig('DecayOcsData.pdf')
# display plot on screen
plt.show()
|
[
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.figure",
"numpy.sin",
"numpy.loadtxt",
"numpy.linspace",
"numpy.exp",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.errorbar"
] |
[((210, 265), 'numpy.loadtxt', 'np.loadtxt', (['"""DecayOcsData.txt"""'], {'skiprows': '(5)', 'unpack': '(True)'}), "('DecayOcsData.txt', skiprows=5, unpack=True)\n", (220, 265), True, 'import numpy as np\n'), ((306, 329), 'numpy.linspace', 'np.linspace', (['(0)', '(45)', '(128)'], {}), '(0, 45, 128)\n', (317, 329), True, 'import numpy as np\n'), ((354, 385), 'matplotlib.pyplot.figure', 'plt.figure', (['(1)'], {'figsize': '(7, 4.5)'}), '(1, figsize=(7, 4.5))\n', (364, 385), True, 'import matplotlib.pyplot as plt\n'), ((388, 424), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""b-"""'], {'label': '"""theory"""'}), "(x, y, 'b-', label='theory')\n", (396, 424), True, 'import matplotlib.pyplot as plt\n'), ((425, 515), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['xdata', 'ydata'], {'fmt': '"""ro"""', 'label': '"""data"""', 'xerr': '(0.75)', 'yerr': 'yerror', 'ecolor': '"""k"""'}), "(xdata, ydata, fmt='ro', label='data', xerr=0.75, yerr=yerror,\n ecolor='k')\n", (437, 515), True, 'import matplotlib.pyplot as plt\n'), ((526, 541), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""x"""'], {}), "('x')\n", (536, 541), True, 'import matplotlib.pyplot as plt\n'), ((542, 579), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""transverse displacement"""'], {}), "('transverse displacement')\n", (552, 579), True, 'import matplotlib.pyplot as plt\n'), ((580, 609), 'matplotlib.pyplot.legend', 'plt.legend', ([], {'loc': '"""upper right"""'}), "(loc='upper right')\n", (590, 609), True, 'import matplotlib.pyplot as plt\n'), ((631, 662), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""DecayOcsData.pdf"""'], {}), "('DecayOcsData.pdf')\n", (642, 662), True, 'import matplotlib.pyplot as plt\n'), ((689, 699), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (697, 699), True, 'import matplotlib.pyplot as plt\n'), ((147, 165), 'numpy.exp', 'np.exp', (['(-x / decay)'], {}), '(-x / decay)\n', (153, 165), True, 'import numpy as np\n'), ((118, 150), 'numpy.sin', 'np.sin', (['(2.0 * np.pi * x / period)'], {}), '(2.0 * np.pi * x / period)\n', (124, 150), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# As v1, but using scipy.sparse.diags instead of spdiags
"""
Functions for solving a 1D diffusion equations of simplest types
(constant coefficient, no source term):
u_t = a*u_xx on (0,L)
with boundary conditions u=0 on x=0,L, for t in (0,T].
Initial condition: u(x,0)=I(x).
The following naming convention of variables are used.
===== ==========================================================
Name Description
===== ==========================================================
Nx The total number of mesh cells; mesh points are numbered
from 0 to Nx.
F The dimensionless number a*dt/dx**2, which implicitly
specifies the time step.
T The stop time for the simulation.
I Initial condition (Python function of x).
a Variable coefficient (constant).
L Length of the domain ([0,L]).
x Mesh points in space.
t Mesh points in time.
n Index counter in time.
u Unknown at current/new time level.
u_n u at the previous time level.
dx Constant mesh spacing in x.
dt Constant mesh spacing in t.
===== ==========================================================
user_action is a function of (u, x, t, n), u[i] is the solution at
spatial mesh point x[i] at time t[n], where the calling code
can add visualization, error computations, data analysis,
store solutions, etc.
"""
import sys
import time
# import scitools.std as plt
import scipy.sparse
import scipy.sparse.linalg
import numpy as np
def solver_FE_simple(I, a, f, L, dt, F, T):
"""
Simplest expression of the computational algorithm
using the Forward Euler method and explicit Python loops.
For this method F <= 0.5 for stability.
"""
import time
t0 = time.perf_counter() # For measuring the CPU time
Nt = int(round(T/float(dt)))
t = np.linspace(0, Nt*dt, Nt+1) # Mesh points in time
dx = np.sqrt(a*dt/F)
Nx = int(round(L/dx))
x = np.linspace(0, L, Nx+1) # Mesh points in space
# Make sure dx and dt are compatible with x and t
dx = x[1] - x[0]
dt = t[1] - t[0]
u = np.zeros(Nx+1)
u_n = np.zeros(Nx+1)
# Set initial condition u(x,0) = I(x)
for i in range(0, Nx+1):
u_n[i] = I(x[i])
for n in range(0, Nt):
# Compute u at inner mesh points
for i in range(1, Nx):
u[i] = u_n[i] + F*(u_n[i-1] - 2*u_n[i] + u_n[i+1]) + \
dt*f(x[i], t[n])
# Insert boundary conditions
u[0] = 0
u[Nx] = 0
# Switch variables before next step
# u_n[:] = u # safe, but slow
u_n, u = u, u_n
t1 = time.perf_counter()
return u_n, x, t, t1-t0 # u_n holds latest u
def solver_FE(I, a, f, L, dt, F, T,
user_action=None, version='scalar'):
"""
Vectorized implementation of solver_FE_simple.
"""
t0 = time.perf_counter() # for measuring the CPU time
Nt = int(round(T/float(dt)))
t = np.linspace(0, Nt*dt, Nt+1) # Mesh points in time
dx = np.sqrt(a*dt/F)
Nx = int(round(L/dx))
x = np.linspace(0, L, Nx+1) # Mesh points in space
# Make sure dx and dt are compatible with x and t
dx = x[1] - x[0]
dt = t[1] - t[0]
u = np.zeros(Nx+1) # solution array
u_n = np.zeros(Nx+1) # solution at t-dt
# Set initial condition
for i in range(0, Nx+1):
u_n[i] = I(x[i])
if user_action is not None:
user_action(u_n, x, t, 0)
for n in range(0, Nt):
# Update all inner points
if version == 'scalar':
for i in range(1, Nx):
u[i] = u_n[i] +\
F*(u_n[i-1] - 2*u_n[i] + u_n[i+1]) +\
dt*f(x[i], t[n])
elif version == 'vectorized':
u[1:Nx] = u_n[1:Nx] + \
F*(u_n[0:Nx-1] - 2*u_n[1:Nx] + u_n[2:Nx+1]) +\
dt*f(x[1:Nx], t[n])
else:
raise ValueError('version=%s' % version)
# Insert boundary conditions
u[0] = 0
u[Nx] = 0
if user_action is not None:
user_action(u, x, t, n+1)
# Switch variables before next step
u_n, u = u, u_n
t1 = time.perf_counter()
return t1-t0
def solver_BE_simple(I, a, f, L, dt, F, T, user_action=None):
"""
Simplest expression of the computational algorithm
for the Backward Euler method, using explicit Python loops
and a dense matrix format for the coefficient matrix.
"""
import time
t0 = time.perf_counter() # for measuring the CPU time
Nt = int(round(T/float(dt)))
t = np.linspace(0, Nt*dt, Nt+1) # Mesh points in time
dx = np.sqrt(a*dt/F)
Nx = int(round(L/dx))
x = np.linspace(0, L, Nx+1) # Mesh points in space
# Make sure dx and dt are compatible with x and t
dx = x[1] - x[0]
dt = t[1] - t[0]
u = np.zeros(Nx+1)
u_n = np.zeros(Nx+1)
# Data structures for the linear system
A = np.zeros((Nx+1, Nx+1))
b = np.zeros(Nx+1)
for i in range(1, Nx):
A[i, i-1] = -F
A[i, i+1] = -F
A[i, i] = 1 + 2*F
A[0, 0] = A[Nx, Nx] = 1
# Set initial condition u(x,0) = I(x)
for i in range(0, Nx+1):
u_n[i] = I(x[i])
if user_action is not None:
user_action(u_n, x, t, 0)
for n in range(0, Nt):
# Compute b and solve linear system
for i in range(1, Nx):
b[i] = u_n[i] + dt*f(x[i], t[n+1])
b[0] = b[Nx] = 0
u[:] = np.linalg.solve(A, b)
if user_action is not None:
user_action(u, x, t, n+1)
# Update u_n before next step
u_n, u = u, u_n
t1 = time.perf_counter()
return t1-t0
def solver_BE(I, a, f, L, dt, F, T, user_action=None):
"""
Vectorized implementation of solver_BE_simple using also
a sparse (tridiagonal) matrix for efficiency.
"""
import time
t0 = time.perf_counter() # for measuring the CPU time
Nt = int(round(T/float(dt)))
t = np.linspace(0, Nt*dt, Nt+1) # Mesh points in time
dx = np.sqrt(a*dt/F)
Nx = int(round(L/dx))
x = np.linspace(0, L, Nx+1) # Mesh points in space
# Make sure dx and dt are compatible with x and t
dx = x[1] - x[0]
dt = t[1] - t[0]
u = np.zeros(Nx+1) # Solution array at t[n+1]
u_n = np.zeros(Nx+1) # Solution at t[n]
# Representation of sparse matrix and right-hand side
diagonal = np.zeros(Nx+1)
lower = np.zeros(Nx)
upper = np.zeros(Nx)
b = np.zeros(Nx+1)
# Precompute sparse matrix
diagonal[:] = 1 + 2*F
lower[:] = -F # 1
upper[:] = -F # 1
# Insert boundary conditions
diagonal[0] = 1
upper[0] = 0
diagonal[Nx] = 1
lower[-1] = 0
A = scipy.sparse.diags(
diagonals=[diagonal, lower, upper],
offsets=[0, -1, 1], shape=(Nx+1, Nx+1),
format='csr')
print(A.todense())
# Set initial condition
for i in range(0, Nx+1):
u_n[i] = I(x[i])
if user_action is not None:
user_action(u_n, x, t, 0)
for n in range(0, Nt):
b = u_n + dt*f(x[:], t[n+1])
b[0] = b[-1] = 0.0 # boundary conditions
u[:] = scipy.sparse.linalg.spsolve(A, b)
if user_action is not None:
user_action(u, x, t, n+1)
# Update u_n before next step
# u_n[:] = u
u_n, u = u, u_n
t1 = time.perf_counter()
return t1-t0
def solver_theta(I, a, f, L, dt, F, T, theta=0.5, u_L=0, u_R=0,
user_action=None):
"""
Full solver for the model problem using the theta-rule
difference approximation in time (no restriction on F,
i.e., the time step when theta >= 0.5).
Vectorized implementation and sparse (tridiagonal)
coefficient matrix.
"""
import time
t0 = time.perf_counter() # for measuring the CPU time
Nt = int(round(T/float(dt)))
t = np.linspace(0, Nt*dt, Nt+1) # Mesh points in time
dx = np.sqrt(a*dt/F)
Nx = int(round(L/dx))
x = np.linspace(0, L, Nx+1) # Mesh points in space
# Make sure dx and dt are compatible with x and t
dx = x[1] - x[0]
dt = t[1] - t[0]
u = np.zeros(Nx+1) # solution array at t[n+1]
u_n = np.zeros(Nx+1) # solution at t[n]
# Representation of sparse matrix and right-hand side
diagonal = np.zeros(Nx+1)
lower = np.zeros(Nx)
upper = np.zeros(Nx)
b = np.zeros(Nx+1)
# Precompute sparse matrix (scipy format)
Fl = F*theta
Fr = F*(1-theta)
diagonal[:] = 1 + 2*Fl
lower[:] = -Fl # 1
upper[:] = -Fl # 1
# Insert boundary conditions
diagonal[0] = 1
upper[0] = 0
diagonal[Nx] = 1
lower[-1] = 0
diags = [0, -1, 1]
A = scipy.sparse.diags(
diagonals=[diagonal, lower, upper],
offsets=[0, -1, 1], shape=(Nx+1, Nx+1),
format='csr')
print(A.todense())
# Set initial condition
for i in range(0, Nx+1):
u_n[i] = I(x[i])
if user_action is not None:
user_action(u_n, x, t, 0)
# Time loop
for n in range(0, Nt):
b[1:-1] = u_n[1:-1] + \
Fr*(u_n[:-2] - 2*u_n[1:-1] + u_n[2:]) + \
dt*theta*f(x[1:-1], t[n+1]) + \
dt*(1-theta)*f(x[1:-1], t[n])
b[0] = u_L # Boundary conditions
b[-1] = u_R
u[:] = scipy.sparse.linalg.spsolve(A, b)
if user_action is not None:
user_action(u, x, t, n+1)
# Update u_n before next step
u_n, u = u, u_n
t1 = time.perf_counter()
return t1-t0
def viz(I, a, L, dt, F, T, umin, umax,
scheme='FE', animate=True, framefiles=True):
def plot_u(u, x, t, n):
plt.plot(x, u, 'r-', axis=[0, L, umin, umax],
title='t=%f' % t[n])
if framefiles:
plt.savefig('tmp_frame%04d.png' % n)
if t[n] == 0:
time.sleep(2)
elif not framefiles:
# It takes time to write files so pause is needed
# for screen only animation
time.sleep(0.2)
user_action = plot_u if animate else lambda u, x, t, n: None
cpu = eval('solver_'+scheme)(I, a, L, dt, F, T,
user_action=user_action)
return cpu
def plug(scheme='FE', F=0.5, Nx=50):
L = 1.
a = 1.
T = 0.1
# Compute dt from Nx and F
dx = L/Nx
dt = F/a*dx**2
def I(x):
"""Plug profile as initial condition."""
if abs(x-L/2.0) > 0.1:
return 0
else:
return 1
cpu = viz(I, a, L, dt, F, T,
umin=-0.1, umax=1.1,
scheme=scheme, animate=True, framefiles=True)
print('CPU time:', cpu)
def gaussian(scheme='FE', F=0.5, Nx=50, sigma=0.05):
L = 1.
a = 1.
T = 0.1
# Compute dt from Nx and F
dx = L/Nx
dt = F/a*dx**2
def I(x):
"""Gaussian profile as initial condition."""
return exp(-0.5*((x-L/2.0)**2)/sigma**2)
u, cpu = viz(I, a, L, dt, F, T,
umin=-0.1, umax=1.1,
scheme=scheme, animate=True, framefiles=True)
print('CPU time:', cpu)
def expsin(scheme='FE', F=0.5, m=3):
L = 10.0
a = 1
T = 1.2
def exact(x, t):
return exp(-m**2*pi**2*a/L**2*t)*sin(m*pi/L*x)
def I(x):
return exact(x, 0)
Nx = 80
# Compute dt from Nx and F
dx = L/Nx
dt = F/a*dx**2
viz(I, a, L, dt, F, T, -1, 1, scheme=scheme, animate=True,
framefiles=True)
# Convergence study
def action(u, x, t, n):
e = abs(u - exact(x, t[n])).max()
errors.append(e)
errors = []
Nx_values = [10, 20, 40, 80, 160]
for Nx in Nx_values:
eval('solver_'+scheme)(I, a, L, Nx, F, T, user_action=action)
dt = F*(L/Nx)**2/a
print(dt, errors[-1])
def test_solvers():
def u_exact(x, t):
return x*(L-x)*5*t # fulfills BC at x=0 and x=L
def I(x):
return u_exact(x, 0)
def f(x, t):
return 5*x*(L-x) + 10*a*t
a = 3.5
L = 1.5
Nx = 4
F = 0.5
# Compute dt from Nx and F
dx = L/Nx
dt = F/a*dx**2
def compare(u, x, t, n): # user_action function
"""Compare exact and computed solution."""
u_e = u_exact(x, t[n])
diff = abs(u_e - u).max()
tol = 1E-14
assert diff < tol, 'max diff: %g' % diff
import functools
s = functools.partial # object for calling a function w/args
solvers = [
s(solver_FE_simple, I=I, a=a, f=f, L=L, dt=dt, F=F, T=0.2),
s(solver_FE, I=I, a=a, f=f, L=L, dt=dt, F=F, T=2,
user_action=compare, version='scalar'),
s(solver_FE, I=I, a=a, f=f, L=L, dt=dt, F=F, T=2,
user_action=compare, version='vectorized'),
s(solver_BE_simple, I=I, a=a, f=f, L=L, dt=dt, F=F, T=2,
user_action=compare),
s(solver_BE, I=I, a=a, f=f, L=L, dt=dt, F=F, T=2,
user_action=compare),
s(solver_theta, I=I, a=a, f=f, L=L, dt=dt, F=F, T=2,
theta=0, u_L=0, u_R=0, user_action=compare),
]
# solver_FE_simple has different return from the others
u, x, t, cpu = solvers[0]()
u_e = u_exact(x, t[-1])
diff = abs(u_e - u).max()
tol = 1E-14
print(u_e)
print(u)
assert diff < tol, 'max diff solver_FE_simple: %g' % diff
for solver in solvers:
solver()
if __name__ == '__main__':
if len(sys.argv) < 2:
print("""Usage %s function arg1 arg2 arg3 ...""" % sys.argv[0])
sys.exit(0)
cmd = '%s(%s)' % (sys.argv[1], ', '.join(sys.argv[2:]))
print(cmd)
eval(cmd)
|
[
"numpy.zeros",
"time.perf_counter",
"time.sleep",
"numpy.linspace",
"numpy.linalg.solve",
"sys.exit",
"numpy.sqrt"
] |
[((1720, 1739), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (1737, 1739), False, 'import time\n'), ((1812, 1843), 'numpy.linspace', 'np.linspace', (['(0)', '(Nt * dt)', '(Nt + 1)'], {}), '(0, Nt * dt, Nt + 1)\n', (1823, 1843), True, 'import numpy as np\n'), ((1873, 1892), 'numpy.sqrt', 'np.sqrt', (['(a * dt / F)'], {}), '(a * dt / F)\n', (1880, 1892), True, 'import numpy as np\n'), ((1923, 1948), 'numpy.linspace', 'np.linspace', (['(0)', 'L', '(Nx + 1)'], {}), '(0, L, Nx + 1)\n', (1934, 1948), True, 'import numpy as np\n'), ((2081, 2097), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (2089, 2097), True, 'import numpy as np\n'), ((2106, 2122), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (2114, 2122), True, 'import numpy as np\n'), ((2612, 2631), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2629, 2631), False, 'import time\n'), ((2847, 2866), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (2864, 2866), False, 'import time\n'), ((2939, 2970), 'numpy.linspace', 'np.linspace', (['(0)', '(Nt * dt)', '(Nt + 1)'], {}), '(0, Nt * dt, Nt + 1)\n', (2950, 2970), True, 'import numpy as np\n'), ((3000, 3019), 'numpy.sqrt', 'np.sqrt', (['(a * dt / F)'], {}), '(a * dt / F)\n', (3007, 3019), True, 'import numpy as np\n'), ((3050, 3075), 'numpy.linspace', 'np.linspace', (['(0)', 'L', '(Nx + 1)'], {}), '(0, L, Nx + 1)\n', (3061, 3075), True, 'import numpy as np\n'), ((3208, 3224), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (3216, 3224), True, 'import numpy as np\n'), ((3251, 3267), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (3259, 3267), True, 'import numpy as np\n'), ((4179, 4198), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4196, 4198), False, 'import time\n'), ((4497, 4516), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (4514, 4516), False, 'import time\n'), ((4589, 4620), 'numpy.linspace', 'np.linspace', (['(0)', '(Nt * dt)', '(Nt + 1)'], {}), '(0, Nt * dt, Nt + 1)\n', (4600, 4620), True, 'import numpy as np\n'), ((4650, 4669), 'numpy.sqrt', 'np.sqrt', (['(a * dt / F)'], {}), '(a * dt / F)\n', (4657, 4669), True, 'import numpy as np\n'), ((4700, 4725), 'numpy.linspace', 'np.linspace', (['(0)', 'L', '(Nx + 1)'], {}), '(0, L, Nx + 1)\n', (4711, 4725), True, 'import numpy as np\n'), ((4858, 4874), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (4866, 4874), True, 'import numpy as np\n'), ((4883, 4899), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (4891, 4899), True, 'import numpy as np\n'), ((4951, 4977), 'numpy.zeros', 'np.zeros', (['(Nx + 1, Nx + 1)'], {}), '((Nx + 1, Nx + 1))\n', (4959, 4977), True, 'import numpy as np\n'), ((4982, 4998), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (4990, 4998), True, 'import numpy as np\n'), ((5648, 5667), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (5665, 5667), False, 'import time\n'), ((5894, 5913), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (5911, 5913), False, 'import time\n'), ((5986, 6017), 'numpy.linspace', 'np.linspace', (['(0)', '(Nt * dt)', '(Nt + 1)'], {}), '(0, Nt * dt, Nt + 1)\n', (5997, 6017), True, 'import numpy as np\n'), ((6047, 6066), 'numpy.sqrt', 'np.sqrt', (['(a * dt / F)'], {}), '(a * dt / F)\n', (6054, 6066), True, 'import numpy as np\n'), ((6097, 6122), 'numpy.linspace', 'np.linspace', (['(0)', 'L', '(Nx + 1)'], {}), '(0, L, Nx + 1)\n', (6108, 6122), True, 'import numpy as np\n'), ((6255, 6271), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (6263, 6271), True, 'import numpy as np\n'), ((6308, 6324), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (6316, 6324), True, 'import numpy as np\n'), ((6417, 6433), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (6425, 6433), True, 'import numpy as np\n'), ((6444, 6456), 'numpy.zeros', 'np.zeros', (['Nx'], {}), '(Nx)\n', (6452, 6456), True, 'import numpy as np\n'), ((6469, 6481), 'numpy.zeros', 'np.zeros', (['Nx'], {}), '(Nx)\n', (6477, 6481), True, 'import numpy as np\n'), ((6490, 6506), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (6498, 6506), True, 'import numpy as np\n'), ((7367, 7386), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7384, 7386), False, 'import time\n'), ((7788, 7807), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (7805, 7807), False, 'import time\n'), ((7880, 7911), 'numpy.linspace', 'np.linspace', (['(0)', '(Nt * dt)', '(Nt + 1)'], {}), '(0, Nt * dt, Nt + 1)\n', (7891, 7911), True, 'import numpy as np\n'), ((7941, 7960), 'numpy.sqrt', 'np.sqrt', (['(a * dt / F)'], {}), '(a * dt / F)\n', (7948, 7960), True, 'import numpy as np\n'), ((7991, 8016), 'numpy.linspace', 'np.linspace', (['(0)', 'L', '(Nx + 1)'], {}), '(0, L, Nx + 1)\n', (8002, 8016), True, 'import numpy as np\n'), ((8149, 8165), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (8157, 8165), True, 'import numpy as np\n'), ((8203, 8219), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (8211, 8219), True, 'import numpy as np\n'), ((8313, 8329), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (8321, 8329), True, 'import numpy as np\n'), ((8340, 8352), 'numpy.zeros', 'np.zeros', (['Nx'], {}), '(Nx)\n', (8348, 8352), True, 'import numpy as np\n'), ((8365, 8377), 'numpy.zeros', 'np.zeros', (['Nx'], {}), '(Nx)\n', (8373, 8377), True, 'import numpy as np\n'), ((8386, 8402), 'numpy.zeros', 'np.zeros', (['(Nx + 1)'], {}), '(Nx + 1)\n', (8394, 8402), True, 'import numpy as np\n'), ((9502, 9521), 'time.perf_counter', 'time.perf_counter', ([], {}), '()\n', (9519, 9521), False, 'import time\n'), ((5478, 5499), 'numpy.linalg.solve', 'np.linalg.solve', (['A', 'b'], {}), '(A, b)\n', (5493, 5499), True, 'import numpy as np\n'), ((13485, 13496), 'sys.exit', 'sys.exit', (['(0)'], {}), '(0)\n', (13493, 13496), False, 'import sys\n'), ((9860, 9873), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (9870, 9873), False, 'import time\n'), ((10017, 10032), 'time.sleep', 'time.sleep', (['(0.2)'], {}), '(0.2)\n', (10027, 10032), False, 'import time\n')]
|
import copy
from typing import List
import numpy as np
from numpy.core import ndarray
from .hg import Histogram
# import matplotlib.pyplot as plt
to_print = False
class NewForest:
"""This creates a forest of trees, given the following list of parameters:
1) n_trees: the number of trees
2) max_depth: the depth of the trees
3) max_samples: number of samples per tree
4) max_buckets: maximum number of buckets used by the histogram
5) epsilon: accuracy of the histogram"""
dim = ... # type: int
size = ... # type: int
points = ... # type: ndarray
start = ... # type: ndarray
end = ... # type: ndarray
def __init__(self, **kwargs):
self.n_trees = kwargs['n_trees']
self.max_depth = kwargs['max_depth']
self.max_samples = kwargs['max_samples']
self.max_buckets = kwargs['max_buckets']
self.epsilon = kwargs['epsilon']
self.sample_axis = kwargs['sample_axis']
self.threshold = kwargs['threshold']
self.tree = []
self.bucket_profile = np.zeros(self.max_buckets)
self.num_leaves = 0
def fit(self, pts):
self.points = pts
self.dim, self.size = np.shape(self.points)
if int(self.sample_axis * self.dim) == 0:
print("sample_axis is too low")
return
self.start = np.zeros((self.dim, 1))
self.end = np.zeros((self.dim, 1))
for axis in range(self.dim):
val = np.unique(np.array(self.points[axis]))
if len(val) <= 1:
print("No entropy in dimension :", axis)
return
self.start[axis] = (3 * val[0] - val[1]) / 2
self.end[axis] = (3 * val[-1] - val[-2]) / 2
k_args = {'depth': 0, 'forest': self}
sample = np.random.choice(self.size, self.max_depth * 50, replace=False)
for i in range(self.n_trees):
k_args['indices'] = np.random.choice(self.size, self.max_samples, replace=False)
root_node = Node(**k_args)
root_node.compute_density(sample)
self.tree.append(root_node)
def plt_scores(self, pts):
_, n_pts = np.shape(pts)
n_show = int(2 * self.n_trees / 3)
scores = np.zeros((self.n_trees, n_pts)) # need to do this streaming
indices = [i for i in range(n_pts)]
for i in range(self.n_trees):
self.tree[i].compute_split(pts, indices, scores[i])
for i in range(n_pts):
plt.plot(np.sort(scores[:, i])[:n_show])
plt.show()
def predict(self, pts, err=0.1, pct=50):
_, n_pts = np.shape(pts)
scores = np.zeros((self.n_trees, n_pts)) # need to do this streaming
indices = np.arange(n_pts)
for i in range(self.n_trees):
self.tree[i].compute_split(pts, indices, scores[i])
n_err = int(err * n_pts)
min_score = np.percentile(scores, pct, axis=0)
top_indices = np.argsort(min_score)[:n_err]
anom_pts = {}
anom_scores = {}
anom_pct = {}
for i in range(n_err):
anom_pts[top_indices[i]] = pts[:, top_indices[i]]
anom_scores[top_indices[i]] = scores[:, top_indices[i]]
anom_pct[top_indices[i]] = min_score[top_indices[i]]
return top_indices, anom_pts, anom_scores, anom_pct
class PointSet:
def __init__(self, node, indices):
self.node = node
self.indices = indices
self.val = []
self.count = []
self.gap = []
for axis in range(self.node.forest.dim):
val, count = np.unique(np.array(self.node.forest.points[axis, self.indices]), return_counts=True)
self.val.append(val)
self.count.append(count)
if len(val) <= 1:
gap = [0]
else:
gap = np.zeros(len(val))
gap[0] = (val[0] + val[1]) / 2 - self.node.cube.start[axis]
gap[-1] = self.node.cube.end[axis] - (val[-1] + val[-2]) / 2
for i in range(1, len(val) - 1):
gap[i] = (val[i + 1] - val[i - 1]) / 2
self.gap.append(gap)
class Cube:
def __init__(self, node, start, end):
assert isinstance(node, Node)
self.node = node
self.child = []
self.start = start
self.end = end
self.dim = len(start)
self.split_axis = -1
self.split_vals = []
self.vol = 1
for i in range(self.dim):
self.vol *= (self.end[i] - self.start[i])
def filter_indices(self, indices):
in_lb = self.node.forest.points[:, indices] >= self.start.reshape(self.dim, 1)
in_ub = self.node.forest.points[:, indices] < self.end.reshape(self.dim, 1)
return [indices[i] for i in range(len(indices)) if in_lb[:, i].all() and in_ub[:, i].all()]
def split_indices(self, pts, indices):
if not self.child:
return indices
n_child = len(self.child)
n_arr = len(indices)
if n_arr == 0:
return [[] for _ in range(n_child)]
s_arr = pts[self.split_axis]
s_start = self.start[self.split_axis]
s_end = self.end[self.split_axis]
index_split = [[] for _ in range(n_child)]
index_split[0] = [indices[ind] for ind in range(n_arr) if ((s_arr[ind] >= s_start) and
(s_arr[ind] < self.split_vals[0]))]
index_split[-1] = [indices[ind] for ind in range(n_arr) if ((s_arr[ind] >= self.split_vals[-1]) and
(s_arr[ind] < s_end))]
for k in range(1, n_child - 1):
index_split[k] = [indices[ind] for ind in range(n_arr) if (s_arr[ind] >= self.split_vals[k - 1]) and
(s_arr[ind] < self.split_vals[k])]
return index_split
class Node:
def __init__(self, depth, forest, **kwargs):
self.depth = depth
self.forest = forest
if self.depth == 0:
self.id_string = [0]
self.cube = Cube(self, self.forest.start, self.forest.end)
self.point_set = PointSet(self, kwargs['indices'])
else:
self.id_string = kwargs['id']
self.cube = Cube(self, kwargs['start'], kwargs['end'])
self.point_set = PointSet(self, self.cube.filter_indices(kwargs['indices']))
self.density = -1
self.child = []
if (self.depth < self.forest.max_depth) and (len(self.point_set.indices) > 1):
self.split_node()
def split_node(self):
imp_axis = [axis for axis in range(self.cube.dim) if len(self.point_set.val[axis]) > 1]
if not imp_axis:
return
max_axes = min(len(imp_axis), int(self.forest.sample_axis * self.cube.dim))
s_axes = np.random.choice(imp_axis, max_axes, replace=False)
buckets = {}
var_red = {}
for axis in s_axes:
hist = Histogram(self.point_set.gap[axis] / self.point_set.count[axis], self.point_set.count[axis],
self.forest.max_buckets, self.forest.epsilon)
opt_buckets, var_red[axis], buckets[axis] = hist.best_split()
if np.max(list(var_red.values())) <= self.forest.threshold:
return
self.forest.bucket_profile[opt_buckets - 1] += 1
self.forest.num_leaves += opt_buckets
split_axis = np.random.choice(s_axes, p=list(var_red.values()) / np.sum(list(var_red.values())))
self.cube.split_axis = split_axis
self.cube.split_vals = [(self.point_set.val[split_axis][i - 1] + self.point_set.val[split_axis][i]) / 2 for i in
buckets[split_axis]]
for i in range(len(self.cube.split_vals) + 1):
new_start = np.array(self.cube.start)
new_end = np.array(self.cube.end)
if 0 < i < len(self.cube.split_vals):
new_start[split_axis] = self.cube.split_vals[i - 1]
new_end[split_axis] = self.cube.split_vals[i]
elif i == 0:
new_end[split_axis] = self.cube.split_vals[0]
else: # i == len(self.cube.split_vals)
new_start[split_axis] = self.cube.split_vals[-1]
new_id = copy.deepcopy(self.id_string)
new_id.append(i)
kwargs = {'start': new_start, 'end': new_end}
kwargs.update({'indices': self.point_set.indices, 'id': new_id})
child_node = Node(self.depth + 1, self.forest, **kwargs)
self.child.append(child_node)
self.cube.child.append(child_node.cube)
def compute_density(self, indices):
if len(indices) == 0:
self.density = 0
self.child = []
self.cube.child = []
self.cube.split_axis = -1
return
n_arr = len(indices)
self.density = n_arr / self.cube.vol
if self.child:
index_split = self.cube.split_indices(self.forest.points, indices)
for i in range(len(self.child)):
self.child[i].compute_density(index_split[i])
def compute_split(self, pts, indices, scores):
if self.child:
index_split = self.cube.split_indices(pts, indices)
for i in range(len(self.child)):
if index_split[i]:
self.child[i].compute_split(pts, index_split[i], scores)
else:
scores[indices] = self.density
def __str__(self):
str_val = "Id: " + str(self.id_string) + "\n"
str_val += "Boundary: "
for i in range(self.cube.dim):
str_val += " [" + str(self.cube.start[i]) + ", " + str(self.cube.end[i]) + "]"
if i < self.cube.dim - 1:
str_val += " x"
else:
str_val += "\n"
str_val += "Indices: " + str(self.point_set.indices) + "\n"
return str_val
def print_node(self):
print_list = [self]
while print_list:
node = print_list.pop(0)
print(str(node))
print_list.extend(node.child)
|
[
"copy.deepcopy",
"numpy.zeros",
"numpy.shape",
"numpy.percentile",
"numpy.argsort",
"numpy.sort",
"numpy.arange",
"numpy.array",
"numpy.random.choice"
] |
[((1059, 1085), 'numpy.zeros', 'np.zeros', (['self.max_buckets'], {}), '(self.max_buckets)\n', (1067, 1085), True, 'import numpy as np\n'), ((1195, 1216), 'numpy.shape', 'np.shape', (['self.points'], {}), '(self.points)\n', (1203, 1216), True, 'import numpy as np\n'), ((1351, 1374), 'numpy.zeros', 'np.zeros', (['(self.dim, 1)'], {}), '((self.dim, 1))\n', (1359, 1374), True, 'import numpy as np\n'), ((1394, 1417), 'numpy.zeros', 'np.zeros', (['(self.dim, 1)'], {}), '((self.dim, 1))\n', (1402, 1417), True, 'import numpy as np\n'), ((1799, 1862), 'numpy.random.choice', 'np.random.choice', (['self.size', '(self.max_depth * 50)'], {'replace': '(False)'}), '(self.size, self.max_depth * 50, replace=False)\n', (1815, 1862), True, 'import numpy as np\n'), ((2170, 2183), 'numpy.shape', 'np.shape', (['pts'], {}), '(pts)\n', (2178, 2183), True, 'import numpy as np\n'), ((2244, 2275), 'numpy.zeros', 'np.zeros', (['(self.n_trees, n_pts)'], {}), '((self.n_trees, n_pts))\n', (2252, 2275), True, 'import numpy as np\n'), ((2623, 2636), 'numpy.shape', 'np.shape', (['pts'], {}), '(pts)\n', (2631, 2636), True, 'import numpy as np\n'), ((2654, 2685), 'numpy.zeros', 'np.zeros', (['(self.n_trees, n_pts)'], {}), '((self.n_trees, n_pts))\n', (2662, 2685), True, 'import numpy as np\n'), ((2733, 2749), 'numpy.arange', 'np.arange', (['n_pts'], {}), '(n_pts)\n', (2742, 2749), True, 'import numpy as np\n'), ((2905, 2939), 'numpy.percentile', 'np.percentile', (['scores', 'pct'], {'axis': '(0)'}), '(scores, pct, axis=0)\n', (2918, 2939), True, 'import numpy as np\n'), ((6879, 6930), 'numpy.random.choice', 'np.random.choice', (['imp_axis', 'max_axes'], {'replace': '(False)'}), '(imp_axis, max_axes, replace=False)\n', (6895, 6930), True, 'import numpy as np\n'), ((1933, 1993), 'numpy.random.choice', 'np.random.choice', (['self.size', 'self.max_samples'], {'replace': '(False)'}), '(self.size, self.max_samples, replace=False)\n', (1949, 1993), True, 'import numpy as np\n'), ((2962, 2983), 'numpy.argsort', 'np.argsort', (['min_score'], {}), '(min_score)\n', (2972, 2983), True, 'import numpy as np\n'), ((7852, 7877), 'numpy.array', 'np.array', (['self.cube.start'], {}), '(self.cube.start)\n', (7860, 7877), True, 'import numpy as np\n'), ((7900, 7923), 'numpy.array', 'np.array', (['self.cube.end'], {}), '(self.cube.end)\n', (7908, 7923), True, 'import numpy as np\n'), ((8329, 8358), 'copy.deepcopy', 'copy.deepcopy', (['self.id_string'], {}), '(self.id_string)\n', (8342, 8358), False, 'import copy\n'), ((1483, 1510), 'numpy.array', 'np.array', (['self.points[axis]'], {}), '(self.points[axis])\n', (1491, 1510), True, 'import numpy as np\n'), ((3612, 3665), 'numpy.array', 'np.array', (['self.node.forest.points[axis, self.indices]'], {}), '(self.node.forest.points[axis, self.indices])\n', (3620, 3665), True, 'import numpy as np\n'), ((2503, 2524), 'numpy.sort', 'np.sort', (['scores[:, i]'], {}), '(scores[:, i])\n', (2510, 2524), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
"""The check functions."""
# Authors: <NAME> <<EMAIL>>
#
# License: BSD (3-clause)
import operator
from distutils.version import LooseVersion
import os.path as op
import numpy as np
from ._logging import warn
def _ensure_int(x, name='unknown', must_be='an int'):
"""Ensure a variable is an integer."""
# This is preferred over numbers.Integral, see:
# https://github.com/scipy/scipy/pull/7351#issuecomment-299713159
try:
x = int(operator.index(x))
except TypeError:
raise TypeError('%s must be %s, got %s' % (name, must_be, type(x)))
return x
def check_fname(fname, filetype, endings, endings_err=()):
"""Enforce MNE filename conventions.
Parameters
----------
fname : str
Name of the file.
filetype : str
Type of file. e.g., ICA, Epochs etc.
endings : tuple
Acceptable endings for the filename.
endings_err : tuple
Obligatory possible endings for the filename.
"""
if len(endings_err) > 0 and not fname.endswith(endings_err):
print_endings = ' or '.join([', '.join(endings_err[:-1]),
endings_err[-1]])
raise IOError('The filename (%s) for file type %s must end with %s'
% (fname, filetype, print_endings))
print_endings = ' or '.join([', '.join(endings[:-1]), endings[-1]])
if not fname.endswith(endings):
warn('This filename (%s) does not conform to MNE naming conventions. '
'All %s files should end with %s'
% (fname, filetype, print_endings))
def check_version(library, min_version):
r"""Check minimum library version required.
Parameters
----------
library : str
The library name to import. Must have a ``__version__`` property.
min_version : str
The minimum version string. Anything that matches
``'(\d+ | [a-z]+ | \.)'``. Can also be empty to skip version
check (just check for library presence).
Returns
-------
ok : bool
True if the library exists with at least the specified version.
"""
ok = True
try:
library = __import__(library)
except ImportError:
ok = False
else:
if min_version:
this_version = LooseVersion(library.__version__)
if this_version < min_version:
ok = False
return ok
def _check_mayavi_version(min_version='4.3.0'):
"""Check mayavi version."""
if not check_version('mayavi', min_version):
raise RuntimeError("Need mayavi >= %s" % min_version)
def _check_pyface_backend():
"""Check the currently selected Pyface backend.
Returns
-------
backend : str
Name of the backend.
result : 0 | 1 | 2
0: the backend has been tested and works.
1: the backend has not been tested.
2: the backend not been tested.
Notes
-----
See also http://docs.enthought.com/pyface/.
"""
try:
from traits.trait_base import ETSConfig
except ImportError:
return None, 2
backend = ETSConfig.toolkit
if backend == 'qt4':
status = 0
else:
status = 1
return backend, status
def check_random_state(seed):
"""Turn seed into a np.random.RandomState instance.
If seed is None, return the RandomState singleton used by np.random.
If seed is an int, return a new RandomState instance seeded with seed.
If seed is already a RandomState instance, return it.
Otherwise raise ValueError.
"""
if seed is None or seed is np.random:
return np.random.mtrand._rand
if isinstance(seed, (int, np.integer)):
return np.random.RandomState(seed)
if isinstance(seed, np.random.RandomState):
return seed
raise ValueError('%r cannot be used to seed a numpy.random.RandomState'
' instance' % seed)
def _check_event_id(event_id, events):
"""Check event_id and convert to default format."""
# check out event_id dict
if event_id is None: # convert to int to make typing-checks happy
event_id = list(np.unique(events[:, 2]))
if isinstance(event_id, dict):
for key in event_id.keys():
_validate_type(key, str, 'Event names')
event_id = dict((key, _ensure_int(val, 'event_id[%s]' % key))
for key, val in event_id.items())
elif isinstance(event_id, list):
event_id = [_ensure_int(v, 'event_id[%s]' % vi)
for vi, v in enumerate(event_id)]
event_id = dict(zip((str(i) for i in event_id), event_id))
else:
event_id = _ensure_int(event_id, 'event_id')
event_id = {str(event_id): event_id}
return event_id
def _check_fname(fname, overwrite=False, must_exist=False):
"""Check for file existence."""
_validate_type(fname, 'str', 'fname')
from mne.utils import logger
if must_exist and not op.isfile(fname):
raise IOError('File "%s" does not exist' % fname)
if op.isfile(fname):
if not overwrite:
raise IOError('Destination file exists. Please use option '
'"overwrite=True" to force overwriting.')
elif overwrite != 'read':
logger.info('Overwriting existing file.')
def _check_subject(class_subject, input_subject, raise_error=True):
"""Get subject name from class."""
if input_subject is not None:
_validate_type(input_subject, 'str', "subject input")
return input_subject
elif class_subject is not None:
_validate_type(class_subject, 'str',
"Either subject input or class subject attribute")
return class_subject
else:
if raise_error is True:
raise ValueError('Neither subject input nor class subject '
'attribute was a string')
return None
def _check_preload(inst, msg):
"""Ensure data are preloaded."""
from ..epochs import BaseEpochs
from ..evoked import Evoked
from ..time_frequency import _BaseTFR
if isinstance(inst, (_BaseTFR, Evoked)):
pass
else:
name = "epochs" if isinstance(inst, BaseEpochs) else 'raw'
if not inst.preload:
raise RuntimeError(
"By default, MNE does not load data into main memory to "
"conserve resources. " + msg + ' requires %s data to be '
'loaded. Use preload=True (or string) in the constructor or '
'%s.load_data().' % (name, name))
def _check_compensation_grade(inst, inst2, name, name2, ch_names=None):
"""Ensure that objects have same compensation_grade."""
from ..io.pick import pick_channels, pick_info
from ..io.compensator import get_current_comp
if None in [inst.info, inst2.info]:
return
if ch_names is None:
grade = inst.compensation_grade
grade2 = inst2.compensation_grade
else:
info = inst.info.copy()
info2 = inst2.info.copy()
# pick channels
for t_info in [info, info2]:
if t_info['comps']:
t_info['comps'] = []
picks = pick_channels(t_info['ch_names'], ch_names)
pick_info(t_info, picks, copy=False)
# get compensation grades
grade = get_current_comp(info)
grade2 = get_current_comp(info2)
# perform check
if grade != grade2:
msg = 'Compensation grade of %s (%d) and %s (%d) don\'t match'
raise RuntimeError(msg % (name, inst.compensation_grade,
name2, inst2.compensation_grade))
def _check_pandas_installed(strict=True):
"""Aux function."""
try:
import pandas
return pandas
except ImportError:
if strict is True:
raise RuntimeError('For this functionality to work, the Pandas '
'library is required.')
else:
return False
def _check_pandas_index_arguments(index, defaults):
"""Check pandas index arguments."""
if not any(isinstance(index, k) for k in (list, tuple)):
index = [index]
invalid_choices = [e for e in index if e not in defaults]
if invalid_choices:
options = [', '.join(e) for e in [invalid_choices, defaults]]
raise ValueError('[%s] is not an valid option. Valid index'
'values are \'None\' or %s' % tuple(options))
def _check_ch_locs(chs):
"""Check if channel locations exist.
Parameters
----------
chs : dict
The channels from info['chs']
"""
locs3d = np.array([ch['loc'][:3] for ch in chs])
return not ((locs3d == 0).all() or
(~np.isfinite(locs3d)).all() or
np.allclose(locs3d, 0.))
def _check_type_picks(picks):
"""Guarantee type integrity of picks."""
err_msg = 'picks must be None, a list or an array of integers'
if picks is None:
pass
elif isinstance(picks, list):
for pick in picks:
_validate_type(pick, 'int', 'Each pick')
picks = np.array(picks)
elif isinstance(picks, np.ndarray):
if not picks.dtype.kind == 'i':
raise TypeError(err_msg)
else:
raise TypeError(err_msg)
return picks
def _is_numeric(n):
return isinstance(n, (np.integer, np.floating, int, float))
def _validate_type(item, types=None, item_name=None, type_name=None):
"""Validate that `item` is an instance of `types`.
Parameters
----------
item : obj
The thing to be checked.
types : type | tuple of types | str
The types to be checked against. If str, must be one of 'str', 'int',
'numeric'.
"""
if types == "int":
_ensure_int(item, name=item_name)
return # terminate prematurely
elif types == "str":
types = str
type_name = "str" if type_name is None else type_name
elif types == "numeric":
types = (np.integer, np.floating, int, float)
type_name = "numeric" if type_name is None else type_name
elif types == "info":
from mne.io import Info as types
type_name = "Info" if type_name is None else type_name
item_name = "Info" if item_name is None else item_name
if type_name is None:
iter_types = ([types] if not isinstance(types, (list, tuple))
else types)
type_name = ', '.join(cls.__name__ for cls in iter_types)
if not isinstance(item, types):
raise TypeError('%s must be an instance of %s, got %s instead'
% (item_name, type_name, type(item),))
def _check_if_nan(data, msg=" to be plotted"):
"""Raise if any of the values are NaN."""
if not np.isfinite(data).all():
raise ValueError("Some of the values {} are NaN.".format(msg))
|
[
"operator.index",
"mne.utils.logger.info",
"distutils.version.LooseVersion",
"numpy.allclose",
"numpy.isfinite",
"numpy.random.RandomState",
"os.path.isfile",
"numpy.array",
"numpy.unique"
] |
[((5048, 5064), 'os.path.isfile', 'op.isfile', (['fname'], {}), '(fname)\n', (5057, 5064), True, 'import os.path as op\n'), ((8651, 8690), 'numpy.array', 'np.array', (["[ch['loc'][:3] for ch in chs]"], {}), "([ch['loc'][:3] for ch in chs])\n", (8659, 8690), True, 'import numpy as np\n'), ((3713, 3740), 'numpy.random.RandomState', 'np.random.RandomState', (['seed'], {}), '(seed)\n', (3734, 3740), True, 'import numpy as np\n'), ((483, 500), 'operator.index', 'operator.index', (['x'], {}), '(x)\n', (497, 500), False, 'import operator\n'), ((2302, 2335), 'distutils.version.LooseVersion', 'LooseVersion', (['library.__version__'], {}), '(library.__version__)\n', (2314, 2335), False, 'from distutils.version import LooseVersion\n'), ((4148, 4171), 'numpy.unique', 'np.unique', (['events[:, 2]'], {}), '(events[:, 2])\n', (4157, 4171), True, 'import numpy as np\n'), ((4965, 4981), 'os.path.isfile', 'op.isfile', (['fname'], {}), '(fname)\n', (4974, 4981), True, 'import os.path as op\n'), ((8794, 8818), 'numpy.allclose', 'np.allclose', (['locs3d', '(0.0)'], {}), '(locs3d, 0.0)\n', (8805, 8818), True, 'import numpy as np\n'), ((9128, 9143), 'numpy.array', 'np.array', (['picks'], {}), '(picks)\n', (9136, 9143), True, 'import numpy as np\n'), ((5278, 5319), 'mne.utils.logger.info', 'logger.info', (['"""Overwriting existing file."""'], {}), "('Overwriting existing file.')\n", (5289, 5319), False, 'from mne.utils import logger\n'), ((10787, 10804), 'numpy.isfinite', 'np.isfinite', (['data'], {}), '(data)\n', (10798, 10804), True, 'import numpy as np\n'), ((8748, 8767), 'numpy.isfinite', 'np.isfinite', (['locs3d'], {}), '(locs3d)\n', (8759, 8767), True, 'import numpy as np\n')]
|
# --------------
#Importing header files
import pandas as pd
import warnings
warnings.filterwarnings("ignore")
from sklearn.model_selection import train_test_split
# Code starts here
data = pd.read_csv(path)
X = data.drop(['customer.id','paid.back.loan'],axis =1 )
y = data['paid.back.loan']
X_train,X_test,y_train,y_test = train_test_split(X,y,test_size = 0.3, random_state = 0 )
# Code ends here
# --------------
#Importing header files
import matplotlib.pyplot as plt
# Code starts here
fully_paid = y_train.value_counts()
fully_paid.plot(kind = "Bar")
# Code ends here
# --------------
#Importing header files
import numpy as np
from sklearn.preprocessing import LabelEncoder
# Code starts here
X_train['int.rate'] = X_train['int.rate'].str.replace("%","")
X_train['int.rate'] = X_train['int.rate'].apply(float)
X_train['int.rate'] = X_train['int.rate']/100
X_test['int.rate'] = X_test['int.rate'].str.replace("%","")
X_test['int.rate'] = X_test['int.rate'].apply(float)
X_test['int.rate'] = X_test['int.rate']/100
num_df= X_train.select_dtypes(exclude = ['object'])
cat_df = X_train.select_dtypes(include = ['object'])
# Code ends here
# --------------
#Importing header files
import seaborn as sns
# Code starts here
cols = list(num_df.columns)
fig,axes = plt.subplots(nrows = 9 , ncols = 1)
for i in range (0,9):
sns.boxplot(x=y_train, y=num_df[cols[i]] , ax=axes[i])
# Code ends here
# --------------
# Code starts here
cols = list(cat_df.columns)
fig,axes = plt.subplots(nrows = 2 , ncols = 2)
for i in range (0,2):
for j in range(0,2):
sns.countplot(x=X_train[cols[i*2+j]], hue=y_train, ax=axes[i,j])
# Code ends here
# --------------
#Importing header files
from sklearn.tree import DecisionTreeClassifier
from sklearn import tree
# Code starts here
le = LabelEncoder()
X_train['credit.policy'] = le.fit_transform(X_train['credit.policy'])
X_train['purpose'] = le.fit_transform(X_train['purpose'])
X_train['inq.last.6mths'] = le.fit_transform(X_train['inq.last.6mths'])
X_train['delinq.2yrs'] = le.fit_transform(X_train['delinq.2yrs'])
X_test['credit.policy'] = le.fit_transform(X_test['credit.policy'])
X_test['purpose'] = le.fit_transform(X_test['purpose'])
X_test['inq.last.6mths'] = le.fit_transform(X_test['inq.last.6mths'])
X_test['delinq.2yrs'] = le.fit_transform(X_test['delinq.2yrs'])
y_train= y_train.str.replace("No","0")
y_train = y_train.str.replace("Yes","1")
y_test =y_test.str.replace("No","0")
y_test = y_test.str.replace("Yes","1")
model = tree.DecisionTreeClassifier(random_state=0)
model.fit(X_train,y_train)
acc = model.score(X_test,y_test)
print(acc)
# Code ends here
# --------------
#Importing header files
from sklearn.model_selection import GridSearchCV
#Parameter grid
parameter_grid = {'max_depth': np.arange(3,10), 'min_samples_leaf': range(10,50,10)}
# Code starts here
model_2 = tree.DecisionTreeClassifier(random_state=0)
p_tree = GridSearchCV(estimator=model_2, param_grid=parameter_grid,cv=5)
p_tree.fit(X_train,y_train)
acc_2= p_tree.score(X_test,y_test)
print(acc_2)
# Code ends here
# --------------
#Importing header files
from io import StringIO
from sklearn.tree import export_graphviz
from sklearn import tree
from sklearn import metrics
from IPython.display import Image
import pydotplus
# Code starts here
dot_data = export_graphviz(decision_tree=p_tree.best_estimator_, out_file=None, feature_names=X.columns, filled = True , class_names=['loan_paid_back_yes','loan_paid_back_no'])
graph_big = pydotplus.graph_from_dot_data(dot_data)
# show graph - do not delete/modify the code below this line
img_path = user_data_dir+'/file.png'
graph_big.write_png(img_path)
plt.figure(figsize=(20,15))
plt.imshow(plt.imread(img_path))
plt.axis('off')
plt.show()
# Code ends here
|
[
"sklearn.model_selection.GridSearchCV",
"matplotlib.pyplot.show",
"warnings.filterwarnings",
"pandas.read_csv",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.axis",
"sklearn.preprocessing.LabelEncoder",
"sklearn.tree.DecisionTreeClassifier",
"sklearn.tree.export_graphviz",
"pydotplus.graph_from_dot_data",
"matplotlib.pyplot.figure",
"seaborn.boxplot",
"numpy.arange",
"seaborn.countplot",
"matplotlib.pyplot.imread",
"matplotlib.pyplot.subplots"
] |
[((80, 113), 'warnings.filterwarnings', 'warnings.filterwarnings', (['"""ignore"""'], {}), "('ignore')\n", (103, 113), False, 'import warnings\n'), ((196, 213), 'pandas.read_csv', 'pd.read_csv', (['path'], {}), '(path)\n', (207, 213), True, 'import pandas as pd\n'), ((330, 383), 'sklearn.model_selection.train_test_split', 'train_test_split', (['X', 'y'], {'test_size': '(0.3)', 'random_state': '(0)'}), '(X, y, test_size=0.3, random_state=0)\n', (346, 383), False, 'from sklearn.model_selection import train_test_split\n'), ((1285, 1315), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(9)', 'ncols': '(1)'}), '(nrows=9, ncols=1)\n', (1297, 1315), True, 'import matplotlib.pyplot as plt\n'), ((1499, 1529), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {'nrows': '(2)', 'ncols': '(2)'}), '(nrows=2, ncols=2)\n', (1511, 1529), True, 'import matplotlib.pyplot as plt\n'), ((1816, 1830), 'sklearn.preprocessing.LabelEncoder', 'LabelEncoder', ([], {}), '()\n', (1828, 1830), False, 'from sklearn.preprocessing import LabelEncoder\n'), ((2522, 2565), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (2549, 2565), False, 'from sklearn import tree\n'), ((2878, 2921), 'sklearn.tree.DecisionTreeClassifier', 'tree.DecisionTreeClassifier', ([], {'random_state': '(0)'}), '(random_state=0)\n', (2905, 2921), False, 'from sklearn import tree\n'), ((2932, 2996), 'sklearn.model_selection.GridSearchCV', 'GridSearchCV', ([], {'estimator': 'model_2', 'param_grid': 'parameter_grid', 'cv': '(5)'}), '(estimator=model_2, param_grid=parameter_grid, cv=5)\n', (2944, 2996), False, 'from sklearn.model_selection import GridSearchCV\n'), ((3334, 3505), 'sklearn.tree.export_graphviz', 'export_graphviz', ([], {'decision_tree': 'p_tree.best_estimator_', 'out_file': 'None', 'feature_names': 'X.columns', 'filled': '(True)', 'class_names': "['loan_paid_back_yes', 'loan_paid_back_no']"}), "(decision_tree=p_tree.best_estimator_, out_file=None,\n feature_names=X.columns, filled=True, class_names=['loan_paid_back_yes',\n 'loan_paid_back_no'])\n", (3349, 3505), False, 'from sklearn.tree import export_graphviz\n'), ((3512, 3551), 'pydotplus.graph_from_dot_data', 'pydotplus.graph_from_dot_data', (['dot_data'], {}), '(dot_data)\n', (3541, 3551), False, 'import pydotplus\n'), ((3683, 3711), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(20, 15)'}), '(figsize=(20, 15))\n', (3693, 3711), True, 'import matplotlib.pyplot as plt\n'), ((3744, 3759), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (3752, 3759), True, 'import matplotlib.pyplot as plt\n'), ((3760, 3770), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (3768, 3770), True, 'import matplotlib.pyplot as plt\n'), ((1349, 1402), 'seaborn.boxplot', 'sns.boxplot', ([], {'x': 'y_train', 'y': 'num_df[cols[i]]', 'ax': 'axes[i]'}), '(x=y_train, y=num_df[cols[i]], ax=axes[i])\n', (1360, 1402), True, 'import seaborn as sns\n'), ((2794, 2810), 'numpy.arange', 'np.arange', (['(3)', '(10)'], {}), '(3, 10)\n', (2803, 2810), True, 'import numpy as np\n'), ((3722, 3742), 'matplotlib.pyplot.imread', 'plt.imread', (['img_path'], {}), '(img_path)\n', (3732, 3742), True, 'import matplotlib.pyplot as plt\n'), ((1592, 1661), 'seaborn.countplot', 'sns.countplot', ([], {'x': 'X_train[cols[i * 2 + j]]', 'hue': 'y_train', 'ax': 'axes[i, j]'}), '(x=X_train[cols[i * 2 + j]], hue=y_train, ax=axes[i, j])\n', (1605, 1661), True, 'import seaborn as sns\n')]
|
# Some tests for the Cylindrical coordinates handler
import numpy as np
from yt.testing import \
fake_amr_ds, \
assert_equal, \
assert_almost_equal
# Our canonical tests are that we can access all of our fields and we can
# compute our volume correctly.
def test_cylindrical_coordinates():
# We're going to load up a simple AMR grid and check its volume
# calculations and path length calculations.
ds = fake_amr_ds(geometry="cylindrical")
axes = ["r", "z", "theta"]
for i, axis in enumerate(axes):
dd = ds.all_data()
fi = ("index", axis)
fd = ("index", "d%s" % axis)
ma = np.argmax(dd[fi])
assert_equal(dd[fi][ma] + dd[fd][ma] / 2.0, ds.domain_right_edge[i].d)
mi = np.argmin(dd[fi])
assert_equal(dd[fi][mi] - dd[fd][mi] / 2.0, ds.domain_left_edge[i].d)
assert_equal(dd[fd].max(), (ds.domain_width/ds.domain_dimensions)[i].d)
assert_almost_equal(dd["cell_volume"].sum(dtype="float64"),
np.pi*ds.domain_width[0]**2 * ds.domain_width[1])
assert_equal(dd["index", "path_element_r"], dd["index", "dr"])
assert_equal(dd["index", "path_element_z"], dd["index", "dz"])
assert_equal(dd["index", "path_element_theta"],
dd["index", "r"] * dd["index", "dtheta"])
|
[
"yt.testing.fake_amr_ds",
"yt.testing.assert_equal",
"numpy.argmin",
"numpy.argmax"
] |
[((432, 467), 'yt.testing.fake_amr_ds', 'fake_amr_ds', ([], {'geometry': '"""cylindrical"""'}), "(geometry='cylindrical')\n", (443, 467), False, 'from yt.testing import fake_amr_ds, assert_equal, assert_almost_equal\n'), ((1069, 1131), 'yt.testing.assert_equal', 'assert_equal', (["dd['index', 'path_element_r']", "dd['index', 'dr']"], {}), "(dd['index', 'path_element_r'], dd['index', 'dr'])\n", (1081, 1131), False, 'from yt.testing import fake_amr_ds, assert_equal, assert_almost_equal\n'), ((1136, 1198), 'yt.testing.assert_equal', 'assert_equal', (["dd['index', 'path_element_z']", "dd['index', 'dz']"], {}), "(dd['index', 'path_element_z'], dd['index', 'dz'])\n", (1148, 1198), False, 'from yt.testing import fake_amr_ds, assert_equal, assert_almost_equal\n'), ((1203, 1297), 'yt.testing.assert_equal', 'assert_equal', (["dd['index', 'path_element_theta']", "(dd['index', 'r'] * dd['index', 'dtheta'])"], {}), "(dd['index', 'path_element_theta'], dd['index', 'r'] * dd[\n 'index', 'dtheta'])\n", (1215, 1297), False, 'from yt.testing import fake_amr_ds, assert_equal, assert_almost_equal\n'), ((641, 658), 'numpy.argmax', 'np.argmax', (['dd[fi]'], {}), '(dd[fi])\n', (650, 658), True, 'import numpy as np\n'), ((667, 737), 'yt.testing.assert_equal', 'assert_equal', (['(dd[fi][ma] + dd[fd][ma] / 2.0)', 'ds.domain_right_edge[i].d'], {}), '(dd[fi][ma] + dd[fd][ma] / 2.0, ds.domain_right_edge[i].d)\n', (679, 737), False, 'from yt.testing import fake_amr_ds, assert_equal, assert_almost_equal\n'), ((751, 768), 'numpy.argmin', 'np.argmin', (['dd[fi]'], {}), '(dd[fi])\n', (760, 768), True, 'import numpy as np\n'), ((777, 846), 'yt.testing.assert_equal', 'assert_equal', (['(dd[fi][mi] - dd[fd][mi] / 2.0)', 'ds.domain_left_edge[i].d'], {}), '(dd[fi][mi] - dd[fd][mi] / 2.0, ds.domain_left_edge[i].d)\n', (789, 846), False, 'from yt.testing import fake_amr_ds, assert_equal, assert_almost_equal\n')]
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2018 the HERA Project
# Licensed under the MIT License
import os
import argparse
import pyuvdata
from hera_cal.version import version_info
import pyuvdata.utils as uvutils
import numpy as np
parser = argparse.ArgumentParser(description='Extract HERA hex antennas from data '
'file, and save with new extension.')
parser.add_argument('--extension', type=str, help='Extension to be appended to '
'filename for output. Default="HH".', default='HH')
parser.add_argument('--filetype', type=str, help='Input and output file type. '
'Allowed values are "miriad" (default), and "uvfits".',
default='miriad')
parser.add_argument('--fixuvws', action='store_true', help='Optional flag to '
'use antenna positions to replace uvws.')
parser.add_argument('--overwrite', action='store_true', default=False,
help='Optional flag to overwrite output file if it exists.')
parser.add_argument('files', metavar='files', type=str, nargs='+',
help='Files to be processed.')
parser.add_argument('--ex_ants_file', type=str, help='Text file with list of antennas'
' which are excluded downstream in RTP. Generally, these are '
'antennas which are being actively commissioned, or known as bad.'
' Note these values are only stored in the history, not actually '
'flagged at this step.',
default=None)
args = parser.parse_args()
for filename in args.files:
uv = pyuvdata.UVData()
if args.filetype == 'miriad':
uv.read_miriad(filename)
elif args.filetype == 'uvfits':
uv.read_uvfits(filename)
else:
raise ValueError('Unrecognized file type ' + str(args.filetype))
st_type_str = uv.extra_keywords.pop('st_type').replace('\x00', '')
st_type_list = st_type_str[1:-1].split(', ')
ind = [i for i, x in enumerate(st_type_list) if x[:7] == 'herahex' or x == 'heraringa' or x == 'heraringb']
uv.select(antenna_nums=uv.antenna_numbers[ind])
st_type_list = list(np.array(st_type_list)[np.array(ind, dtype=int)])
uv.extra_keywords['st_type'] = '[' + ', '.join(st_type_list) + ']'
uv.history += ' Hera Hex antennas selected'
if args.fixuvws:
antpos = uv.antenna_positions + uv.telescope_location
antpos = uvutils.ENU_from_ECEF(antpos.T, *uv.telescope_location_lat_lon_alt).T
antmap = -np.ones(np.max(uv.antenna_numbers) + 1, dtype=int)
for i, ant in enumerate(uv.antenna_numbers):
antmap[ant] = i
uv.uvw_array = antpos[antmap[uv.ant_2_array], :] - antpos[antmap[uv.ant_1_array], :]
uv.history += ' and uvws corrected'
uv.history += ' with hera_cal/scripts/extract_hh.py, hera_cal version: ' +\
str(version_info) + '.'
if args.ex_ants_file:
ex_ants = np.loadtxt(args.ex_ants_file, dtype=int)
ex_ants = [str(ant) for ant in ex_ants if ant in uv.get_ants()]
uv.history += ' Antennas to exclude in RTP: ' + ','.join(ex_ants) + '.'
if args.filetype == 'miriad':
base, ext = os.path.splitext(filename)
uv.write_miriad(base + '.' + args.extension + ext, clobber=args.overwrite)
else:
base, ext = os.path.splitext(filename)
uv.write_uvfits(base + args.extension + ext, clobber=args.overwrite)
del(uv) # Reset for next loop
|
[
"pyuvdata.UVData",
"argparse.ArgumentParser",
"pyuvdata.utils.ENU_from_ECEF",
"numpy.max",
"numpy.array",
"os.path.splitext",
"numpy.loadtxt"
] |
[((261, 375), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Extract HERA hex antennas from data file, and save with new extension."""'}), "(description=\n 'Extract HERA hex antennas from data file, and save with new extension.')\n", (284, 375), False, 'import argparse\n'), ((1653, 1670), 'pyuvdata.UVData', 'pyuvdata.UVData', ([], {}), '()\n', (1668, 1670), False, 'import pyuvdata\n'), ((2990, 3030), 'numpy.loadtxt', 'np.loadtxt', (['args.ex_ants_file'], {'dtype': 'int'}), '(args.ex_ants_file, dtype=int)\n', (3000, 3030), True, 'import numpy as np\n'), ((3237, 3263), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (3253, 3263), False, 'import os\n'), ((3377, 3403), 'os.path.splitext', 'os.path.splitext', (['filename'], {}), '(filename)\n', (3393, 3403), False, 'import os\n'), ((2198, 2220), 'numpy.array', 'np.array', (['st_type_list'], {}), '(st_type_list)\n', (2206, 2220), True, 'import numpy as np\n'), ((2221, 2245), 'numpy.array', 'np.array', (['ind'], {'dtype': 'int'}), '(ind, dtype=int)\n', (2229, 2245), True, 'import numpy as np\n'), ((2467, 2534), 'pyuvdata.utils.ENU_from_ECEF', 'uvutils.ENU_from_ECEF', (['antpos.T', '*uv.telescope_location_lat_lon_alt'], {}), '(antpos.T, *uv.telescope_location_lat_lon_alt)\n', (2488, 2534), True, 'import pyuvdata.utils as uvutils\n'), ((2563, 2589), 'numpy.max', 'np.max', (['uv.antenna_numbers'], {}), '(uv.antenna_numbers)\n', (2569, 2589), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
from __future__ import print_function # Python 2/3 compatibility
__doc__ = """
Demo ward clustering on a graph: various ways of forming clusters and dendrogram
Requires matplotlib
"""
print(__doc__)
import numpy as np
from numpy.random import randn, rand
try:
import matplotlib.pyplot as plt
except ImportError:
raise RuntimeError("This script needs the matplotlib library")
from nipy.algorithms.graph import knn
from nipy.algorithms.clustering.hierarchical_clustering import ward
# n = number of points, k = number of nearest neighbours
n = 100
k = 5
# Set verbose to True to see more printed output
verbose = False
X = randn(n, 2)
X[:np.ceil(n / 3)] += 3
G = knn(X, 5)
tree = ward(G, X, verbose)
threshold = .5 * n
u = tree.partition(threshold)
plt.figure(figsize=(12, 6))
plt.subplot(1, 3, 1)
for i in range(u.max()+1):
plt.plot(X[u == i, 0], X[u == i, 1], 'o', color=(rand(), rand(), rand()))
plt.axis('tight')
plt.axis('off')
plt.title('clustering into clusters \n of inertia < %g' % threshold)
u = tree.split(k)
plt.subplot(1, 3, 2)
for e in range(G.E):
plt.plot([X[G.edges[e, 0], 0], X[G.edges[e, 1], 0]],
[X[G.edges[e, 0], 1], X[G.edges[e, 1], 1]], 'k')
for i in range(u.max() + 1):
plt.plot(X[u == i, 0], X[u == i, 1], 'o', color=(rand(), rand(), rand()))
plt.axis('tight')
plt.axis('off')
plt.title('clustering into 5 clusters')
nl = np.sum(tree.isleaf())
validleaves = np.zeros(n)
validleaves[:np.ceil(n / 4)] = 1
valid = np.zeros(tree.V, 'bool')
valid[tree.isleaf()] = validleaves.astype('bool')
nv = np.sum(validleaves)
nv0 = 0
while nv > nv0:
nv0 = nv
for v in range(tree.V):
if valid[v]:
valid[tree.parents[v]]=1
nv = np.sum(valid)
ax = plt.subplot(1, 3, 3)
ax = tree.plot(ax)
ax.set_title('Dendrogram')
ax.set_visible(True)
plt.show()
if verbose:
print('List of sub trees')
print(tree.list_of_subtrees())
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.subplot",
"numpy.sum",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.random.randn",
"numpy.ceil",
"nipy.algorithms.clustering.hierarchical_clustering.ward",
"numpy.zeros",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figure",
"nipy.algorithms.graph.knn",
"numpy.random.rand"
] |
[((772, 783), 'numpy.random.randn', 'randn', (['n', '(2)'], {}), '(n, 2)\n', (777, 783), False, 'from numpy.random import randn, rand\n'), ((812, 821), 'nipy.algorithms.graph.knn', 'knn', (['X', '(5)'], {}), '(X, 5)\n', (815, 821), False, 'from nipy.algorithms.graph import knn\n'), ((829, 848), 'nipy.algorithms.clustering.hierarchical_clustering.ward', 'ward', (['G', 'X', 'verbose'], {}), '(G, X, verbose)\n', (833, 848), False, 'from nipy.algorithms.clustering.hierarchical_clustering import ward\n'), ((900, 927), 'matplotlib.pyplot.figure', 'plt.figure', ([], {'figsize': '(12, 6)'}), '(figsize=(12, 6))\n', (910, 927), True, 'import matplotlib.pyplot as plt\n'), ((928, 948), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(1)'], {}), '(1, 3, 1)\n', (939, 948), True, 'import matplotlib.pyplot as plt\n'), ((1055, 1072), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (1063, 1072), True, 'import matplotlib.pyplot as plt\n'), ((1073, 1088), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1081, 1088), True, 'import matplotlib.pyplot as plt\n'), ((1089, 1160), 'matplotlib.pyplot.title', 'plt.title', (['("""clustering into clusters \n of inertia < %g""" % threshold)'], {}), '("""clustering into clusters \n of inertia < %g""" % threshold)\n', (1098, 1160), True, 'import matplotlib.pyplot as plt\n'), ((1177, 1197), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(2)'], {}), '(1, 3, 2)\n', (1188, 1197), True, 'import matplotlib.pyplot as plt\n'), ((1444, 1461), 'matplotlib.pyplot.axis', 'plt.axis', (['"""tight"""'], {}), "('tight')\n", (1452, 1461), True, 'import matplotlib.pyplot as plt\n'), ((1462, 1477), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1470, 1477), True, 'import matplotlib.pyplot as plt\n'), ((1478, 1517), 'matplotlib.pyplot.title', 'plt.title', (['"""clustering into 5 clusters"""'], {}), "('clustering into 5 clusters')\n", (1487, 1517), True, 'import matplotlib.pyplot as plt\n'), ((1560, 1571), 'numpy.zeros', 'np.zeros', (['n'], {}), '(n)\n', (1568, 1571), True, 'import numpy as np\n'), ((1613, 1637), 'numpy.zeros', 'np.zeros', (['tree.V', '"""bool"""'], {}), "(tree.V, 'bool')\n", (1621, 1637), True, 'import numpy as np\n'), ((1693, 1712), 'numpy.sum', 'np.sum', (['validleaves'], {}), '(validleaves)\n', (1699, 1712), True, 'import numpy as np\n'), ((1869, 1889), 'matplotlib.pyplot.subplot', 'plt.subplot', (['(1)', '(3)', '(3)'], {}), '(1, 3, 3)\n', (1880, 1889), True, 'import matplotlib.pyplot as plt\n'), ((1957, 1967), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (1965, 1967), True, 'import matplotlib.pyplot as plt\n'), ((1223, 1328), 'matplotlib.pyplot.plot', 'plt.plot', (['[X[G.edges[e, 0], 0], X[G.edges[e, 1], 0]]', '[X[G.edges[e, 0], 1], X[G.edges[e, 1], 1]]', '"""k"""'], {}), "([X[G.edges[e, 0], 0], X[G.edges[e, 1], 0]], [X[G.edges[e, 0], 1],\n X[G.edges[e, 1], 1]], 'k')\n", (1231, 1328), True, 'import matplotlib.pyplot as plt\n'), ((787, 801), 'numpy.ceil', 'np.ceil', (['(n / 3)'], {}), '(n / 3)\n', (794, 801), True, 'import numpy as np\n'), ((1585, 1599), 'numpy.ceil', 'np.ceil', (['(n / 4)'], {}), '(n / 4)\n', (1592, 1599), True, 'import numpy as np\n'), ((1849, 1862), 'numpy.sum', 'np.sum', (['valid'], {}), '(valid)\n', (1855, 1862), True, 'import numpy as np\n'), ((1029, 1035), 'numpy.random.rand', 'rand', ([], {}), '()\n', (1033, 1035), False, 'from numpy.random import randn, rand\n'), ((1037, 1043), 'numpy.random.rand', 'rand', ([], {}), '()\n', (1041, 1043), False, 'from numpy.random import randn, rand\n'), ((1045, 1051), 'numpy.random.rand', 'rand', ([], {}), '()\n', (1049, 1051), False, 'from numpy.random import randn, rand\n'), ((1419, 1425), 'numpy.random.rand', 'rand', ([], {}), '()\n', (1423, 1425), False, 'from numpy.random import randn, rand\n'), ((1427, 1433), 'numpy.random.rand', 'rand', ([], {}), '()\n', (1431, 1433), False, 'from numpy.random import randn, rand\n'), ((1435, 1441), 'numpy.random.rand', 'rand', ([], {}), '()\n', (1439, 1441), False, 'from numpy.random import randn, rand\n')]
|
from __future__ import print_function
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import IndexLocator, FormatStrFormatter
'''
<NAME>, Dec 2015
Plotting routine for initial 'test' runs of ELC.
It will make a plot that has both light curve data w/fit and RV data w/fit.
There are also residuals in the plots!
(Strongly based on ELCplotter_unfold.py)
***IMPORTANT***
This version assumes the files above are NOT yet folded in phase, and are in time.
This would happen if you are using ELCgap.inp, or anytime when ELC.inp has itime = 2.
So we need to fold them.
(If you want to plot already-folded data, use ELCplotter_new.py)
***ALSO IMPORTANT***
This version assumes you haven't run demcmcELC yet, but just ELC, to get an initial
clue whether or not your input parameters are half decent.
In other words, it doesn't need .fold files or fitparm.all, but it does need ELC.out.
'''
# Colors for plots. Selected with help from colorbrewer.
red = '#e34a33' # red, star 1
yel = '#fdbb84' # yellow, star 2
# Columns in fitparm file that correspond to T0 and Period
#tconj_col = 0
#porb_col = 15
# Read in everything
f1 = 'modelU.mag'
#f2 = 'ELCdataU.fold'
f3 = 'star1.RV'
f4 = 'star2.RV'
ELCoutfile = 'ELC.out'
gridloop = 'gridloop.opt'
#f5 = 'ELCdataRV1.fold'
#f6 = 'ELCdataRV2.fold'
#fitparm = 'fitparm.all'
# OPTIONAL ADJUSTMENT B/C FINAL ELC RV MODEL OUTPUT IS SHIFTED BY GAMMA
#gamma = 0
gamma = input("Enter gamma adjustment (0 for none): ")
phase_mod,mag_mod = np.loadtxt(f1, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
#phase_dat,mag_dat = np.loadtxt(f2, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
phase_rv1,rv1 = np.loadtxt(f3, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
phase_rv2,rv2 = np.loadtxt(f4, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
#phase_rv1dat,rv1dat,rv1err = np.loadtxt(f5, comments='#', dtype=np.float64, usecols=(0,1,2), unpack=True)
#phase_rv2dat,rv2dat,rv2err = np.loadtxt(f6, comments='#', dtype=np.float64, usecols=(0,1,2), unpack=True)
# FUNCTION TO FOLD STUFF so phases are actually phases ... and then sort all the arrays.
def phasecalc(times, period=100, BJD0=2454833):
phases = []
#cycles = []
for i in range(0, len(times)):
fracP = (times[i] - BJD0) / period
if fracP < 0:
phases.append(fracP % 1)
#cycles.append(int(fracP))
else:
phases.append(fracP % 1)
#cycles.append(int(fracP) + 1)
#print(fracP, phases[i])
return np.array(phases)
# GET PERIOD AND T0 from ELC.out file
with open(ELCoutfile) as f:
for i, row in enumerate(f):
if i == 27: # 28th row
columns = row.split()
period = float(columns[0]) # 1st column
#if i == 38: # 39th row, i.e. T0 # this one has a funny zeropoint (ok if circular)
if i == 133: # 134th row, i.e. Tconj # this one puts primary eclipse at phase 0
columns = row.split()
Tconj = float(columns[0]) #1st column
#periods, tconjs = np.loadtxt(fitparm, usecols=(porb_col, tconj_col), unpack=True)
#period = np.median(periods)
#Tconj = np.median(tconjs)
print(period, Tconj)
Tconj = Tconj + 0.5*period
with open(gridloop) as f:
for i, row in enumerate(f):
if i == 0:
LCinfile = row.split()[0]
if i == 8:
RV1infile = row.split()[0]
if i == 9:
RV2infile = row.split()[0]
# Read in observed times, magnitudes, and RVs (calling time 'phase' but that's a lie)
phase_dat,mag_dat = np.loadtxt(LCinfile, comments='#', dtype=np.float64, usecols=(0,1), unpack=True)
phase_rv1dat,rv1dat,rv1err = np.loadtxt(RV1infile, comments='#', dtype=np.float64, usecols=(0,1,2), unpack=True)
phase_rv2dat,rv2dat,rv2err = np.loadtxt(RV2infile, comments='#', dtype=np.float64, usecols=(0,1,2), unpack=True)
# Fold everything (observations and model)
phase_mod = phasecalc(phase_mod, period=period, BJD0=Tconj)
phase_dat = phasecalc(phase_dat, period=period, BJD0=Tconj)
phase_rv1 = phasecalc(phase_rv1, period=period, BJD0=Tconj)
phase_rv2 = phasecalc(phase_rv2, period=period, BJD0=Tconj)
phase_rv1dat = phasecalc(phase_rv1dat, period=period, BJD0=Tconj)
phase_rv2dat = phasecalc(phase_rv2dat, period=period, BJD0=Tconj)
p1 = phase_mod.argsort()
p2 = phase_dat.argsort()
p3 = phase_rv1.argsort()
p4 = phase_rv2.argsort()
p5 = phase_rv1dat.argsort()
p6 = phase_rv2dat.argsort()
phase_mod = phase_mod[p1]
phase_dat = phase_dat[p2]
phase_rv1 = phase_rv1[p3]
phase_rv2 = phase_rv2[p4]
phase_rv1dat = phase_rv1dat[p5]
phase_rv2dat = phase_rv2dat[p6]
mag_mod = mag_mod[p1]
mag_dat = mag_dat[p2]
rv1 = rv1[p3]
rv2 = rv2[p4]
rv1dat = rv1dat[p5]
rv2dat = rv2dat[p6]
# OPTIONAL ADJUSTMENT B/C FINAL ELC RV MODEL OUTPUT IS SHIFTED BY GAMMA
#gamma = input("Enter gamma adjustment (0 for none): ")
rv1 = rv1 + gamma
rv2 = rv2 + gamma
print ("Done reading (and folding) data!")
if np.abs(np.median(mag_mod) - np.median(mag_dat)) > 1:
print('Adjusting magnitude of model light curve...')
mag_mod = mag_mod + (np.median(mag_dat) - np.median(mag_mod))
# Interpolate model onto data phase grid, for residuals
newmag_model = np.interp(phase_dat, phase_mod, mag_mod)
newrv1 = np.interp(phase_rv1dat, phase_rv1, rv1)
newrv2 = np.interp(phase_rv2dat, phase_rv2, rv2)
lcresid = mag_dat - newmag_model
rv1resid = rv1dat - newrv1
rv2resid = rv2dat - newrv2
print ("Done interpolating!")
# Make plots
# First, define some handy global parameters for the plots
phasemin = 0
phasemax = 1
magdim = np.max(mag_dat) + 0.02 #11.97 # remember magnitudes are backwards, dangit
magbright = np.min(mag_dat) - 0.02 #11.861
rvmin = np.min([np.min(rv1dat), np.min(rv2dat)]) - 5 #-79
rvmax = np.max([np.max(rv1dat), np.max(rv2dat)]) + 5 #-1
primary_phasemin = 0.48 #0.09 #0.48
primary_phasemax = 0.52 #0.14 #0.52
secondary_phasemin = 0.98 #0.881
secondary_phasemax = 1.01 #0.921
magresid_min = 0.006 # remember magnitudes are backwards, dangit
magresid_max = -0.006
rvresid_min = -5
rvresid_max = 5
# Light curve
ax1 = plt.subplot2grid((12,1),(4,0), rowspan=3)
plt.axis([phasemin, phasemax, magdim, magbright])
plt.tick_params(axis='both', which='major')
plt.plot(phase_dat, mag_dat, color=red, marker='.', ls='None', ms=6, mew=0) #lc data
plt.plot(phase_mod, mag_mod, 'k', lw=1.5, label='ELC Model') #lc model
ax1.set_ylabel('Magnitude', size=18)
ax1.set_xticklabels([])
# Radial velocities
ax2 = plt.subplot2grid((12,1),(1,0), rowspan=3)
plt.subplots_adjust(wspace = 0.0001, hspace=0.0001)
plt.axis([phasemin, phasemax, rvmin, rvmax])
plt.errorbar(phase_rv1dat, rv1dat, yerr=rv1err, marker='o', color=yel, ms=9, mec='None', ls='None') #rv1 data
plt.errorbar(phase_rv2dat, rv2dat, yerr=rv2err, marker='o', color=red, ms=9, mec='None', ls='None') #rv2 data
plt.plot(phase_rv1, rv1, color='k', lw=1.5) #rv1 model
plt.plot(phase_rv2, rv2, color='k', lw=1.5) #rv2 model
ax2.set_ylabel('Radial Velocity (km s$^{-1}$)', size=18)
ax2.set_xticklabels([])
# Light curve residuals
axr1 = plt.subplot2grid((12,1),(7,0))
axr1.axis([phasemin, phasemax, magresid_min, magresid_max])
axr1.set_yticks([-0.004, 0, 0.004])
plt.axhline(y=0, xmin=phasemin, xmax=phasemax, color='0.75', ls=':')
plt.plot(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0) #lc residual
# Radial velocity residuals
axr2 = plt.subplot2grid((12,1),(0,0))
axr2.axis([phasemin, phasemax, rvresid_min, rvresid_max])
#axr2.set_yticks([-2,0,2])
plt.axhline(y=0, xmin=phasemin, xmax=phasemax, color='0.75', ls=':')
plt.errorbar(phase_rv1dat, rv1resid, yerr=rv1err, marker='o', color=yel, ms=9, mec='None', ls='None') #rv1 residual
plt.errorbar(phase_rv2dat, rv2resid, yerr=rv2err, marker='o', color=red, ms=9, mec='None', ls='None') #rv2 residual
#plt.xlabel('Orbital Phase (conjunction at $\phi = 0.5$)', size=20) # EXTRA LABEL
axr2.set_xticklabels([])
# Zoom-in of shallower (secondary) eclipse
ax3 = plt.subplot2grid((12,2),(9,1), rowspan=2)
plt.axis([secondary_phasemin, secondary_phasemax, magdim, magbright])
ax3.set_xticks([0.89, 0.90, 0.91, 0.92])
plt.plot(phase_dat, mag_dat, color=yel, marker='.', ls='None', ms=6, mew=0) #lc data
plt.plot(phase_mod, mag_mod, color='k', lw=1.5) #lc model
ax3.set_ylabel('Magnitude')
ax3.set_xticklabels([])
ax3.set_yticklabels([])
# Zoom-in of deeper (primary) eclipse
ax4 = plt.subplot2grid((12,2),(9,0), rowspan=2)
plt.axis([primary_phasemin, primary_phasemax, magdim, magbright])
ax4.set_xticks([0.49, 0.50, 0.51, 0.52])
plt.plot(phase_dat, mag_dat, color=red, marker='.', ls='None', ms=6, mew=0) #lc data
plt.plot(phase_mod, mag_mod, color='k', lw=1.5) #lc model
ax4.set_xticklabels([])
#ax4.set_yticklabels([])
# Zoom plot residuals, shallower (secondary) eclipse
axr3 = plt.subplot2grid((12,2),(11,1))
plt.axis([secondary_phasemin, secondary_phasemax, magresid_min, magresid_max])
axr3.set_yticks([-0.004, 0, 0.004])
axr3.set_xticks([0.89, 0.90, 0.91, 0.92])
plt.axhline(y=0, xmin=0, xmax=2, color='0.75', ls=':')
plt.plot(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0) #lc residual
axr3.set_yticklabels([])
# Zoom plot residuals, deeper (primary) eclipse
axr4 = plt.subplot2grid((12,2),(11,0))
plt.axis([primary_phasemin, primary_phasemax, magresid_min, magresid_max])
axr4.set_yticks([-0.004, 0, 0.004])
axr4.set_xticks([0.49, 0.50, 0.51, 0.52])
plt.axhline(y=0, xmin=0, xmax=2, color='0.75', ls=':')
plt.plot(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0) #lc residual
#axr4.set_yticklabels([])
# Labels using overall figure as a reference
plt.figtext(0.5, 0.04, 'Orbital Phase (conjunction at $\phi = 0.5$)', ha='center', va='center', size=25)
#plt.figtext(0.135, 0.18, 'Secondary')
#plt.figtext(0.535, 0.18, 'Primary')
plt.figtext(0.06, 0.86, '$\Delta$')
plt.figtext(0.04, 0.395, '$\Delta$')
plt.figtext(0.04, 0.125, '$\Delta$')
ax1.legend(loc='lower right', frameon=False, prop={'size':20})
print ("Done preparing plot!")
plt.show()
#outfile = 'testplot1.png'
#plt.savefig(outfile)
#print ("Plot saved to %s!" % outfile)
|
[
"matplotlib.pyplot.axhline",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"numpy.median",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.subplot2grid",
"matplotlib.pyplot.axis",
"matplotlib.pyplot.figtext",
"numpy.max",
"numpy.min",
"numpy.array",
"numpy.loadtxt",
"numpy.interp",
"matplotlib.pyplot.errorbar",
"matplotlib.pyplot.subplots_adjust"
] |
[((1544, 1619), 'numpy.loadtxt', 'np.loadtxt', (['f1'], {'comments': '"""#"""', 'dtype': 'np.float64', 'usecols': '(0, 1)', 'unpack': '(True)'}), "(f1, comments='#', dtype=np.float64, usecols=(0, 1), unpack=True)\n", (1554, 1619), True, 'import numpy as np\n'), ((1731, 1806), 'numpy.loadtxt', 'np.loadtxt', (['f3'], {'comments': '"""#"""', 'dtype': 'np.float64', 'usecols': '(0, 1)', 'unpack': '(True)'}), "(f3, comments='#', dtype=np.float64, usecols=(0, 1), unpack=True)\n", (1741, 1806), True, 'import numpy as np\n'), ((1822, 1897), 'numpy.loadtxt', 'np.loadtxt', (['f4'], {'comments': '"""#"""', 'dtype': 'np.float64', 'usecols': '(0, 1)', 'unpack': '(True)'}), "(f4, comments='#', dtype=np.float64, usecols=(0, 1), unpack=True)\n", (1832, 1897), True, 'import numpy as np\n'), ((3491, 3577), 'numpy.loadtxt', 'np.loadtxt', (['LCinfile'], {'comments': '"""#"""', 'dtype': 'np.float64', 'usecols': '(0, 1)', 'unpack': '(True)'}), "(LCinfile, comments='#', dtype=np.float64, usecols=(0, 1), unpack\n =True)\n", (3501, 3577), True, 'import numpy as np\n'), ((3601, 3690), 'numpy.loadtxt', 'np.loadtxt', (['RV1infile'], {'comments': '"""#"""', 'dtype': 'np.float64', 'usecols': '(0, 1, 2)', 'unpack': '(True)'}), "(RV1infile, comments='#', dtype=np.float64, usecols=(0, 1, 2),\n unpack=True)\n", (3611, 3690), True, 'import numpy as np\n'), ((3714, 3803), 'numpy.loadtxt', 'np.loadtxt', (['RV2infile'], {'comments': '"""#"""', 'dtype': 'np.float64', 'usecols': '(0, 1, 2)', 'unpack': '(True)'}), "(RV2infile, comments='#', dtype=np.float64, usecols=(0, 1, 2),\n unpack=True)\n", (3724, 3803), True, 'import numpy as np\n'), ((5109, 5149), 'numpy.interp', 'np.interp', (['phase_dat', 'phase_mod', 'mag_mod'], {}), '(phase_dat, phase_mod, mag_mod)\n', (5118, 5149), True, 'import numpy as np\n'), ((5159, 5198), 'numpy.interp', 'np.interp', (['phase_rv1dat', 'phase_rv1', 'rv1'], {}), '(phase_rv1dat, phase_rv1, rv1)\n', (5168, 5198), True, 'import numpy as np\n'), ((5208, 5247), 'numpy.interp', 'np.interp', (['phase_rv2dat', 'phase_rv2', 'rv2'], {}), '(phase_rv2dat, phase_rv2, rv2)\n', (5217, 5247), True, 'import numpy as np\n'), ((5988, 6032), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(12, 1)', '(4, 0)'], {'rowspan': '(3)'}), '((12, 1), (4, 0), rowspan=3)\n', (6004, 6032), True, 'import matplotlib.pyplot as plt\n'), ((6030, 6079), 'matplotlib.pyplot.axis', 'plt.axis', (['[phasemin, phasemax, magdim, magbright]'], {}), '([phasemin, phasemax, magdim, magbright])\n', (6038, 6079), True, 'import matplotlib.pyplot as plt\n'), ((6080, 6123), 'matplotlib.pyplot.tick_params', 'plt.tick_params', ([], {'axis': '"""both"""', 'which': '"""major"""'}), "(axis='both', which='major')\n", (6095, 6123), True, 'import matplotlib.pyplot as plt\n'), ((6124, 6199), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_dat', 'mag_dat'], {'color': 'red', 'marker': '"""."""', 'ls': '"""None"""', 'ms': '(6)', 'mew': '(0)'}), "(phase_dat, mag_dat, color=red, marker='.', ls='None', ms=6, mew=0)\n", (6132, 6199), True, 'import matplotlib.pyplot as plt\n'), ((6209, 6269), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_mod', 'mag_mod', '"""k"""'], {'lw': '(1.5)', 'label': '"""ELC Model"""'}), "(phase_mod, mag_mod, 'k', lw=1.5, label='ELC Model')\n", (6217, 6269), True, 'import matplotlib.pyplot as plt\n'), ((6368, 6412), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(12, 1)', '(1, 0)'], {'rowspan': '(3)'}), '((12, 1), (1, 0), rowspan=3)\n', (6384, 6412), True, 'import matplotlib.pyplot as plt\n'), ((6410, 6459), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.0001)', 'hspace': '(0.0001)'}), '(wspace=0.0001, hspace=0.0001)\n', (6429, 6459), True, 'import matplotlib.pyplot as plt\n'), ((6462, 6506), 'matplotlib.pyplot.axis', 'plt.axis', (['[phasemin, phasemax, rvmin, rvmax]'], {}), '([phasemin, phasemax, rvmin, rvmax])\n', (6470, 6506), True, 'import matplotlib.pyplot as plt\n'), ((6507, 6610), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['phase_rv1dat', 'rv1dat'], {'yerr': 'rv1err', 'marker': '"""o"""', 'color': 'yel', 'ms': '(9)', 'mec': '"""None"""', 'ls': '"""None"""'}), "(phase_rv1dat, rv1dat, yerr=rv1err, marker='o', color=yel, ms=9,\n mec='None', ls='None')\n", (6519, 6610), True, 'import matplotlib.pyplot as plt\n'), ((6617, 6720), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['phase_rv2dat', 'rv2dat'], {'yerr': 'rv2err', 'marker': '"""o"""', 'color': 'red', 'ms': '(9)', 'mec': '"""None"""', 'ls': '"""None"""'}), "(phase_rv2dat, rv2dat, yerr=rv2err, marker='o', color=red, ms=9,\n mec='None', ls='None')\n", (6629, 6720), True, 'import matplotlib.pyplot as plt\n'), ((6727, 6770), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_rv1', 'rv1'], {'color': '"""k"""', 'lw': '(1.5)'}), "(phase_rv1, rv1, color='k', lw=1.5)\n", (6735, 6770), True, 'import matplotlib.pyplot as plt\n'), ((6782, 6825), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_rv2', 'rv2'], {'color': '"""k"""', 'lw': '(1.5)'}), "(phase_rv2, rv2, color='k', lw=1.5)\n", (6790, 6825), True, 'import matplotlib.pyplot as plt\n'), ((6950, 6983), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(12, 1)', '(7, 0)'], {}), '((12, 1), (7, 0))\n', (6966, 6983), True, 'import matplotlib.pyplot as plt\n'), ((7077, 7145), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': '(0)', 'xmin': 'phasemin', 'xmax': 'phasemax', 'color': '"""0.75"""', 'ls': '""":"""'}), "(y=0, xmin=phasemin, xmax=phasemax, color='0.75', ls=':')\n", (7088, 7145), True, 'import matplotlib.pyplot as plt\n'), ((7146, 7221), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_dat', 'lcresid'], {'color': 'red', 'marker': '"""."""', 'ls': '"""None"""', 'ms': '(4)', 'mew': '(0)'}), "(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0)\n", (7154, 7221), True, 'import matplotlib.pyplot as plt\n'), ((7271, 7304), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(12, 1)', '(0, 0)'], {}), '((12, 1), (0, 0))\n', (7287, 7304), True, 'import matplotlib.pyplot as plt\n'), ((7387, 7455), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': '(0)', 'xmin': 'phasemin', 'xmax': 'phasemax', 'color': '"""0.75"""', 'ls': '""":"""'}), "(y=0, xmin=phasemin, xmax=phasemax, color='0.75', ls=':')\n", (7398, 7455), True, 'import matplotlib.pyplot as plt\n'), ((7456, 7562), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['phase_rv1dat', 'rv1resid'], {'yerr': 'rv1err', 'marker': '"""o"""', 'color': 'yel', 'ms': '(9)', 'mec': '"""None"""', 'ls': '"""None"""'}), "(phase_rv1dat, rv1resid, yerr=rv1err, marker='o', color=yel, ms\n =9, mec='None', ls='None')\n", (7468, 7562), True, 'import matplotlib.pyplot as plt\n'), ((7572, 7678), 'matplotlib.pyplot.errorbar', 'plt.errorbar', (['phase_rv2dat', 'rv2resid'], {'yerr': 'rv2err', 'marker': '"""o"""', 'color': 'red', 'ms': '(9)', 'mec': '"""None"""', 'ls': '"""None"""'}), "(phase_rv2dat, rv2resid, yerr=rv2err, marker='o', color=red, ms\n =9, mec='None', ls='None')\n", (7584, 7678), True, 'import matplotlib.pyplot as plt\n'), ((7845, 7889), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(12, 2)', '(9, 1)'], {'rowspan': '(2)'}), '((12, 2), (9, 1), rowspan=2)\n', (7861, 7889), True, 'import matplotlib.pyplot as plt\n'), ((7887, 7956), 'matplotlib.pyplot.axis', 'plt.axis', (['[secondary_phasemin, secondary_phasemax, magdim, magbright]'], {}), '([secondary_phasemin, secondary_phasemax, magdim, magbright])\n', (7895, 7956), True, 'import matplotlib.pyplot as plt\n'), ((7998, 8073), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_dat', 'mag_dat'], {'color': 'yel', 'marker': '"""."""', 'ls': '"""None"""', 'ms': '(6)', 'mew': '(0)'}), "(phase_dat, mag_dat, color=yel, marker='.', ls='None', ms=6, mew=0)\n", (8006, 8073), True, 'import matplotlib.pyplot as plt\n'), ((8083, 8130), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_mod', 'mag_mod'], {'color': '"""k"""', 'lw': '(1.5)'}), "(phase_mod, mag_mod, color='k', lw=1.5)\n", (8091, 8130), True, 'import matplotlib.pyplot as plt\n'), ((8262, 8306), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(12, 2)', '(9, 0)'], {'rowspan': '(2)'}), '((12, 2), (9, 0), rowspan=2)\n', (8278, 8306), True, 'import matplotlib.pyplot as plt\n'), ((8304, 8369), 'matplotlib.pyplot.axis', 'plt.axis', (['[primary_phasemin, primary_phasemax, magdim, magbright]'], {}), '([primary_phasemin, primary_phasemax, magdim, magbright])\n', (8312, 8369), True, 'import matplotlib.pyplot as plt\n'), ((8411, 8486), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_dat', 'mag_dat'], {'color': 'red', 'marker': '"""."""', 'ls': '"""None"""', 'ms': '(6)', 'mew': '(0)'}), "(phase_dat, mag_dat, color=red, marker='.', ls='None', ms=6, mew=0)\n", (8419, 8486), True, 'import matplotlib.pyplot as plt\n'), ((8496, 8543), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_mod', 'mag_mod'], {'color': '"""k"""', 'lw': '(1.5)'}), "(phase_mod, mag_mod, color='k', lw=1.5)\n", (8504, 8543), True, 'import matplotlib.pyplot as plt\n'), ((8664, 8698), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(12, 2)', '(11, 1)'], {}), '((12, 2), (11, 1))\n', (8680, 8698), True, 'import matplotlib.pyplot as plt\n'), ((8696, 8774), 'matplotlib.pyplot.axis', 'plt.axis', (['[secondary_phasemin, secondary_phasemax, magresid_min, magresid_max]'], {}), '([secondary_phasemin, secondary_phasemax, magresid_min, magresid_max])\n', (8704, 8774), True, 'import matplotlib.pyplot as plt\n'), ((8853, 8907), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': '(0)', 'xmin': '(0)', 'xmax': '(2)', 'color': '"""0.75"""', 'ls': '""":"""'}), "(y=0, xmin=0, xmax=2, color='0.75', ls=':')\n", (8864, 8907), True, 'import matplotlib.pyplot as plt\n'), ((8908, 8983), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_dat', 'lcresid'], {'color': 'red', 'marker': '"""."""', 'ls': '"""None"""', 'ms': '(4)', 'mew': '(0)'}), "(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0)\n", (8916, 8983), True, 'import matplotlib.pyplot as plt\n'), ((9078, 9112), 'matplotlib.pyplot.subplot2grid', 'plt.subplot2grid', (['(12, 2)', '(11, 0)'], {}), '((12, 2), (11, 0))\n', (9094, 9112), True, 'import matplotlib.pyplot as plt\n'), ((9110, 9184), 'matplotlib.pyplot.axis', 'plt.axis', (['[primary_phasemin, primary_phasemax, magresid_min, magresid_max]'], {}), '([primary_phasemin, primary_phasemax, magresid_min, magresid_max])\n', (9118, 9184), True, 'import matplotlib.pyplot as plt\n'), ((9263, 9317), 'matplotlib.pyplot.axhline', 'plt.axhline', ([], {'y': '(0)', 'xmin': '(0)', 'xmax': '(2)', 'color': '"""0.75"""', 'ls': '""":"""'}), "(y=0, xmin=0, xmax=2, color='0.75', ls=':')\n", (9274, 9317), True, 'import matplotlib.pyplot as plt\n'), ((9318, 9393), 'matplotlib.pyplot.plot', 'plt.plot', (['phase_dat', 'lcresid'], {'color': 'red', 'marker': '"""."""', 'ls': '"""None"""', 'ms': '(4)', 'mew': '(0)'}), "(phase_dat, lcresid, color=red, marker='.', ls='None', ms=4, mew=0)\n", (9326, 9393), True, 'import matplotlib.pyplot as plt\n'), ((9479, 9589), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.5)', '(0.04)', '"""Orbital Phase (conjunction at $\\\\phi = 0.5$)"""'], {'ha': '"""center"""', 'va': '"""center"""', 'size': '(25)'}), "(0.5, 0.04, 'Orbital Phase (conjunction at $\\\\phi = 0.5$)', ha=\n 'center', va='center', size=25)\n", (9490, 9589), True, 'import matplotlib.pyplot as plt\n'), ((9660, 9696), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.06)', '(0.86)', '"""$\\\\Delta$"""'], {}), "(0.06, 0.86, '$\\\\Delta$')\n", (9671, 9696), True, 'import matplotlib.pyplot as plt\n'), ((9696, 9733), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.04)', '(0.395)', '"""$\\\\Delta$"""'], {}), "(0.04, 0.395, '$\\\\Delta$')\n", (9707, 9733), True, 'import matplotlib.pyplot as plt\n'), ((9733, 9770), 'matplotlib.pyplot.figtext', 'plt.figtext', (['(0.04)', '(0.125)', '"""$\\\\Delta$"""'], {}), "(0.04, 0.125, '$\\\\Delta$')\n", (9744, 9770), True, 'import matplotlib.pyplot as plt\n'), ((9866, 9876), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (9874, 9876), True, 'import matplotlib.pyplot as plt\n'), ((2524, 2540), 'numpy.array', 'np.array', (['phases'], {}), '(phases)\n', (2532, 2540), True, 'import numpy as np\n'), ((5475, 5490), 'numpy.max', 'np.max', (['mag_dat'], {}), '(mag_dat)\n', (5481, 5490), True, 'import numpy as np\n'), ((5563, 5578), 'numpy.min', 'np.min', (['mag_dat'], {}), '(mag_dat)\n', (5569, 5578), True, 'import numpy as np\n'), ((4874, 4892), 'numpy.median', 'np.median', (['mag_mod'], {}), '(mag_mod)\n', (4883, 4892), True, 'import numpy as np\n'), ((4895, 4913), 'numpy.median', 'np.median', (['mag_dat'], {}), '(mag_dat)\n', (4904, 4913), True, 'import numpy as np\n'), ((4996, 5014), 'numpy.median', 'np.median', (['mag_dat'], {}), '(mag_dat)\n', (5005, 5014), True, 'import numpy as np\n'), ((5017, 5035), 'numpy.median', 'np.median', (['mag_mod'], {}), '(mag_mod)\n', (5026, 5035), True, 'import numpy as np\n'), ((5610, 5624), 'numpy.min', 'np.min', (['rv1dat'], {}), '(rv1dat)\n', (5616, 5624), True, 'import numpy as np\n'), ((5626, 5640), 'numpy.min', 'np.min', (['rv2dat'], {}), '(rv2dat)\n', (5632, 5640), True, 'import numpy as np\n'), ((5668, 5682), 'numpy.max', 'np.max', (['rv1dat'], {}), '(rv1dat)\n', (5674, 5682), True, 'import numpy as np\n'), ((5684, 5698), 'numpy.max', 'np.max', (['rv2dat'], {}), '(rv2dat)\n', (5690, 5698), True, 'import numpy as np\n')]
|
# -*- coding: utf-8 -*-
__all__ = [
'predict',
'redistribute',
'simulate',
'walk_probability'
]
###########
# IMPORTS #
###########
# Libraries
import numpy as _np
# Internal
from .custom_types import (
oint as _oint,
olist_int as _olist_int,
tarray as _tarray,
tlist_int as _tlist_int,
tmc as _tmc,
trand as _trand,
tredists as _tredists
)
#############
# FUNCTIONS #
#############
def predict(mc: _tmc, steps: int, initial_state: int) -> _olist_int:
current_state = initial_state
value = [initial_state]
for _ in range(steps):
d = mc.p[current_state, :]
d_max = _np.argwhere(d == _np.max(d))
if d_max.size > 1:
return None
current_state = d_max.item()
value.append(current_state)
return value
def redistribute(mc: _tmc, steps: int, initial_status: _tarray, output_last: bool) -> _tredists:
value = _np.zeros((steps + 1, mc.size), dtype=float)
value[0, :] = initial_status
for i in range(1, steps + 1):
value[i, :] = value[i - 1, :].dot(mc.p)
value[i, :] /= _np.sum(value[i, :])
if output_last:
return value[-1]
value = [_np.ravel(distribution) for distribution in _np.split(value, value.shape[0])]
return value
def simulate(mc: _tmc, steps: int, initial_state: int, final_state: _oint, rng: _trand) -> _tlist_int:
current_state = initial_state
value = [initial_state]
for _ in range(steps):
w = mc.p[current_state, :]
current_state = rng.choice(mc.size, size=1, p=w).item()
value.append(current_state)
if final_state is not None and current_state == final_state:
break
return value
def walk_probability(mc: _tmc, walk: _tlist_int) -> float:
p = 0.0
for (i, j) in zip(walk[:-1], walk[1:]):
if mc.p[i, j] > 0.0:
p += _np.log(mc.p[i, j])
else:
p = -_np.inf
break
value = _np.exp(p)
return value
|
[
"numpy.sum",
"numpy.log",
"numpy.ravel",
"numpy.zeros",
"numpy.split",
"numpy.max",
"numpy.exp"
] |
[((935, 979), 'numpy.zeros', '_np.zeros', (['(steps + 1, mc.size)'], {'dtype': 'float'}), '((steps + 1, mc.size), dtype=float)\n', (944, 979), True, 'import numpy as _np\n'), ((1990, 2000), 'numpy.exp', '_np.exp', (['p'], {}), '(p)\n', (1997, 2000), True, 'import numpy as _np\n'), ((1119, 1139), 'numpy.sum', '_np.sum', (['value[i, :]'], {}), '(value[i, :])\n', (1126, 1139), True, 'import numpy as _np\n'), ((1200, 1223), 'numpy.ravel', '_np.ravel', (['distribution'], {}), '(distribution)\n', (1209, 1223), True, 'import numpy as _np\n'), ((1244, 1276), 'numpy.split', '_np.split', (['value', 'value.shape[0]'], {}), '(value, value.shape[0])\n', (1253, 1276), True, 'import numpy as _np\n'), ((1900, 1919), 'numpy.log', '_np.log', (['mc.p[i, j]'], {}), '(mc.p[i, j])\n', (1907, 1919), True, 'import numpy as _np\n'), ((667, 677), 'numpy.max', '_np.max', (['d'], {}), '(d)\n', (674, 677), True, 'import numpy as _np\n')]
|
# This example demonstrates prototype of the update model that Ryan, Alex, and Chip discussed.
################################################################################################################################
# Everything here would be part of a DH library
################################################################################################################################
import numpy as np
from deephaven import QueryScope
#TODO: this should be java
class IndexSet:
def __init__(self, max_size):
self.current = -1
self.idx = np.zeros(max_size, dtype=np.int64)
def clear(self):
self.current = -2
self.idx = None
def add(self, kk):
if self.current == self.idx.size:
raise Exception("Adding more indices than can fit")
self.current += 1
self.idx[self.current] = kk
def __len__(self):
return self.current + 1
def __getitem__(self, i):
if i >= len(self):
raise Exception("Index out of bounds")
return self.idx[i]
#TODO: this should be java
class Gatherer:
def __init__(self, batch_size):
self.batch_size = batch_size
self.current = None
def clear(self):
self.current = None
def gather(self, kk):
if self.current == None or self.current.size() >= self.batch_size:
self.current = IndexSet(self.batch_size)
self.current.add(kk)
return self.current
#TODO: this should probably be java
class Future:
def __init__(self, func, index_set):
self.func = func
self.index_set = index_set
self.called = False
self.result = None
def clear(self):
self.func = None
self.index_set = None
self.result = None
def get(self):
if not self.called:
# data should be gathered here and then passed to model instead of doing it all in one go. That means were
# going to need to get the input objects here somehow, and I think that complicates things quite a bit.
# self.func gets passed an index set, but I think it should get passed the gathered data.
# otherwise, how does the interface not change?
self.result = self.func(self.index_set)
self.index_set.clear()
self.called = True
return self.result
#TODO: this should probably be java
class Computer:
def __init__(self, func):
self.func = func
self.futures = {}
def compute(self, index_set):
if index_set in self.futures:
return self.futures[index_set]
f = Future(self.func, index_set)
self.futures[gathered] = f
return f
#TODO: this should be java
class Scatterer:
def __init__(self, batch_size, scatter_func):
self.batch_size = batch_size
self.count = -1
self.scatter_func = scatter_func
def clear(self):
self.count = -1
def scatter(self, data):
self.count += 1
offset = self.count % self.batch_size
return self.scatter_func(data, offset)
def do_magic(table, model, scatter_func, batch_size):
#TODO: horrible hack
def gather_it(index_set):
print("Calling gather_it")
data = np.zeros([len(index_set), 3], dtype=np.float64)
for i in range(len(index_set)):
data[i,0] = table.getColumnSource("A", index_set[i])
data[i,1] = table.getColumnSource("B", index_set[i])
data[i,2] = table.getColumnSource("C", index_set[i])
return data
#TODO: horrible hack
def eval_func(index_set):
print("Calling eval_func")
data = gather_it(index_set)
return model(data)
gatherer = Gatherer(batch_size)
computer = Computer(eval_func)
scatterer_x = Scatterer(batch_size, scatter_func)
#TODO: python is having major problems. It doesn't resolve these variables inside of a function, and when you try to add them, it complains they aren't java
#TODO: may need to implement this function in Java as well to avoid some problems. Right now, it doesn't run.
QueryScope.addParam("gatherer", gatherer)
QueryScope.addParam("computer", computer)
QueryScope.addParam("scatterer_x", scatterer_x)
def cleanup(future):
gatherer.clear()
computer.clear()
future.clear()
scatterer_x.clear()
return table.update("IndexSet = gatherer.gather(kk)", "Future = computer.compute(IndexSet)", "X = (double) scatterer_x.scatter(Future.get())", "Clean = cleanup(Future)") \
.dropColumns("IndexSet", "Future", "Clean")
################################################################################################################################
# Everything here would be part of user code
################################################################################################################################
def model(data):
return np.sum(data, axis=1)
def scatter(data,i):
return data[i]
from deephaven.TableTools import timeTable
source = timeTable("00:00:01").update("A=i", "B=sqrt(i)", "C=i*i")
batch_size = 10
result = do_magic(source, model, scatter, batch_size)
|
[
"numpy.zeros",
"deephaven.TableTools.timeTable",
"numpy.sum",
"deephaven.QueryScope.addParam"
] |
[((4181, 4222), 'deephaven.QueryScope.addParam', 'QueryScope.addParam', (['"""gatherer"""', 'gatherer'], {}), "('gatherer', gatherer)\n", (4200, 4222), False, 'from deephaven import QueryScope\n'), ((4227, 4268), 'deephaven.QueryScope.addParam', 'QueryScope.addParam', (['"""computer"""', 'computer'], {}), "('computer', computer)\n", (4246, 4268), False, 'from deephaven import QueryScope\n'), ((4273, 4320), 'deephaven.QueryScope.addParam', 'QueryScope.addParam', (['"""scatterer_x"""', 'scatterer_x'], {}), "('scatterer_x', scatterer_x)\n", (4292, 4320), False, 'from deephaven import QueryScope\n'), ((5012, 5032), 'numpy.sum', 'np.sum', (['data'], {'axis': '(1)'}), '(data, axis=1)\n', (5018, 5032), True, 'import numpy as np\n'), ((579, 613), 'numpy.zeros', 'np.zeros', (['max_size'], {'dtype': 'np.int64'}), '(max_size, dtype=np.int64)\n', (587, 613), True, 'import numpy as np\n'), ((5128, 5149), 'deephaven.TableTools.timeTable', 'timeTable', (['"""00:00:01"""'], {}), "('00:00:01')\n", (5137, 5149), False, 'from deephaven.TableTools import timeTable\n')]
|
'''Prediction and plotting routine
In preparation for prediction and plotting, this script will:
1) Load the obs_dimensions
2) Specify the input_dimensions and latent_dimensions
3) Instantiate the DataHandler class
4) Instantiate the neural network
5) Load the trained neural network weights
6) Select and prepare an illustrative test example
7) Draw from the predicted posterior by utilizing nn.iaf_chain_posterior as
well as the encoder
8) Predict the state using the draw from the posterior either using the
modelled or learned (decoder) parameter-to-observable map
9) Plot the prediction
Inputs:
- hyperp: dictionary storing set hyperparameter values
- options: dictionary storing the set options
- filepaths: instance of the FilePaths class storing the default strings for
importing and exporting required objects.
Author: <NAME>, Oden Institute, Austin, Texas 2020
'''
import sys
sys.path.append('../../../../..')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.ioff() # Turn interactive plotting off
# Import src code
from utils_data.data_handler import DataHandler
from neural_networks.nn_vaeiaf import VAEIAF
from utils_misc.positivity_constraints import positivity_constraint_log_exp
# Import FEM Code
from Finite_Element_Method.src.load_mesh import load_mesh
from utils_project.plot_fem_function import plot_fem_function
import pdb #Equivalent of keyboard in MATLAB, just add "pdb.set_trace()"
###############################################################################
# Plot Predictions #
###############################################################################
def predict_and_plot(hyperp, options, filepaths):
#=== Load Observation Indices ===#
if options.obs_type == 'full':
obs_dimensions = options.parameter_dimensions
if options.obs_type == 'obs':
obs_dimensions = options.num_obs_points
print('Loading Boundary Indices')
df_obs_indices = pd.read_csv(filepaths.project.obs_indices + '.csv')
obs_indices = df_obs_indices.to_numpy()
#=== Data and Latent Dimensions of Autoencoder ===#
input_dimensions = obs_dimensions
latent_dimensions = options.parameter_dimensions
#=== Prepare Data ===#
data = DataHandler(hyperp, options, filepaths,
options.parameter_dimensions, obs_dimensions)
data.load_data_test()
if options.add_noise == 1:
data.add_noise_qoi_test()
parameter_test = data.poi_test
state_obs_test = data.qoi_test
#=== Load Trained Neural Network ===#
nn = VAEIAF(hyperp, options,
input_dimensions, latent_dimensions,
None, None,
None, None,
positivity_constraint_log_exp)
nn.load_weights(filepaths.trained_nn)
#=== Selecting Samples ===#
sample_number = 105
parameter_test_sample = np.expand_dims(parameter_test[sample_number,:], 0)
state_obs_test_sample = np.expand_dims(state_obs_test[sample_number,:], 0)
#=== Predictions ===#
parameter_pred_sample, _ = nn.iaf_chain_posterior(
nn.encoder(state_obs_test_sample))
state_obs_pred_sample = nn.decoder(parameter_test_sample)
parameter_pred_sample = parameter_pred_sample.numpy().flatten()
state_obs_pred_sample = state_obs_pred_sample.numpy().flatten()
#=== Plotting Prediction ===#
print('================================')
print(' Plotting Predictions ')
print('================================')
#=== Load Mesh ===#
nodes, elements, _, _, _, _, _, _ = load_mesh(filepaths.project)
#=== Plot FEM Functions ===#
plot_fem_function(filepaths.figures_savefile_name_parameter_test,
'True Parameter', 7.0,
nodes, elements,
parameter_test_sample)
plot_fem_function(filepaths.figures_savefile_name_parameter_pred,
'Parameter Prediction', 7.0,
nodes, elements,
parameter_pred_sample)
if options.obs_type == 'full':
plot_fem_function(filepaths.figures_savefile_name_state_test,
'True State', 2.6,
nodes, elements,
state_obs_test_sample)
plot_fem_function(filepaths.figures_savefile_name_state_pred,
'State Prediction', 2.6,
nodes, elements,
state_obs_pred_sample)
print('Predictions plotted')
###############################################################################
# Plot Metrics #
###############################################################################
def plot_and_save_metrics(hyperp, options, filepaths):
print('================================')
print(' Plotting Metrics ')
print('================================')
#=== Load Metrics ===#
print('Loading Metrics')
df_metrics = pd.read_csv(filepaths.trained_nn + "_metrics" + '.csv')
array_metrics = df_metrics.to_numpy()
####################
# Load Metrics #
####################
storage_array_loss_train = array_metrics[:,0]
storage_array_loss_train_VAE = array_metrics[:,1]
storage_array_loss_train_encoder = array_metrics[:,2]
storage_array_relative_error_input_VAE = array_metrics[:,10]
storage_array_relative_error_latent_encoder = array_metrics[:,11]
storage_array_relative_error_input_decoder = array_metrics[:,12]
storage_array_relative_gradient_norm = array_metrics[:,13]
################
# Plotting #
################
#=== Loss Train ===#
fig_loss = plt.figure()
x_axis = np.linspace(1, hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, np.log(storage_array_loss_train))
plt.title('Log-Loss for Training Neural Network')
plt.xlabel('Epochs')
plt.ylabel('Log-Loss')
figures_savefile_name = filepaths.directory_figures + '/' +\
'loss.png'
plt.savefig(figures_savefile_name)
plt.close(fig_loss)
#=== Loss Autoencoder ===#
fig_loss = plt.figure()
x_axis = np.linspace(1, hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, np.log(storage_array_loss_train_VAE))
plt.title('Log-Loss for VAE')
plt.xlabel('Epochs')
plt.ylabel('Log-Loss')
figures_savefile_name = filepaths.directory_figures + '/' +\
'loss_autoencoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_loss)
#=== Loss Encoder ===#
fig_loss = plt.figure()
x_axis = np.linspace(1, hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, np.log(storage_array_loss_train_encoder))
plt.title('Log-Loss for Encoder')
plt.xlabel('Epochs')
plt.ylabel('Log-Loss')
figures_savefile_name = filepaths.directory_figures + '/' +\
'loss_encoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_loss)
#=== Relative Error Autoencoder ===#
fig_accuracy = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_relative_error_input_VAE)
plt.title('Relative Error for Autoencoder')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'relative_error_autoencoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_accuracy)
#=== Relative Error Encoder ===#
fig_accuracy = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_relative_error_latent_encoder)
plt.title('Relative Error for Encoder')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'relative_error_encoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_accuracy)
#=== Relative Error Decoder ===#
fig_accuracy = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_relative_error_input_decoder)
plt.title('Relative Error for Decoder')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'relative_error_decoder.png'
plt.savefig(figures_savefile_name)
plt.close(fig_accuracy)
#=== Relative Gradient Norm ===#
fig_gradient_norm = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_relative_gradient_norm)
plt.title('Relative Gradient Norm')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'relative_error_gradient_norm.png'
plt.savefig(figures_savefile_name)
plt.close(fig_gradient_norm)
if options.model_augmented == 1:
#=== Relative Error Decoder ===#
fig_loss = plt.figure()
x_axis = np.linspace(1,hyperp.num_epochs, hyperp.num_epochs, endpoint = True)
plt.plot(x_axis, storage_array_loss_train_forward_model)
plt.title('Log-loss Forward Model')
plt.xlabel('Epochs')
plt.ylabel('Relative Error')
figures_savefile_name = filepaths.directory_figures + '/' +\
'loss_forward_model.png'
plt.savefig(figures_savefile_name)
plt.close(fig_loss)
print('Plotting complete')
|
[
"sys.path.append",
"matplotlib.pyplot.title",
"numpy.log",
"matplotlib.pyplot.ioff",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"matplotlib.pyplot.close",
"neural_networks.nn_vaeiaf.VAEIAF",
"numpy.expand_dims",
"matplotlib.pyplot.figure",
"utils_data.data_handler.DataHandler",
"numpy.linspace",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"utils_project.plot_fem_function.plot_fem_function",
"matplotlib.pyplot.savefig",
"Finite_Element_Method.src.load_mesh.load_mesh"
] |
[((968, 1001), 'sys.path.append', 'sys.path.append', (['"""../../../../.."""'], {}), "('../../../../..')\n", (983, 1001), False, 'import sys\n'), ((1074, 1084), 'matplotlib.pyplot.ioff', 'plt.ioff', ([], {}), '()\n', (1082, 1084), True, 'import matplotlib.pyplot as plt\n'), ((2374, 2463), 'utils_data.data_handler.DataHandler', 'DataHandler', (['hyperp', 'options', 'filepaths', 'options.parameter_dimensions', 'obs_dimensions'], {}), '(hyperp, options, filepaths, options.parameter_dimensions,\n obs_dimensions)\n', (2385, 2463), False, 'from utils_data.data_handler import DataHandler\n'), ((2696, 2815), 'neural_networks.nn_vaeiaf.VAEIAF', 'VAEIAF', (['hyperp', 'options', 'input_dimensions', 'latent_dimensions', 'None', 'None', 'None', 'None', 'positivity_constraint_log_exp'], {}), '(hyperp, options, input_dimensions, latent_dimensions, None, None,\n None, None, positivity_constraint_log_exp)\n', (2702, 2815), False, 'from neural_networks.nn_vaeiaf import VAEIAF\n'), ((3003, 3054), 'numpy.expand_dims', 'np.expand_dims', (['parameter_test[sample_number, :]', '(0)'], {}), '(parameter_test[sample_number, :], 0)\n', (3017, 3054), True, 'import numpy as np\n'), ((3082, 3133), 'numpy.expand_dims', 'np.expand_dims', (['state_obs_test[sample_number, :]', '(0)'], {}), '(state_obs_test[sample_number, :], 0)\n', (3096, 3133), True, 'import numpy as np\n'), ((3697, 3725), 'Finite_Element_Method.src.load_mesh.load_mesh', 'load_mesh', (['filepaths.project'], {}), '(filepaths.project)\n', (3706, 3725), False, 'from Finite_Element_Method.src.load_mesh import load_mesh\n'), ((3764, 3896), 'utils_project.plot_fem_function.plot_fem_function', 'plot_fem_function', (['filepaths.figures_savefile_name_parameter_test', '"""True Parameter"""', '(7.0)', 'nodes', 'elements', 'parameter_test_sample'], {}), "(filepaths.figures_savefile_name_parameter_test,\n 'True Parameter', 7.0, nodes, elements, parameter_test_sample)\n", (3781, 3896), False, 'from utils_project.plot_fem_function import plot_fem_function\n'), ((3962, 4100), 'utils_project.plot_fem_function.plot_fem_function', 'plot_fem_function', (['filepaths.figures_savefile_name_parameter_pred', '"""Parameter Prediction"""', '(7.0)', 'nodes', 'elements', 'parameter_pred_sample'], {}), "(filepaths.figures_savefile_name_parameter_pred,\n 'Parameter Prediction', 7.0, nodes, elements, parameter_pred_sample)\n", (3979, 4100), False, 'from utils_project.plot_fem_function import plot_fem_function\n'), ((5159, 5214), 'pandas.read_csv', 'pd.read_csv', (["(filepaths.trained_nn + '_metrics' + '.csv')"], {}), "(filepaths.trained_nn + '_metrics' + '.csv')\n", (5170, 5214), True, 'import pandas as pd\n'), ((5866, 5878), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (5876, 5878), True, 'import matplotlib.pyplot as plt\n'), ((5892, 5959), 'numpy.linspace', 'np.linspace', (['(1)', 'hyperp.num_epochs', 'hyperp.num_epochs'], {'endpoint': '(True)'}), '(1, hyperp.num_epochs, hyperp.num_epochs, endpoint=True)\n', (5903, 5959), True, 'import numpy as np\n'), ((6021, 6070), 'matplotlib.pyplot.title', 'plt.title', (['"""Log-Loss for Training Neural Network"""'], {}), "('Log-Loss for Training Neural Network')\n", (6030, 6070), True, 'import matplotlib.pyplot as plt\n'), ((6075, 6095), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (6085, 6095), True, 'import matplotlib.pyplot as plt\n'), ((6100, 6122), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Log-Loss"""'], {}), "('Log-Loss')\n", (6110, 6122), True, 'import matplotlib.pyplot as plt\n'), ((6215, 6249), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figures_savefile_name'], {}), '(figures_savefile_name)\n', (6226, 6249), True, 'import matplotlib.pyplot as plt\n'), ((6254, 6273), 'matplotlib.pyplot.close', 'plt.close', (['fig_loss'], {}), '(fig_loss)\n', (6263, 6273), True, 'import matplotlib.pyplot as plt\n'), ((6321, 6333), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6331, 6333), True, 'import matplotlib.pyplot as plt\n'), ((6347, 6414), 'numpy.linspace', 'np.linspace', (['(1)', 'hyperp.num_epochs', 'hyperp.num_epochs'], {'endpoint': '(True)'}), '(1, hyperp.num_epochs, hyperp.num_epochs, endpoint=True)\n', (6358, 6414), True, 'import numpy as np\n'), ((6480, 6509), 'matplotlib.pyplot.title', 'plt.title', (['"""Log-Loss for VAE"""'], {}), "('Log-Loss for VAE')\n", (6489, 6509), True, 'import matplotlib.pyplot as plt\n'), ((6514, 6534), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (6524, 6534), True, 'import matplotlib.pyplot as plt\n'), ((6539, 6561), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Log-Loss"""'], {}), "('Log-Loss')\n", (6549, 6561), True, 'import matplotlib.pyplot as plt\n'), ((6666, 6700), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figures_savefile_name'], {}), '(figures_savefile_name)\n', (6677, 6700), True, 'import matplotlib.pyplot as plt\n'), ((6705, 6724), 'matplotlib.pyplot.close', 'plt.close', (['fig_loss'], {}), '(fig_loss)\n', (6714, 6724), True, 'import matplotlib.pyplot as plt\n'), ((6768, 6780), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6778, 6780), True, 'import matplotlib.pyplot as plt\n'), ((6794, 6861), 'numpy.linspace', 'np.linspace', (['(1)', 'hyperp.num_epochs', 'hyperp.num_epochs'], {'endpoint': '(True)'}), '(1, hyperp.num_epochs, hyperp.num_epochs, endpoint=True)\n', (6805, 6861), True, 'import numpy as np\n'), ((6931, 6964), 'matplotlib.pyplot.title', 'plt.title', (['"""Log-Loss for Encoder"""'], {}), "('Log-Loss for Encoder')\n", (6940, 6964), True, 'import matplotlib.pyplot as plt\n'), ((6969, 6989), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (6979, 6989), True, 'import matplotlib.pyplot as plt\n'), ((6994, 7016), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Log-Loss"""'], {}), "('Log-Loss')\n", (7004, 7016), True, 'import matplotlib.pyplot as plt\n'), ((7117, 7151), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figures_savefile_name'], {}), '(figures_savefile_name)\n', (7128, 7151), True, 'import matplotlib.pyplot as plt\n'), ((7156, 7175), 'matplotlib.pyplot.close', 'plt.close', (['fig_loss'], {}), '(fig_loss)\n', (7165, 7175), True, 'import matplotlib.pyplot as plt\n'), ((7237, 7249), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7247, 7249), True, 'import matplotlib.pyplot as plt\n'), ((7263, 7330), 'numpy.linspace', 'np.linspace', (['(1)', 'hyperp.num_epochs', 'hyperp.num_epochs'], {'endpoint': '(True)'}), '(1, hyperp.num_epochs, hyperp.num_epochs, endpoint=True)\n', (7274, 7330), True, 'import numpy as np\n'), ((7336, 7392), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'storage_array_relative_error_input_VAE'], {}), '(x_axis, storage_array_relative_error_input_VAE)\n', (7344, 7392), True, 'import matplotlib.pyplot as plt\n'), ((7397, 7440), 'matplotlib.pyplot.title', 'plt.title', (['"""Relative Error for Autoencoder"""'], {}), "('Relative Error for Autoencoder')\n", (7406, 7440), True, 'import matplotlib.pyplot as plt\n'), ((7445, 7465), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (7455, 7465), True, 'import matplotlib.pyplot as plt\n'), ((7470, 7498), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Error"""'], {}), "('Relative Error')\n", (7480, 7498), True, 'import matplotlib.pyplot as plt\n'), ((7613, 7647), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figures_savefile_name'], {}), '(figures_savefile_name)\n', (7624, 7647), True, 'import matplotlib.pyplot as plt\n'), ((7652, 7675), 'matplotlib.pyplot.close', 'plt.close', (['fig_accuracy'], {}), '(fig_accuracy)\n', (7661, 7675), True, 'import matplotlib.pyplot as plt\n'), ((7733, 7745), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (7743, 7745), True, 'import matplotlib.pyplot as plt\n'), ((7759, 7826), 'numpy.linspace', 'np.linspace', (['(1)', 'hyperp.num_epochs', 'hyperp.num_epochs'], {'endpoint': '(True)'}), '(1, hyperp.num_epochs, hyperp.num_epochs, endpoint=True)\n', (7770, 7826), True, 'import numpy as np\n'), ((7832, 7893), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'storage_array_relative_error_latent_encoder'], {}), '(x_axis, storage_array_relative_error_latent_encoder)\n', (7840, 7893), True, 'import matplotlib.pyplot as plt\n'), ((7898, 7937), 'matplotlib.pyplot.title', 'plt.title', (['"""Relative Error for Encoder"""'], {}), "('Relative Error for Encoder')\n", (7907, 7937), True, 'import matplotlib.pyplot as plt\n'), ((7942, 7962), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (7952, 7962), True, 'import matplotlib.pyplot as plt\n'), ((7967, 7995), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Error"""'], {}), "('Relative Error')\n", (7977, 7995), True, 'import matplotlib.pyplot as plt\n'), ((8106, 8140), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figures_savefile_name'], {}), '(figures_savefile_name)\n', (8117, 8140), True, 'import matplotlib.pyplot as plt\n'), ((8145, 8168), 'matplotlib.pyplot.close', 'plt.close', (['fig_accuracy'], {}), '(fig_accuracy)\n', (8154, 8168), True, 'import matplotlib.pyplot as plt\n'), ((8226, 8238), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8236, 8238), True, 'import matplotlib.pyplot as plt\n'), ((8252, 8319), 'numpy.linspace', 'np.linspace', (['(1)', 'hyperp.num_epochs', 'hyperp.num_epochs'], {'endpoint': '(True)'}), '(1, hyperp.num_epochs, hyperp.num_epochs, endpoint=True)\n', (8263, 8319), True, 'import numpy as np\n'), ((8325, 8385), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'storage_array_relative_error_input_decoder'], {}), '(x_axis, storage_array_relative_error_input_decoder)\n', (8333, 8385), True, 'import matplotlib.pyplot as plt\n'), ((8390, 8429), 'matplotlib.pyplot.title', 'plt.title', (['"""Relative Error for Decoder"""'], {}), "('Relative Error for Decoder')\n", (8399, 8429), True, 'import matplotlib.pyplot as plt\n'), ((8434, 8454), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (8444, 8454), True, 'import matplotlib.pyplot as plt\n'), ((8459, 8487), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Error"""'], {}), "('Relative Error')\n", (8469, 8487), True, 'import matplotlib.pyplot as plt\n'), ((8598, 8632), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figures_savefile_name'], {}), '(figures_savefile_name)\n', (8609, 8632), True, 'import matplotlib.pyplot as plt\n'), ((8637, 8660), 'matplotlib.pyplot.close', 'plt.close', (['fig_accuracy'], {}), '(fig_accuracy)\n', (8646, 8660), True, 'import matplotlib.pyplot as plt\n'), ((8723, 8735), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (8733, 8735), True, 'import matplotlib.pyplot as plt\n'), ((8749, 8816), 'numpy.linspace', 'np.linspace', (['(1)', 'hyperp.num_epochs', 'hyperp.num_epochs'], {'endpoint': '(True)'}), '(1, hyperp.num_epochs, hyperp.num_epochs, endpoint=True)\n', (8760, 8816), True, 'import numpy as np\n'), ((8822, 8876), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'storage_array_relative_gradient_norm'], {}), '(x_axis, storage_array_relative_gradient_norm)\n', (8830, 8876), True, 'import matplotlib.pyplot as plt\n'), ((8881, 8916), 'matplotlib.pyplot.title', 'plt.title', (['"""Relative Gradient Norm"""'], {}), "('Relative Gradient Norm')\n", (8890, 8916), True, 'import matplotlib.pyplot as plt\n'), ((8921, 8941), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (8931, 8941), True, 'import matplotlib.pyplot as plt\n'), ((8946, 8974), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Error"""'], {}), "('Relative Error')\n", (8956, 8974), True, 'import matplotlib.pyplot as plt\n'), ((9091, 9125), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figures_savefile_name'], {}), '(figures_savefile_name)\n', (9102, 9125), True, 'import matplotlib.pyplot as plt\n'), ((9130, 9158), 'matplotlib.pyplot.close', 'plt.close', (['fig_gradient_norm'], {}), '(fig_gradient_norm)\n', (9139, 9158), True, 'import matplotlib.pyplot as plt\n'), ((2087, 2138), 'pandas.read_csv', 'pd.read_csv', (["(filepaths.project.obs_indices + '.csv')"], {}), "(filepaths.project.obs_indices + '.csv')\n", (2098, 2138), True, 'import pandas as pd\n'), ((4206, 4330), 'utils_project.plot_fem_function.plot_fem_function', 'plot_fem_function', (['filepaths.figures_savefile_name_state_test', '"""True State"""', '(2.6)', 'nodes', 'elements', 'state_obs_test_sample'], {}), "(filepaths.figures_savefile_name_state_test, 'True State',\n 2.6, nodes, elements, state_obs_test_sample)\n", (4223, 4330), False, 'from utils_project.plot_fem_function import plot_fem_function\n'), ((4413, 4543), 'utils_project.plot_fem_function.plot_fem_function', 'plot_fem_function', (['filepaths.figures_savefile_name_state_pred', '"""State Prediction"""', '(2.6)', 'nodes', 'elements', 'state_obs_pred_sample'], {}), "(filepaths.figures_savefile_name_state_pred,\n 'State Prediction', 2.6, nodes, elements, state_obs_pred_sample)\n", (4430, 4543), False, 'from utils_project.plot_fem_function import plot_fem_function\n'), ((5983, 6015), 'numpy.log', 'np.log', (['storage_array_loss_train'], {}), '(storage_array_loss_train)\n', (5989, 6015), True, 'import numpy as np\n'), ((6438, 6474), 'numpy.log', 'np.log', (['storage_array_loss_train_VAE'], {}), '(storage_array_loss_train_VAE)\n', (6444, 6474), True, 'import numpy as np\n'), ((6885, 6925), 'numpy.log', 'np.log', (['storage_array_loss_train_encoder'], {}), '(storage_array_loss_train_encoder)\n', (6891, 6925), True, 'import numpy as np\n'), ((9257, 9269), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (9267, 9269), True, 'import matplotlib.pyplot as plt\n'), ((9287, 9354), 'numpy.linspace', 'np.linspace', (['(1)', 'hyperp.num_epochs', 'hyperp.num_epochs'], {'endpoint': '(True)'}), '(1, hyperp.num_epochs, hyperp.num_epochs, endpoint=True)\n', (9298, 9354), True, 'import numpy as np\n'), ((9364, 9420), 'matplotlib.pyplot.plot', 'plt.plot', (['x_axis', 'storage_array_loss_train_forward_model'], {}), '(x_axis, storage_array_loss_train_forward_model)\n', (9372, 9420), True, 'import matplotlib.pyplot as plt\n'), ((9429, 9464), 'matplotlib.pyplot.title', 'plt.title', (['"""Log-loss Forward Model"""'], {}), "('Log-loss Forward Model')\n", (9438, 9464), True, 'import matplotlib.pyplot as plt\n'), ((9473, 9493), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Epochs"""'], {}), "('Epochs')\n", (9483, 9493), True, 'import matplotlib.pyplot as plt\n'), ((9502, 9530), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Relative Error"""'], {}), "('Relative Error')\n", (9512, 9530), True, 'import matplotlib.pyplot as plt\n'), ((9649, 9683), 'matplotlib.pyplot.savefig', 'plt.savefig', (['figures_savefile_name'], {}), '(figures_savefile_name)\n', (9660, 9683), True, 'import matplotlib.pyplot as plt\n'), ((9692, 9711), 'matplotlib.pyplot.close', 'plt.close', (['fig_loss'], {}), '(fig_loss)\n', (9701, 9711), True, 'import matplotlib.pyplot as plt\n')]
|
import logging
logging.basicConfig(format="[%(asctime)s] %(filename)s [line:%(lineno)d] %(message)s", datefmt="%m-%d %H:%M:%S")
import os
import sys
import urllib
import pprint
import tarfile
import tensorflow as tf
import json
import datetime
import dateutil.tz
import numpy as np
import scipy.misc
pp = pprint.PrettyPrinter().pprint
logger = logging.getLogger(__name__)
def setup_model_saving(model_name, data, hyperparams=None, root_dir='run/'):
# construct the model directory template name
name = os.path.join(root_dir, data, model_name + '%s')
# iterate until we find an index that hasn't been taken yet.
i = 0
while os.path.exists(name % i):
i += 1
name = name % i
# create the folder
os.makedirs(name)
return name
def mprint(matrix, pivot=0.5):
for array in matrix:
print("".join("#" if i > pivot else " " for i in array))
def show_all_variables():
total_count = 0
for idx, op in enumerate(tf.trainable_variables()):
shape = op.get_shape()
count = np.prod(shape)
print("[%2d] %s %s = %s" % (idx, op.name, shape, count))
total_count += int(count)
print("[Total] variable size: %s" % "{:,}".format(total_count))
def get_timestamp():
now = datetime.datetime.now(dateutil.tz.tzlocal())
return now.strftime('%Y_%m_%d_%H_%M_%S')
def binarize(images):
return (np.random.uniform(size=images.shape) < images).astype('float32')
def save_images_in(images,cmin=0.0, cmax=1.0,directory="./",prefix="sample"):
index = 1
for i in np.arange(images.shape[0]):
filename = '%s_%s_%s.jpg' % (i,prefix, get_timestamp())
scipy.misc.toimage(images[i].reshape(images[i].shape[0],images[i].shape[1]), cmin=0, cmax=255).save(filename)
def save_images(images, height, width,channel, n_row, n_col, cmin=0.0, cmax=1.0, directory="./", prefix="sample"):
if channel == 1:
images = images.reshape((n_row, n_col, height, width))
images = images.transpose(1, 2, 0, 3)
images = images.reshape((height * n_row, width * n_col))
filename = '%s_%s.jpg' % (prefix, get_timestamp())
scipy.misc.toimage(images, cmin=cmin, cmax=cmax).save(os.path.join(directory, filename))
elif channel == 3:
images = images.reshape((n_row, n_col, height, width,channel))
images = images.transpose(1, 2, 0, 3, 4)
images = images.reshape((height * n_row, width * n_col,channel))
filename = '%s_%s.jpg' % (prefix, get_timestamp())
scipy.misc.toimage(images).save(os.path.join(directory, filename))
def get_model_dir(conf, exceptions=None):
# attrs = conf.__dict__['__flags']
# pp(attrs)
keys = conf.flag_values_dict()
# keys.remove('data')
# keys = ['data'] + keys
names =[]
for key in keys:
# Only use useful flags
if key not in exceptions:
names.append("%s=%s" % (key, ",".join([str(i) for i in conf[key]])
if type(conf[key]) == list else conf[key]))
return os.path.join('checkpoints', *names) + '/'
def preprocess_conf(conf):
options = conf.__flags
for option, value in options.items():
option = option.lower()
def check_and_create_dir(directory):
if not os.path.exists(directory):
logger.info('Creating directory: %s' % directory)
os.makedirs(directory)
else:
logger.info('Skip creating directory: %s' % directory)
def maybe_download_and_extract(dest_directory):
"""
Download and extract the tarball from Alex's website.
From https://github.com/tensorflow/tensorflow/blob/r0.9/tensorflow/models/image/cifar10/cifar10.py
"""
DATA_URL = 'http://www.cs.toronto.edu/~kriz/cifar-10-binary.tar.gz'
if not os.path.exists(dest_directory):
os.makedirs(dest_directory)
filename = DATA_URL.split('/')[-1]
filepath = os.path.join(dest_directory, filename)
if not os.path.exists(filepath):
def _progress(count, block_size, total_size):
sys.stdout.write('\r>> Downloading %s %.1f%%' % (filename,
float(count * block_size) / float(total_size) * 100.0))
sys.stdout.flush()
filepath, _ = urllib.urlretrieve(DATA_URL, filepath, _progress)
print()
statinfo = os.stat(filepath)
print('Successfully downloaded', filename, statinfo.st_size, 'bytes.')
tarfile.open(filepath, 'r:gz').extractall(dest_directory)
|
[
"numpy.random.uniform",
"os.makedirs",
"logging.basicConfig",
"tensorflow.trainable_variables",
"os.stat",
"os.path.exists",
"numpy.prod",
"pprint.PrettyPrinter",
"numpy.arange",
"sys.stdout.flush",
"urllib.urlretrieve",
"tarfile.open",
"os.path.join",
"logging.getLogger"
] |
[((15, 137), 'logging.basicConfig', 'logging.basicConfig', ([], {'format': '"""[%(asctime)s] %(filename)s [line:%(lineno)d] %(message)s"""', 'datefmt': '"""%m-%d %H:%M:%S"""'}), "(format=\n '[%(asctime)s] %(filename)s [line:%(lineno)d] %(message)s', datefmt=\n '%m-%d %H:%M:%S')\n", (34, 137), False, 'import logging\n'), ((347, 374), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (364, 374), False, 'import logging\n'), ((308, 330), 'pprint.PrettyPrinter', 'pprint.PrettyPrinter', ([], {}), '()\n', (328, 330), False, 'import pprint\n'), ((510, 557), 'os.path.join', 'os.path.join', (['root_dir', 'data', "(model_name + '%s')"], {}), "(root_dir, data, model_name + '%s')\n", (522, 557), False, 'import os\n'), ((637, 661), 'os.path.exists', 'os.path.exists', (['(name % i)'], {}), '(name % i)\n', (651, 661), False, 'import os\n'), ((716, 733), 'os.makedirs', 'os.makedirs', (['name'], {}), '(name)\n', (727, 733), False, 'import os\n'), ((1492, 1518), 'numpy.arange', 'np.arange', (['images.shape[0]'], {}), '(images.shape[0])\n', (1501, 1518), True, 'import numpy as np\n'), ((3692, 3730), 'os.path.join', 'os.path.join', (['dest_directory', 'filename'], {}), '(dest_directory, filename)\n', (3704, 3730), False, 'import os\n'), ((936, 960), 'tensorflow.trainable_variables', 'tf.trainable_variables', ([], {}), '()\n', (958, 960), True, 'import tensorflow as tf\n'), ((1002, 1016), 'numpy.prod', 'np.prod', (['shape'], {}), '(shape)\n', (1009, 1016), True, 'import numpy as np\n'), ((2893, 2928), 'os.path.join', 'os.path.join', (['"""checkpoints"""', '*names'], {}), "('checkpoints', *names)\n", (2905, 2928), False, 'import os\n'), ((3104, 3129), 'os.path.exists', 'os.path.exists', (['directory'], {}), '(directory)\n', (3118, 3129), False, 'import os\n'), ((3189, 3211), 'os.makedirs', 'os.makedirs', (['directory'], {}), '(directory)\n', (3200, 3211), False, 'import os\n'), ((3577, 3607), 'os.path.exists', 'os.path.exists', (['dest_directory'], {}), '(dest_directory)\n', (3591, 3607), False, 'import os\n'), ((3613, 3640), 'os.makedirs', 'os.makedirs', (['dest_directory'], {}), '(dest_directory)\n', (3624, 3640), False, 'import os\n'), ((3741, 3765), 'os.path.exists', 'os.path.exists', (['filepath'], {}), '(filepath)\n', (3755, 3765), False, 'import os\n'), ((3991, 4040), 'urllib.urlretrieve', 'urllib.urlretrieve', (['DATA_URL', 'filepath', '_progress'], {}), '(DATA_URL, filepath, _progress)\n', (4009, 4040), False, 'import urllib\n'), ((4068, 4085), 'os.stat', 'os.stat', (['filepath'], {}), '(filepath)\n', (4075, 4085), False, 'import os\n'), ((2114, 2147), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (2126, 2147), False, 'import os\n'), ((3954, 3972), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3970, 3972), False, 'import sys\n'), ((1325, 1361), 'numpy.random.uniform', 'np.random.uniform', ([], {'size': 'images.shape'}), '(size=images.shape)\n', (1342, 1361), True, 'import numpy as np\n'), ((2453, 2486), 'os.path.join', 'os.path.join', (['directory', 'filename'], {}), '(directory, filename)\n', (2465, 2486), False, 'import os\n'), ((4165, 4195), 'tarfile.open', 'tarfile.open', (['filepath', '"""r:gz"""'], {}), "(filepath, 'r:gz')\n", (4177, 4195), False, 'import tarfile\n')]
|
#!/usr/bin/env python3
import os
import sys
import re
import argparse
from pathlib import Path
from collections import Counter
from enum import Enum
import itertools
import json
from operator import itemgetter
import math
import datetime
import logging
import multiprocessing
import time
import signal
from typing import Tuple, Union
import io
import cv2
from numpy import ndarray
import numpy as np
import pytesseract
from PIL import Image
from PIL.ExifTags import TAGS
import pageinfo
PROGNAME = "FGOスクショカウント"
VERSION = "0.4.0"
DEFAULT_ITEM_LANG = "jpn" # "jpn": japanese, "eng": English
logger = logging.getLogger(__name__)
watcher_running = True
class CustomAdapter(logging.LoggerAdapter):
"""
この adapter を通した場合、自動的にログ出力文字列の先頭に [target] が挿入される。
target は adapter インスタンス生成時に確定させること。
"""
def process(self, msg, kwargs):
return f"[{self.extra['target']}] {msg}", kwargs
class Ordering(Enum):
"""
ファイルの処理順序を示す定数
"""
NOTSPECIFIED = 'notspecified' # 指定なし
FILENAME = 'filename' # ファイル名
TIMESTAMP = 'timestamp' # 作成日時
def __str__(self):
return str(self.value)
basedir = Path(__file__).resolve().parent
Item_dir = basedir / Path("item/equip/")
CE_dir = basedir / Path("item/ce/")
Point_dir = basedir / Path("item/point/")
train_item = basedir / Path("item.xml") # item stack & bonus
train_chest = basedir / Path("chest.xml") # drop_coount (Old UI)
train_dcnt = basedir / Path("dcnt.xml") # drop_coount (New UI)
train_card = basedir / Path("card.xml") # card name
drop_file = basedir / Path("fgoscdata/hash_drop.json")
eventquest_dir = basedir / Path("fgoscdata/data/json/")
items_img = basedir / Path("data/misc/items_img.png")
hasher = cv2.img_hash.PHash_create()
FONTSIZE_UNDEFINED = -1
FONTSIZE_NORMAL = 0
FONTSIZE_SMALL = 1
FONTSIZE_TINY = 2
FONTSIZE_NEWSTYLE = 99
PRIORITY_CE = 9000
PRIORITY_POINT = 3000
PRIORITY_ITEM = 700
PRIORITY_GEM_MIN = 6094
PRIORITY_MAGIC_GEM_MIN = 6194
PRIORITY_SECRET_GEM_MIN = 6294
PRIORITY_PIECE_MIN = 5194
PRIORITY_REWARD_QP = 9012
ID_START = 9500000
ID_QP = 1
ID_REWARD_QP = 5
ID_GEM_MIN = 6001
ID_GEM_MAX = 6007
ID_MAGIC_GEM_MIN = 6101
ID_MAGIC_GEM_MAX = 6107
ID_SECRET_GEM_MIN = 6201
ID_SECRET_GEM_MAX = 6207
ID_PIECE_MIN = 7001
ID_MONUMENT_MAX = 7107
ID_EXP_MIN = 9700100
ID_EXP_MAX = 9707500
ID_2ZORO_DICE = 94047708
ID_3ZORO_DICE = 94047709
ID_NORTH_AMERICA = 93000500
ID_SYURENJYO = 94006800
ID_EVNET = 94000000
TIMEOUT = 15
QP_UNKNOWN = -1
DEFAULT_POLL_FREQ = 60
DEFAULT_AMT_PROCESSES = 1
class FgosccntError(Exception):
pass
class GainedQPandDropMissMatchError(FgosccntError):
pass
with open(drop_file, encoding='UTF-8') as f:
drop_item = json.load(f)
# JSONファイルから各辞書を作成
item_name = {item["id"]: item["name"] for item in drop_item}
item_name_eng = {item["id"]: item["name_eng"] for item in drop_item
if "name_eng" in item.keys()}
item_shortname = {item["id"]: item["shortname"] for item in drop_item
if "shortname" in item.keys()}
item_dropPriority = {item["id"]: item["dropPriority"] for item in drop_item}
item_background = {item["id"]: item["background"] for item in drop_item
if "background" in item.keys()}
item_type = {item["id"]: item["type"] for item in drop_item}
dist_item = {item["phash_battle"]: item["id"] for item in drop_item
if item["type"] == "Item" and "phash_battle" in item.keys()}
dist_ce = {item["phash"]: item["id"] for item in drop_item
if item["type"] == "Craft Essence"}
dist_ce_narrow = {item["phash_narrow"]: item["id"] for item in drop_item
if item["type"] == "Craft Essence"}
dist_secret_gem = {item["id"]: item["phash_class"] for item in drop_item
if 6200 < item["id"] < 6208
and "phash_class" in item.keys()}
dist_magic_gem = {item["id"]: item["phash_class"] for item in drop_item
if 6100 < item["id"] < 6108 and "phash_class" in item.keys()}
dist_gem = {item["id"]: item["phash_class"] for item in drop_item
if 6000 < item["id"] < 6008 and "phash_class" in item.keys()}
dist_exp_rarity = {item["phash_rarity"]: item["id"] for item in drop_item
if item["type"] == "Exp. UP"
and "phash_rarity" in item.keys()}
dist_exp_rarity_sold = {item["phash_rarity_sold"]: item["id"] for item
in drop_item if item["type"] == "Exp. UP"
and "phash_rarity_sold" in item.keys()}
dist_exp_rarity.update(dist_exp_rarity_sold)
dist_exp_class = {item["phash_class"]: item["id"] for item in drop_item
if item["type"] == "Exp. UP"
and "phash_class" in item.keys()}
dist_exp_class_sold = {item["phash_class_sold"]: item["id"]
for item in drop_item
if item["type"] == "Exp. UP" and "phash_class_sold"
in item.keys()}
dist_exp_class.update(dist_exp_class_sold)
dist_point = {item["phash_battle"]: item["id"]
for item in drop_item
if item["type"] == "Point" and "phash_battle" in item.keys()}
with open(drop_file, encoding='UTF-8') as f:
drop_item = json.load(f)
freequest = []
evnetfiles = eventquest_dir.glob('**/*.json')
for evnetfile in evnetfiles:
try:
with open(evnetfile, encoding='UTF-8') as f:
event = json.load(f)
freequest = freequest + event
except (OSError, UnicodeEncodeError) as e:
logger.exception(e)
npz = np.load(basedir / Path('background.npz'))
hist_zero = npz["hist_zero"]
hist_gold = npz["hist_gold"]
hist_silver = npz["hist_silver"]
hist_bronze = npz["hist_bronze"]
def has_intersect(a, b):
"""
二つの矩形の当たり判定
隣接するのはOKとする
"""
return max(a[0], b[0]) < min(a[2], b[2]) \
and max(a[1], b[1]) < min(a[3], b[3])
class State():
def set_screen(self):
self.screen_type = "normal"
def set_char_position(self):
logger.debug("JP Standard Position")
def set_font_size(self):
logger.debug("JP Standard Font Size")
def set_max_qp(self):
self.max_qp = 999999999
logger.debug("999,999,999")
class JpNov2020(State):
def set_screen(self):
self.screen_type = "wide"
class JpAug2021(JpNov2020):
def set_font_size(self):
logger.debug("JP New Font Size")
def set_max_qp(self):
self.max_qp = 2000000000
logger.debug("2,000,000,000")
class NaState(State):
def set_char_position(self):
logger.debug("NA Standard Position")
class Context:
def __init__(self):
self.jp_aug_2021 = JpAug2021()
self.jp_nov_2020 = JpNov2020()
self.jp = State()
self.na = NaState()
self.state = self.jp_aug_2021
self.set_screen()
self.set_font_size()
self.set_char_position()
self.set_max_qp()
def change_state(self, mode):
if mode == "jp":
self.state = self.jp_aug_2021
elif mode == "na":
self.state = self.na
else:
raise ValueError("change_state method must be in {}".format(["jp", "na"]))
self.set_screen()
self.set_font_size()
self.set_char_position()
self.set_max_qp()
def set_screen(self):
self.state.set_screen()
def set_char_position(self):
self.state.set_char_position()
def set_font_size(self):
self.state.set_font_size()
def set_max_qp(self):
self.state.set_max_qp()
def get_coodinates(img: ndarray,
display: bool = False) -> Tuple[Tuple[int, int],
Tuple[int, int]]:
threshold: int = 30
height, width = img.shape[:2]
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if display:
cv2.imshow('image', img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
_, inv = cv2.threshold(img_gray, threshold, 255, cv2.THRESH_BINARY_INV)
if display:
cv2.imshow('image', inv)
cv2.waitKey(0)
cv2.destroyAllWindows()
contours, _ = cv2.findContours(inv, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
contours2 = []
for cnt in contours:
_, _, w, h = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
if 1.81 < w/h < 1.83 and area > height / 2 * width / 2 and height/h > 1080/910:
contours2.append(cnt)
if len(contours2) == 0:
raise ValueError("Game screen not found.")
max_contour = max(contours2, key=lambda x: cv2.contourArea(x))
x, y, width, height = cv2.boundingRect(max_contour)
return ((x, y), (x + width, y + height))
def standardize_size(frame_img: ndarray,
display: bool = False) -> Tuple[ndarray, float]:
TRAINING_WIDTH: int = 1754
height, width = frame_img.shape[:2]
if display:
pass
logger.debug("height: %d", height)
logger.debug("width: %d", width)
_, width, _ = frame_img.shape
resize_scale: float = TRAINING_WIDTH / width
logger.debug("resize_scale: %f", resize_scale)
if resize_scale > 1:
frame_img = cv2.resize(frame_img, (0, 0),
fx=resize_scale, fy=resize_scale,
interpolation=cv2.INTER_CUBIC)
elif resize_scale < 1:
frame_img = cv2.resize(frame_img, (0, 0),
fx=resize_scale, fy=resize_scale,
interpolation=cv2.INTER_AREA)
if display:
cv2.imshow('image', frame_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return frame_img, resize_scale
def area_decision(frame_img: ndarray,
display: bool = False) -> str:
"""
FGOアプリの地域を選択
'na', 'jp'に対応
'items_img.png' とのオブジェクトマッチングで判定
"""
img = frame_img[0:100, 0:500]
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
if display:
cv2.imshow('image', img_gray)
cv2.waitKey(0)
cv2.destroyAllWindows()
template = imread(items_img, 0)
res = cv2.matchTemplate(
img_gray,
template,
cv2.TM_CCOEFF_NORMED
)
threshold = 0.9
loc = np.where(res >= threshold)
for pt in zip(*loc[::-1]):
return 'na'
return 'jp'
def check_page_mismatch(page_items: int, chestnum: int, pagenum: int, pages: int, lines: int) -> bool:
if pages == 1:
if chestnum + 1 != page_items:
return False
return True
if not (pages - 1) * 21 <= chestnum <= pages * 21 - 1:
return False
if pagenum == pages:
item_count = chestnum - ((pages - 1) * 21 - 1) + (pages * 3 - lines) * 7
if item_count != page_items:
return False
return True
class ScreenShot:
"""
戦利品スクリーンショットを表すクラス
"""
def __init__(self, args, img_rgb, svm, svm_chest, svm_dcnt, svm_card,
fileextention, exLogger, reward_only=False):
self.exLogger = exLogger
threshold = 80
try:
self.pagenum, self.pages, self.lines = pageinfo.guess_pageinfo(img_rgb)
except pageinfo.TooManyAreasDetectedError:
self.pagenum, self.pages, self.lines = (-1, -1, -1)
self.img_rgb_orig = img_rgb
img_blue, img_green, img_red = cv2.split(img_rgb)
if (img_blue==img_green).all() & (img_green==img_red ).all():
raise ValueError("Input image is grayscale")
self.img_gray_orig = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
self.img_hsv_orig = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2HSV)
_, self.img_th_orig = cv2.threshold(self.img_gray_orig,
threshold, 255, cv2.THRESH_BINARY)
((self.x1, self.y1), (self.x2, self.y2)) = get_coodinates(self.img_rgb_orig)
frame_img: ndarray = self.img_rgb_orig[self.y1: self.y2, self.x1: self.x2]
img_resize, resize_scale = standardize_size(frame_img)
self.img_rgb = img_resize
mode = area_decision(img_resize)
logger.debug("lang: %s", mode)
# UI modeを決める
sc = Context()
sc.change_state(mode)
self.max_qp = sc.state.max_qp
self.screen_type = sc.state.screen_type
dcnt_old, dcnt_new = self.drop_count_area(self.img_rgb_orig, resize_scale, sc)
if logger.isEnabledFor(logging.DEBUG):
cv2.imwrite('frame_img.png', img_resize)
if logger.isEnabledFor(logging.DEBUG):
if self.screen_type == "normal":
cv2.imwrite('dcnt_old.png', dcnt_old)
cv2.imwrite('dcnt_new.png', dcnt_new)
self.img_gray = cv2.cvtColor(self.img_rgb, cv2.COLOR_BGR2GRAY)
_, self.img_th = cv2.threshold(self.img_gray,
threshold, 255, cv2.THRESH_BINARY)
self.svm = svm
self.svm_chest = svm_chest
self.svm_dcnt = svm_dcnt
self.height, self.width = self.img_rgb.shape[:2]
if self.screen_type == "normal":
self.chestnum = self.ocr_tresurechest(dcnt_old)
if self.chestnum == -1:
self.chestnum = self.ocr_dcnt(dcnt_new)
else:
self.chestnum = self.ocr_dcnt(dcnt_new)
self.asr_y, self.actual_height = self.detect_scroll_bar()
logger.debug("Total Drop (OCR): %d", self.chestnum)
item_pts = self.img2points(mode)
logger.debug("item_pts:%s", item_pts)
self.items = []
self.current_dropPriority = PRIORITY_REWARD_QP
if reward_only:
# qpsplit.py で利用
item_pts = item_pts[0:1]
prev_item = None
for i, pt in enumerate(item_pts):
lx, _ = self.find_edge(self.img_th[pt[1]: pt[3],
pt[0]: pt[2]], reverse=True)
logger.debug("lx: %d", lx)
item_img_th = self.img_th[pt[1] + 37: pt[3] - 30,
pt[0] + lx: pt[2] + lx]
if self.is_empty_box(item_img_th):
break
item_img_rgb = self.img_rgb[pt[1]: pt[3],
pt[0] + lx: pt[2] + lx]
item_img_gray = self.img_gray[pt[1]: pt[3],
pt[0] + lx: pt[2] + lx]
if logger.isEnabledFor(logging.DEBUG):
cv2.imwrite('item' + str(i) + '.png', item_img_rgb)
dropitem = Item(args, i, prev_item, item_img_rgb, item_img_gray,
svm, svm_card, fileextention,
self.current_dropPriority, self.exLogger, mode)
if dropitem.id == -1:
break
self.current_dropPriority = item_dropPriority[dropitem.id]
self.items.append(dropitem)
prev_item = dropitem
self.itemlist = self.makeitemlist()
try:
self.total_qp = self.get_qp(mode)
self.qp_gained = self.get_qp_gained(mode)
asr_y, actual_height = self.detect_scroll_bar()
if asr_y == -1 or actual_height == -1:
self.scroll_position = -1
else:
entire_height = 649 # from correct_pageinfo()
self.scroll_position = asr_y / entire_height
except Exception as e:
self.total_qp = -1
self.qp_gained = -1
self.exLogger.warning("QP detection fails")
logger.exception(e)
if self.qp_gained > 0 and len(self.itemlist) == 0:
raise GainedQPandDropMissMatchError
self.pagenum, self.pages, self.lines = self.correct_pageinfo()
if not reward_only:
self.check_page_mismatch()
# Determine scrollbar's position. AtlasAcademy processing pipeline uses this to group drop-pages
asr_y, actual_height = self.detect_scroll_bar()
if asr_y == -1 or actual_height == -1:
self.scroll_position = -1
else:
entire_height = 649 # from correct_pageinfo()
self.scroll_position = asr_y / entire_height
def check_page_mismatch(self):
valid = check_page_mismatch(
len(self.itemlist),
self.chestnum,
self.pagenum,
self.pages,
self.lines,
)
if not valid:
self.exLogger.warning("drops_count is a mismatch:")
self.exLogger.warning("drops_count = %d", self.chestnum)
self.exLogger.warning("drops_found = %d", len(self.itemlist))
def find_notch(self):
"""
直線検出で検出されなかったフチ幅を検出
"""
edge_width = 150
height, width = self.img_hsv_orig.shape[:2]
target_color = 0
for rx in range(edge_width):
img_hsv_x = self.img_hsv_orig[:, width - rx - 1: width - rx]
# ヒストグラムを計算
hist = cv2.calcHist([img_hsv_x], [0], None, [256], [0, 256])
# 最小値・最大値・最小値の位置・最大値の位置を取得
_, maxVal, _, maxLoc = cv2.minMaxLoc(hist)
if not (maxLoc[1] == target_color and maxVal > height * 0.7):
break
return rx
def drop_count_area(self, img: ndarray,
resize_scale,
sc,
display: bool = False) -> Tuple[Union[ndarray, None], ndarray]:
# widescreenかどうかで挙動を変える
if resize_scale > 1:
img = cv2.resize(img, (0, 0),
fx=resize_scale, fy=resize_scale,
interpolation=cv2.INTER_CUBIC)
elif resize_scale < 1:
img = cv2.resize(img, (0, 0),
fx=resize_scale, fy=resize_scale,
interpolation=cv2.INTER_AREA)
# ((x1, y1), (_, _)) = get_coodinates(img)
# 相対座標(旧UI)
dcnt_old = None
if sc.state.screen_type == "normal":
dcnt_old = img[int(self.y1*resize_scale) - 81: int(self.y1*resize_scale) - 44,
int(self.x1*resize_scale) + 1446: int(self.x1*resize_scale) + 1505]
if display:
cv2.imshow('image', dcnt_old)
cv2.waitKey(0)
cv2.destroyAllWindows()
# 相対座標(新UI)
rx = self.find_notch()
height, width = img.shape[:2]
if width/height > 16/8.96: # Issue #317
dcnt_new = img[int(self.y1*resize_scale) - 20: int(self.y1*resize_scale) + 14,
width - 495 - rx: width - 415 - int(rx*resize_scale)]
else:
dcnt_new = img[int(self.y1*resize_scale) - 20: int(self.y1*resize_scale) + 14,
width - 430: width - 350]
if display:
cv2.imshow('image', dcnt_new)
cv2.waitKey(0)
cv2.destroyAllWindows()
return dcnt_old, dcnt_new
def detect_scroll_bar(self):
'''
Modified from determine_scroll_position()
'''
width = self.img_rgb.shape[1]
topleft = (width - 90, 81)
bottomright = (width, 2 + 753)
if logger.isEnabledFor(logging.DEBUG):
img_copy = self.img_rgb.copy()
cv2.rectangle(img_copy, topleft, bottomright, (0, 0, 255), 3)
cv2.imwrite("./scroll_bar_selected2.jpg", img_copy)
gray_image = self.img_gray[
topleft[1]: bottomright[1],
topleft[0]: bottomright[0]
]
_, binary = cv2.threshold(gray_image, 200, 255, cv2.THRESH_BINARY)
if logger.isEnabledFor(logging.DEBUG):
cv2.imwrite("scroll_bar_binary2.png", binary)
contours = cv2.findContours(
binary,
cv2.RETR_LIST,
cv2.CHAIN_APPROX_NONE
)[0]
pts = []
for cnt in contours:
ret = cv2.boundingRect(cnt)
pt = [ret[0], ret[1], ret[0] + ret[2], ret[1] + ret[3]]
if ret[3] > 10:
pts.append(pt)
if len(pts) == 0:
logger.debug("Can't find scroll bar")
return -1, -1
elif len(pts) > 1:
self.exLogger.warning("Too many objects.")
return -1, -1
else:
return pt[1], pt[3] - pt[1]
def valid_pageinfo(self):
'''
Checking the content of pageinfo and correcting it when it fails
'''
if self.pagenum == -1 or self.pages == -1 or self.lines == -1:
return False
if (self.pagenum == 1 and self.pages == 1 and self.lines == 0) and self.chestnum > 20:
return False
elif self.itemlist[0]["id"] != ID_REWARD_QP and self.pagenum == 1:
return False
elif self.chestnum != -1 and self.pagenum != 1 \
and self.lines != int(self.chestnum/7) + 1:
return False
return True
def correct_pageinfo(self):
if self.valid_pageinfo() is False:
self.exLogger.warning("pageinfo validation failed")
if self.asr_y == -1 or self.actual_height == -1:
return 1, 1, 0
entire_height = 649
esr_y = 17
cap_height = 14 # 正規化後の im.height を 1155 であると仮定して計算した値
pagenum = pageinfo.guess_pagenum(self.asr_y, esr_y, self.actual_height, entire_height, cap_height)
pages = pageinfo.guess_pages(self.actual_height, entire_height, cap_height)
lines = pageinfo.guess_lines(self.actual_height, entire_height, cap_height)
return pagenum, pages, lines
else:
return self.pagenum, self.pages, self.lines
def calc_black_whiteArea(self, bw_image):
image_size = bw_image.size
whitePixels = cv2.countNonZero(bw_image)
whiteAreaRatio = (whitePixels / image_size) * 100 # [%]
return whiteAreaRatio
def is_empty_box(self, img_th):
"""
アイテムボックスにアイテムが無いことを判別する
"""
if self.calc_black_whiteArea(img_th) < 1:
return True
return False
def get_qp_from_text(self, text):
"""
capy-drop-parser から流用
"""
qp = 0
power = 1
# re matches left to right so reverse the list
# to process lower orders of magnitude first.
for match in re.findall("[0-9]+", text)[::-1]:
qp += int(match) * power
power *= 1000
return qp
def extract_text_from_image(self, image):
"""
capy-drop-parser から流用
"""
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
_, qp_image = cv2.threshold(gray, 65, 255, cv2.THRESH_BINARY_INV)
# '+' is needed to ensure that tesseract doesn't force a recognition on it,
# which results in a '4' most of the time.
return pytesseract.image_to_string(
qp_image,
config="-l eng --oem 1 --psm 7 -c tessedit_char_whitelist=+,0123456789",
)
def get_qp(self, mode):
"""
capy-drop-parser から流用
tesseract-OCR is quite slow and changed to use SVM
"""
use_tesseract = False
pt = pageinfo.detect_qp_region(self.img_rgb_orig, mode)
logger.debug('pt from pageinfo: %s', pt)
if pt is None:
use_tesseract = True
qp_total = -1
if use_tesseract is False: # use SVM
im_th = cv2.bitwise_not(
self.img_th_orig[pt[0][1]: pt[1][1], pt[0][0]: pt[1][0]]
)
qp_total = self.ocr_text(im_th)
if use_tesseract or qp_total == -1:
if self.screen_type == "normal":
pt = ((288, 948), (838, 1024))
else:
pt = ((288, 838), (838, 914))
logger.debug('Use tesseract')
qp_total_text = self.extract_text_from_image(
self.img_rgb[pt[0][1]: pt[1][1], pt[0][0]: pt[1][0]]
)
logger.debug('qp_total_text from text: %s', qp_total_text)
qp_total = self.get_qp_from_text(qp_total_text)
logger.debug('qp_total from text: %s', qp_total)
if qp_total > self.max_qp:
self.exLogger.warning(
"qp_total exceeds the system's maximum: %s", qp_total
)
if qp_total == 0:
return QP_UNKNOWN
return qp_total
def get_qp_gained(self, mode):
use_tesseract = False
bounds = pageinfo.detect_qp_region(self.img_rgb_orig, mode)
if bounds is None:
# fall back on hardcoded bound
if self.screen_type == "normal":
bounds = ((398, 858), (948, 934))
else:
bounds = ((398, 748), (948, 824))
use_tesseract = True
else:
# Detecting the QP box with different shading is "easy", while detecting the absence of it
# for the gain QP amount is hard. However, the 2 values have the same font and thus roughly
# the same height (please NA...). You can consider them to be 2 same-sized boxes on top of
# each other.
(topleft, bottomright) = bounds
height = bottomright[1] - topleft[1]
topleft = (topleft[0], topleft[1] - height + int(height*0.12))
bottomright = (bottomright[0], bottomright[1] - height)
bounds = (topleft, bottomright)
logger.debug('Gained QP bounds: %s', bounds)
if logger.isEnabledFor(logging.DEBUG):
img_copy = self.img_rgb.copy()
cv2.rectangle(img_copy, bounds[0], bounds[1], (0, 0, 255), 3)
cv2.imwrite("./qp_gain_detection.jpg", img_copy)
qp_gain = -1
if use_tesseract is False:
im_th = cv2.bitwise_not(
self.img_th_orig[topleft[1]: bottomright[1],
topleft[0]: bottomright[0]]
)
qp_gain = self.ocr_text(im_th)
if use_tesseract or qp_gain == -1:
logger.debug('Use tesseract')
(topleft, bottomright) = bounds
qp_gain_text = self.extract_text_from_image(
self.img_rgb[topleft[1]: bottomright[1],
topleft[0]: bottomright[0]]
)
qp_gain = self.get_qp_from_text(qp_gain_text)
logger.debug('qp from text: %s', qp_gain)
if qp_gain == 0:
qp_gain = QP_UNKNOWN
return qp_gain
def find_edge(self, img_th, reverse=False):
"""
直線検出で検出されなかったフチ幅を検出
"""
edge_width = 4
_, width = img_th.shape[:2]
target_color = 255 if reverse else 0
for i in range(edge_width):
img_th_x = img_th[:, i:i + 1]
# ヒストグラムを計算
hist = cv2.calcHist([img_th_x], [0], None, [256], [0, 256])
# 最小値・最大値・最小値の位置・最大値の位置を取得
_, _, _, maxLoc = cv2.minMaxLoc(hist)
if maxLoc[1] == target_color:
break
lx = i
for j in range(edge_width):
img_th_x = img_th[:, width - j - 1: width - j]
# ヒストグラムを計算
hist = cv2.calcHist([img_th_x], [0], None, [256], [0, 256])
# 最小値・最大値・最小値の位置・最大値の位置を取得
_, _, _, maxLoc = cv2.minMaxLoc(hist)
if maxLoc[1] == 0:
break
rx = j
return lx, rx
def makeitemlist(self):
"""
アイテムを出力
"""
itemlist = []
for item in self.items:
tmp = {}
tmp['id'] = item.id
tmp['name'] = item.name
tmp['dropPriority'] = item_dropPriority[item.id]
tmp['stack'] = int(item.dropnum[1:])
tmp['bonus'] = item.bonus
tmp['category'] = item.category
tmp['x'] = item.position % 7
tmp['y'] = item.position//7
itemlist.append(tmp)
return itemlist
def ocr_text(self, im_th):
h, w = im_th.shape[:2]
# 物体検出
im_th = cv2.bitwise_not(im_th)
contours = cv2.findContours(im_th,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[0]
item_pts = []
for cnt in contours:
ret = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
pt = [ret[0], ret[1], ret[0] + ret[2], ret[1] + ret[3]]
if ret[2] < int(w/2) and area > 80 and ret[1] < h/2 \
and 0.3 < ret[2]/ret[3] < 0.85 and ret[3] > h * 0.45:
flag = False
for p in item_pts:
if has_intersect(p, pt):
# どちらかを消す
p_area = (p[2]-p[0])*(p[3]-p[1])
pt_area = ret[2]*ret[3]
if p_area < pt_area:
item_pts.remove(p)
else:
flag = True
if flag is False:
item_pts.append(pt)
if len(item_pts) == 0:
# Recognizing Failure
return -1
item_pts.sort()
if len(item_pts) > len(str(self.max_qp)):
# QP may be misrecognizing the 10th digit or more, so cut it
item_pts = item_pts[len(item_pts) - len(str(self.max_qp)):]
logger.debug("ocr item_pts: %s", item_pts)
logger.debug("ドロップ桁数(OCR): %d", len(item_pts))
# Hog特徴のパラメータ
win_size = (120, 60)
block_size = (16, 16)
block_stride = (4, 4)
cell_size = (4, 4)
bins = 9
res = ""
for pt in item_pts:
test = []
if pt[0] == 0:
tmpimg = im_th[pt[1]:pt[3], pt[0]:pt[2]+1]
else:
tmpimg = im_th[pt[1]:pt[3], pt[0]-1:pt[2]+1]
tmpimg = cv2.resize(tmpimg, (win_size))
hog = cv2.HOGDescriptor(win_size, block_size,
block_stride, cell_size, bins)
test.append(hog.compute(tmpimg)) # 特徴量の格納
test = np.array(test)
pred = self.svm_chest.predict(test)
res = res + str(int(pred[1][0][0]))
return int(res)
def ocr_tresurechest(self, drop_count_img):
"""
宝箱数をOCRする関数
"""
threshold = 80
img_gray = cv2.cvtColor(drop_count_img, cv2.COLOR_BGR2GRAY)
_, img_num = cv2.threshold(img_gray,
threshold, 255, cv2.THRESH_BINARY)
im_th = cv2.bitwise_not(img_num)
h, w = im_th.shape[:2]
# 情報ウィンドウが数字とかぶった部分を除去する
for y in range(h):
im_th[y, 0] = 255
for x in range(w): # ドロップ数7のときバグる対策 #54
im_th[0, x] = 255
return self.ocr_text(im_th)
def pred_dcnt(self, img):
"""
for JP new UI
"""
# Hog特徴のパラメータ
win_size = (120, 60)
block_size = (16, 16)
block_stride = (4, 4)
cell_size = (4, 4)
bins = 9
char = []
tmpimg = cv2.resize(img, (win_size))
hog = cv2.HOGDescriptor(win_size, block_size,
block_stride, cell_size, bins)
char.append(hog.compute(tmpimg)) # 特徴量の格納
char = np.array(char)
pred = self.svm_dcnt.predict(char)
res = str(int(pred[1][0][0]))
return int(res)
def img2num(self, img, img_th, pts, char_w, end):
"""実際より小さく切り抜かれた数字画像を補正して認識させる
"""
height, width = img.shape[:2]
c_center = int(pts[0] + (pts[2] - pts[0])/2)
# newimg = img[:, item_pts[-1][0]-1:item_pts[-1][2]+1]
newimg = img[:, max(int(c_center - char_w/2), 0):min(int(c_center + char_w/2), width)]
threshold2 = 10
ret, newimg_th = cv2.threshold(newimg,
threshold2,
255,
cv2.THRESH_BINARY)
# 上部はもとのやつを上書き
# for w in range(item_pts[-1][2] - item_pts[-1][0] + 2):
for w in range(min(int(c_center + char_w/2), width) - max(int(c_center - char_w/2), 0)):
for h in range(end):
newimg_th[h, w] = img_th[h, w + int(c_center - char_w/2)]
# newimg_th[h, w] = img_th[h, w + item_pts[-1][0]]
newimg_th[height - 1, w] = 0
newimg_th[height - 2, w] = 0
newimg_th[height - 3, w] = 0
res = self.pred_dcnt(newimg_th)
return res
def ocr_dcnt(self, drop_count_img):
"""
ocr drop_count (for New UI)
"""
char_w = 28
threshold = 80
kernel = np.ones((4, 4), np.uint8)
img = cv2.cvtColor(drop_count_img, cv2.COLOR_BGR2GRAY)
_, img_th = cv2.threshold(img, threshold, 255, cv2.THRESH_BINARY)
img_th = cv2.dilate(img_th, kernel, iterations=1)
height, width = img_th.shape[:2]
end = -1
for i in range(height):
if end == -1 and img_th[height - i - 1, width - 1] == 255:
end = height - i
break
start = end - 7
for j in range(width):
for k in range(end - start):
img_th[start + k, j] = 0
contours = cv2.findContours(img_th,
cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)[0]
item_pts = []
for cnt in contours:
ret = cv2.boundingRect(cnt)
pt = [ret[0], ret[1], ret[0] + ret[2], ret[1] + ret[3]]
if ret[1] > 0 and ret[3] > 8 and ret[1] + ret[3] == start \
and 12 < ret[2] < char_w + 4 and ret[0] + ret[2] != width:
item_pts.append(pt)
if len(item_pts) == 0:
return -1
item_pts.sort()
res = self.img2num(img, img_th, item_pts[-1], char_w, end)
if len(item_pts) >= 2:
if item_pts[-1][0] - item_pts[-2][2] < char_w / (2 / 3):
res2 = self.img2num(img, img_th, item_pts[-2], char_w, end)
res = res2 * 10 + res
if len(item_pts) == 3:
if item_pts[-2][0] - item_pts[-3][2] < char_w / (2 / 3):
res3 = self.img2num(img, img_th, item_pts[-3], char_w, end)
res = res3 * 100 + res2 * 10 + res
return res
def calc_offset(self, pts, std_pts, margin_x):
"""
オフセットを反映
"""
if len(pts) == 0:
return std_pts
# Y列でソート
pts.sort(key=lambda x: x[1])
if len(pts) > 1: # fix #107
if (pts[1][3] - pts[1][1]) - (pts[0][3] - pts[0][1]) > 0:
pts = pts[1:]
# Offsetを算出
offset_x = pts[0][0] - margin_x
offset_y = pts[0][1] - std_pts[0][1]
if offset_y > (std_pts[7][3] - std_pts[7][1])*2:
# これ以上になったら三行目の座標と判断
offset_y = pts[0][1] - std_pts[14][1]
elif offset_y > 30:
# これ以上になったら二行目の座標と判断
offset_y = pts[0][1] - std_pts[7][1]
# Offset を反映
item_pts = []
for pt in std_pts:
ptl = list(pt)
ptl[0] = ptl[0] + offset_x
ptl[1] = ptl[1] + offset_y
ptl[3] = ptl[3] + offset_y
ptl[2] = ptl[2] + offset_x
item_pts.append(ptl)
return item_pts
def img2points(self, mode):
"""
戦利品左一列のY座標を求めて標準座標とのずれを補正して座標を出力する
"""
std_pts = self.booty_pts()
row_size = 7 # アイテム表示最大列
col_size = 3 # アイテム表示最大行
margin_x = 15
area_size_lower = 37000 # アイテム枠の面積の最小値
img_1strow = self.img_th[0:self.height,
std_pts[0][0] - margin_x:
std_pts[0][2] + margin_x]
SCROLLBAR_WIDTH4ONEPAGE = 610
POSITION_TOP = 16
POSITION_BOTTOM_JP = 42 # JP
POSITION_BOTTOM_NA = 52 # NA
SCROLL_OFFSET = 28
# 輪郭を抽出
contours = cv2.findContours(img_1strow, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)[0]
leftcell_pts = []
for cnt in contours:
area = cv2.contourArea(cnt)
if area > area_size_lower \
and area < self.height * self.width / (row_size * col_size):
epsilon = 0.01*cv2.arcLength(cnt, True)
approx = cv2.approxPolyDP(cnt, epsilon, True)
if 4 <= len(approx) <= 6: # 六角形のみ認識
ret = cv2.boundingRect(cnt)
if ret[1] > self.height * 0.15 - 101 \
and ret[1] + ret[3] < self.height * 0.76 - 101:
# 小数の数値はだいたいの実測
pts = [ret[0], ret[1],
ret[0] + ret[2], ret[1] + ret[3]]
leftcell_pts.append(pts)
if len(leftcell_pts) != 0:
item_pts = self.calc_offset(leftcell_pts, std_pts, margin_x)
logger.debug("leftcell_pts: %s", leftcell_pts)
else:
if (self.asr_y == POSITION_TOP and self.actual_height == SCROLLBAR_WIDTH4ONEPAGE) or self.actual_height == -1:
# case: normal
if mode == "na":
leftcell_pts = [[25, 109, 214, 315]]
else:
leftcell_pts = [[14, 97, 202, 303]]
item_pts = self.calc_offset(leftcell_pts, std_pts, margin_x)
elif POSITION_BOTTOM_JP <= self.asr_y <= POSITION_BOTTOM_NA and self.actual_height == SCROLLBAR_WIDTH4ONEPAGE:
# case: scrolling down by mistake
if mode == "na":
leftcell_pts = [[25, 299, 214, 504]]
else:
leftcell_pts = [[14, 97 - SCROLL_OFFSET, 202, 303 - SCROLL_OFFSET]]
item_pts = self.calc_offset(leftcell_pts, std_pts, margin_x)
return item_pts
def booty_pts(self):
"""
戦利品が出現する21の座標 [left, top, right, bottom]
解像度別に設定
"""
criteria_left = 102
criteria_top = 99
item_width = 188
item_height = 206
margin_width = 32
margin_height = 21
pts = generate_booty_pts(criteria_left, criteria_top,
item_width, item_height,
margin_width, margin_height)
return pts
def generate_booty_pts(criteria_left, criteria_top, item_width, item_height,
margin_width, margin_height):
"""
ScreenShot#booty_pts() が返すべき座標リストを生成する。
全戦利品画像が等間隔に並んでいることを仮定している。
criteria_left ... 左上にある戦利品の left 座標
criteria_top ... 左上にある戦利品の top 座標
item_width ... 戦利品画像の width
item_height ... 戦利品画像の height
margin_width ... 戦利品画像間の width
margin_height ... 戦利品画像間の height
"""
pts = []
current = (criteria_left, criteria_top, criteria_left + item_width,
criteria_top + item_height)
for j in range(3):
# top, bottom の y座標を計算
current_top = criteria_top + (item_height + margin_height) * j
current_bottom = current_top + item_height
# x座標を左端に固定
current = (criteria_left, current_top,
criteria_left + item_width, current_bottom)
for i in range(7):
# y座標を固定したままx座標をスライドさせていく
current_left = criteria_left + (item_width + margin_width) * i
current_right = current_left + item_width
current = (current_left, current_top,
current_right, current_bottom)
pts.append(current)
return pts
class Item:
def __init__(self, args, pos, prev_item, img_rgb, img_gray, svm, svm_card,
fileextention, current_dropPriority, exLogger, mode='jp'):
self.position = pos
self.prev_item = prev_item
self.img_rgb = img_rgb
self.img_gray = img_gray
self.img_hsv = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2HSV)
_, img_th = cv2.threshold(self.img_gray, 174, 255, cv2.THRESH_BINARY)
self.img_th = cv2.bitwise_not(img_th)
self.fileextention = fileextention
self.exLogger = exLogger
self.dropnum_cache = []
self.margin_left = 5
self.height, self.width = img_rgb.shape[:2]
logger.debug("pos: %d", pos)
self.identify_item(args, prev_item, svm_card,
current_dropPriority)
if self.id == -1:
return
logger.debug("id: %d", self.id)
logger.debug("background: %s", self.background)
logger.debug("dropPriority: %s", item_dropPriority[self.id])
logger.debug("Category: %s", self.category)
logger.debug("Name: %s", self.name)
self.svm = svm
self.bonus = ""
if self.category != "Craft Essence" and self.category != "Exp. UP":
self.ocr_digit(mode)
else:
self.dropnum = "x1"
logger.debug("Bonus: %s", self.bonus)
logger.debug("Stack: %s", self.dropnum)
def identify_item(self, args, prev_item, svm_card,
current_dropPriority):
self.background = classify_background(self.img_rgb)
self.hash_item = compute_hash(self.img_rgb) # 画像の距離
if prev_item is not None:
# [Requirements for Caching]
# 1. previous item is not a reward QP.
# 2. Same background as the previous item
# 3. Not (similarity is close) dice, gem or EXP
if prev_item.id != ID_REWARD_QP \
and prev_item.background == self.background \
and not (ID_GEM_MIN <= prev_item.id <= ID_SECRET_GEM_MAX or
ID_2ZORO_DICE <= prev_item.id <= ID_3ZORO_DICE or
ID_EXP_MIN <= prev_item.id <= ID_EXP_MAX):
d = hasher.compare(self.hash_item, prev_item.hash_item)
if d <= 4:
self.category = prev_item.category
self.id = prev_item.id
self.name = prev_item.name
return
self.category = self.classify_category(svm_card)
self.id = self.classify_card(self.img_rgb, current_dropPriority)
if args.lang == "jpn":
self.name = item_name[self.id]
else:
if self.id in item_name_eng.keys():
self.name = item_name_eng[self.id]
else:
self.name = item_name[self.id]
if self.category == "":
if self.id in item_type:
self.category = item_type[self.id]
else:
self.category = "Item"
def conflictcheck(self, pts, pt):
"""
pt が ptsのどれかと衝突していたら面積に応じて入れ替える
"""
flag = False
for p in list(pts):
if has_intersect(p, pt):
# どちらかを消す
p_area = (p[2]-p[0])*(p[3]-p[1])
pt_area = (pt[2]-pt[0])*(pt[3]-pt[1])
if p_area < pt_area:
pts.remove(p)
else:
flag = True
if flag is False:
pts.append(pt)
return pts
def extension(self, pts):
"""
文字エリアを1pixcel微修正
"""
new_pts = []
for pt in pts:
if pt[0] == 0 and pt[1] == 0:
pt = [pt[0], pt[1], pt[2], pt[3] + 1]
elif pt[0] == 0 and pt[1] != 0:
pt = [pt[0], pt[1] - 1, pt[2], pt[3] + 1]
elif pt[0] != 0 and pt[1] == 0:
pt = [pt[0] - 1, pt[1], pt[2], pt[3] + 1]
else:
pt = [pt[0] - 1, pt[1] - 1, pt[2], pt[3] + 1]
new_pts.append(pt)
return new_pts
def extension_straighten(self, pts):
"""
Y軸を最大値にそろえつつ文字エリアを1pixcel微修正
"""
base_top = 6 # 強制的に高さを確保
base_bottom = 10
for pt in pts:
if base_top > pt[1]:
base_top = pt[1]
if base_bottom < pt[3]:
base_bottom = pt[3]
# 5桁目がおかしくなる対策
new_pts = []
pts.reverse()
for i, pt in enumerate(pts):
if len(pts) > 6 and i == 4:
pt = [pts[5][2], base_top, pts[3][0], base_bottom]
else:
pt = [pt[0], base_top, pt[2], base_bottom]
new_pts.append(pt)
new_pts.reverse()
return new_pts
def detect_bonus_char4jpg(self, mode):
"""
[JP]Ver.2.37.0以前の仕様
戦利品数OCRで下段の黄文字の座標を抽出する
PNGではない画像の認識用
"""
# QP,ポイントはボーナス6桁のときに高さが変わる
# それ以外は3桁のときに変わるはず(未確認)
# ここのmargin_right はドロップ数の下一桁目までの距離
base_line = 181 if mode == "na" else 179
pattern_tiny = r"^\(\+\d{4,5}0\)$"
pattern_small = r"^\(\+\d{5}0\)$"
pattern_normal = r"^\(\+[1-9]\d*\)$"
# 1-5桁の読み込み
font_size = FONTSIZE_NORMAL
if mode == 'na':
margin_right = 20
else:
margin_right = 26
line, pts = self.get_number4jpg(base_line, margin_right, font_size)
logger.debug("Read BONUS NORMAL: %s", line)
m_normal = re.match(pattern_normal, line)
if m_normal:
logger.debug("Font Size: %d", font_size)
return line, pts, font_size
# 6桁の読み込み
if mode == 'na':
margin_right = 19
else:
margin_right = 25
font_size = FONTSIZE_SMALL
line, pts = self.get_number4jpg(base_line, margin_right, font_size)
logger.debug("Read BONUS SMALL: %s", line)
m_small = re.match(pattern_small, line)
if m_small:
logger.debug("Font Size: %d", font_size)
return line, pts, font_size
# 7桁読み込み
font_size = FONTSIZE_TINY
if mode == 'na':
margin_right = 18
else:
margin_right = 26
line, pts = self.get_number4jpg(base_line, margin_right, font_size)
logger.debug("Read BONUS TINY: %s", line)
m_tiny = re.match(pattern_tiny, line)
if m_tiny:
logger.debug("Font Size: %d", font_size)
return line, pts, font_size
else:
font_size = FONTSIZE_UNDEFINED
logger.debug("Font Size: %d", font_size)
line = ""
pts = []
return line, pts, font_size
def detect_bonus_char4jpg2(self, mode):
"""
[JP]Ver.2.37.0以降の仕様
戦利品数OCRで下段の黄文字の座標を抽出する
PNGではない画像の認識用
"""
# QP,ポイントはボーナス6桁のときに高さが変わる
# それ以外は3桁のときに変わるはず(未確認)
# ここのmargin_right はドロップ数の下一桁目までの距離
base_line = 181 if mode == "na" else 179
pattern_tiny = r"^\(\+\d{4,5}0\)$"
pattern_small = r"^\(\+\d{5}0\)$"
pattern_normal = r"^\(\+[1-9]\d*\)$"
font_size = FONTSIZE_NEWSTYLE
if mode == 'na':
margin_right = 20
else:
margin_right = 26
# 1-5桁の読み込み
cut_width = 21
comma_width = 5
line, pts = self.get_number4jpg2(base_line, margin_right, cut_width, comma_width)
logger.debug("Read BONUS NORMAL: %s", line)
m_normal = re.match(pattern_normal, line)
if m_normal:
logger.debug("Font Size: %d", font_size)
return line, pts, font_size
# 6桁の読み込み
cut_width = 19
comma_width = 5
line, pts = self.get_number4jpg2(base_line, margin_right, cut_width, comma_width)
logger.debug("Read BONUS SMALL: %s", line)
m_small = re.match(pattern_small, line)
if m_small:
logger.debug("Font Size: %d", font_size)
return line, pts, font_size
# 7桁読み込み
cut_width = 18
comma_width = 5
line, pts = self.get_number4jpg2(base_line, margin_right, cut_width, comma_width)
logger.debug("Read BONUS TINY: %s", line)
m_tiny = re.match(pattern_tiny, line)
if m_tiny:
logger.debug("Font Size: %d", font_size)
return line, pts, font_size
else:
font_size = FONTSIZE_UNDEFINED
logger.debug("Font Size: %d", font_size)
line = ""
pts = []
return line, pts, font_size
def detect_bonus_char(self):
"""
戦利品数OCRで下段の黄文字の座標を抽出する
HSVで黄色をマスクしてオブジェクト検出
ノイズは少なく精度はかなり良い
"""
margin_top = int(self.height*0.72)
margin_bottom = int(self.height*0.11)
margin_left = 8
margin_right = 8
img_hsv_lower = self.img_hsv[margin_top: self.height - margin_bottom,
margin_left: self.width - margin_right]
h, w = img_hsv_lower.shape[:2]
# 手持ちスクショでうまくいっている範囲
# 黄文字がこの数値でマスクできるかが肝
# 未対応機種が発生したため[25,180,119] →[25,175,119]に変更
lower_yellow = np.array([25, 175, 119])
upper_yellow = np.array([37, 255, 255])
img_hsv_lower_mask = cv2.inRange(img_hsv_lower,
lower_yellow, upper_yellow)
contours = cv2.findContours(img_hsv_lower_mask, cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)[0]
bonus_pts = []
# 物体検出マスクがうまくいっているかが成功の全て
for cnt in contours:
ret = cv2.boundingRect(cnt)
area = cv2.contourArea(cnt)
pt = [ret[0] + margin_left, ret[1] + margin_top,
ret[0] + ret[2] + margin_left, ret[1] + ret[3] + margin_top]
# )が上下に割れることがあるので上の一つは消す
if ret[2] < int(w/2) and ret[1] < int(h*3/5) \
and ret[1] + ret[3] > h*0.65 and area > 3:
bonus_pts = self.conflictcheck(bonus_pts, pt)
bonus_pts.sort()
if len(bonus_pts) > 0:
if self.width - bonus_pts[-1][2] > int((22*self.width/188)):
# 黄文字は必ず右寄せなので最後の文字が画面端から離れている場合全部ゴミ
bonus_pts = []
return self.extension(bonus_pts)
def define_fontsize(self, font_size):
if font_size == FONTSIZE_NORMAL:
cut_width = 20
cut_height = 28
comma_width = 9
elif font_size == FONTSIZE_SMALL:
cut_width = 18
cut_height = 25
comma_width = 8
else:
cut_width = 16
cut_height = 22
comma_width = 6
return cut_width, cut_height, comma_width
def get_number4jpg(self, base_line, margin_right, font_size):
"""[JP]Ver.2.37.0以前の仕様
"""
cut_width, cut_height, comma_width = self.define_fontsize(font_size)
top_y = base_line - cut_height
# まず、+, xの位置が何桁目か調査する
pts = []
if font_size == FONTSIZE_TINY:
max_digits = 8
elif font_size == FONTSIZE_SMALL:
max_digits = 8
else:
max_digits = 7
for i in range(max_digits):
if i == 0:
continue
pt = [self.width - margin_right - cut_width * (i + 1)
- comma_width * int((i - 1)/3),
top_y,
self.width - margin_right - cut_width * i
- comma_width * int((i - 1)/3),
base_line]
result = self.read_char(pt)
if i == 1 and ord(result) == 0:
# アイテム数 x1 とならず表記無し場合のエラー処理
return "", pts
if result in ['x', '+']:
break
# 決まった位置まで出力する
line = ""
for j in range(i):
pt = [self.width - margin_right - cut_width * (j + 1)
- comma_width * int(j/3),
top_y,
self.width - margin_right - cut_width * j
- comma_width * int(j/3),
base_line]
c = self.read_char(pt)
if ord(c) == 0: # Null文字対策
line = line + '?'
break
line = line + c
pts.append(pt)
j = j + 1
pt = [self.width - margin_right - cut_width * (j + 1)
- comma_width * int((j - 1)/3),
top_y,
self.width - margin_right - cut_width * j
- comma_width * int((j - 1)/3),
base_line]
c = self.read_char(pt)
if ord(c) == 0: # Null文字対策
c = '?'
line = line + c
line = "(" + line[::-1] + ")"
pts.append(pt)
pts.sort()
# PNGのマスク法との差を埋める補正
new_pts = [[pts[0][0]-10, pts[0][1],
pts[0][0]-1, pts[0][3]]] # "(" に対応
new_pts.append("") # ")" に対応
return line, new_pts
def get_number4jpg2(self, base_line, margin_right, cut_width, comma_width):
"""[JP]Ver.2.37.0以降の仕様
"""
cut_height = 30
top_y = base_line - cut_height
# まず、+, xの位置が何桁目か調査する
pts = []
max_digits = 7
for i in range(max_digits):
if i == 0:
continue
pt = [self.width - margin_right - cut_width * (i + 1)
- comma_width * int((i - 1)/3),
top_y,
self.width - margin_right - cut_width * i
- comma_width * int((i - 1)/3),
base_line]
result = self.read_char(pt)
if i == 1 and ord(result) == 0:
# アイテム数 x1 とならず表記無し場合のエラー処理
return "", pts
if result in ['x', '+']:
break
# 決まった位置まで出力する
line = ""
for j in range(i):
pt = [self.width - margin_right - cut_width * (j + 1)
- comma_width * int(j/3),
top_y,
self.width - margin_right - cut_width * j
- comma_width * int(j/3),
base_line]
c = self.read_char(pt)
if ord(c) == 0: # Null文字対策
line = line + '?'
break
line = line + c
pts.append(pt)
j = j + 1
pt = [self.width - margin_right - cut_width * (j + 1)
- comma_width * int((j - 1)/3),
top_y,
self.width - margin_right - cut_width * j
- comma_width * int((j - 1)/3),
base_line]
c = self.read_char(pt)
if ord(c) == 0: # Null文字対策
c = '?'
line = line + c
line = "(" + line[::-1] + ")"
pts.append(pt)
pts.sort()
# PNGのマスク法との差を埋める補正
new_pts = [[pts[0][0]-10, pts[0][1],
pts[0][0]-1, pts[0][3]]] # "(" に対応
new_pts.append("") # ")" に対応
return line, new_pts
def get_number(self, base_line, margin_right, font_size):
"""[JP]Ver.2.37.0以前の仕様
"""
cut_width, cut_height, comma_width = self.define_fontsize(font_size)
top_y = base_line - cut_height
# まず、+, xの位置が何桁目か調査する
for i in range(8): # 8桁以上は無い
if i == 0:
continue
elif (self.id == ID_REWARD_QP
or self.category in ["Point"]) and i <= 2:
# 報酬QPとPointは3桁以上
continue
elif self.name == "QP" and i <= 3:
# QPは4桁以上
continue
pt = [self.width - margin_right - cut_width * (i + 1)
- comma_width * int((i - 1)/3),
top_y,
self.width - margin_right - cut_width * i
- comma_width * int((i - 1)/3),
base_line]
if pt[0] < 0:
break
result = self.read_char(pt)
if i == 1 and ord(result) == 0:
# アイテム数 x1 とならず表記無し場合のエラー処理
return ""
if result in ['x', '+']:
self.margin_left = pt[0]
break
# 決まった位置まで出力する
line = ""
for j in range(i):
if (self.id == ID_REWARD_QP) and j < 1:
# 報酬QPの下一桁は0
line += '0'
continue
elif (self.name == "QP" or self.category in ["Point"]) and j < 2:
# QPとPointは下二桁は00
line += '0'
continue
pt = [self.width - margin_right - cut_width * (j + 1)
- comma_width * int(j/3),
top_y,
self.width - margin_right - cut_width * j
- comma_width * int(j/3),
base_line]
if pt[0] < 0:
break
c = self.read_char(pt)
if ord(c) == 0: # Null文字対策
c = '?'
line = line + c
j = j + 1
pt = [self.width - margin_right - cut_width * (j + 1)
- comma_width * int((j - 1)/3),
top_y,
self.width - margin_right - cut_width * j
- comma_width * int((j - 1)/3),
base_line]
if pt[0] > 0:
c = self.read_char(pt)
if ord(c) == 0: # Null文字対策
c = '?'
line = line + c
line = line[::-1]
return line
def get_number2(self, cut_width, comma_width, base_line=147, margin_right=15):
"""[JP]Ver.2.37.0以降の仕様
"""
cut_height = 26
# base_line = 147
# margin_right = 15
top_y = base_line - cut_height
# まず、+, xの位置が何桁目か調査する
for i in range(8): # 8桁以上は無い
if i == 0:
continue
elif (self.id == ID_REWARD_QP
or self.category in ["Point"]) and i <= 2:
# 報酬QPとPointは3桁以上
continue
elif self.name == "QP" and i <= 3:
# QPは4桁以上
continue
pt = [self.width - margin_right - cut_width * (i + 1)
- comma_width * int((i - 1)/3),
top_y,
self.width - margin_right - cut_width * i
- comma_width * int((i - 1)/3),
base_line]
if pt[0] < 0:
break
result = self.read_char(pt)
if i == 1 and ord(result) == 0:
# アイテム数 x1 とならず表記無し場合のエラー処理
return ""
if result in ['x', '+']:
self.margin_left = pt[0]
break
# 決まった位置まで出力する
line = ""
for j in range(i):
if (self.id == ID_REWARD_QP) and j < 1:
# 報酬QPの下一桁は0
line += '0'
continue
elif (self.name == "QP" or self.category in ["Point"]) and j < 2:
# QPとPointは下二桁は00
line += '0'
continue
pt = [self.width - margin_right - cut_width * (j + 1)
- comma_width * int(j/3),
top_y,
self.width - margin_right - cut_width * j
- comma_width * int(j/3),
base_line]
if pt[0] < 0:
break
c = self.read_char(pt)
if ord(c) == 0: # Null文字対策
c = '?'
line = line + c
j = j + 1
pt = [self.width - margin_right - cut_width * (j + 1)
- comma_width * int((j - 1)/3),
top_y,
self.width - margin_right - cut_width * j
- comma_width * int((j - 1)/3),
base_line]
if pt[0] > 0:
c = self.read_char(pt)
if ord(c) == 0: # Null文字対策
c = '?'
line = line + c
line = line[::-1]
return line
def detect_white_char(self, base_line, margin_right, mode="jp"):
"""
上段と下段の白文字を見つける機能を一つに統合
[JP]Ver.2.37.0からボーナスがある場合の表示の仕様変更有り
"""
pattern_tiny = r"^[\+x][12]\d{4}00$"
pattern_tiny_qp = r"^\+[12]\d{4,5}00$"
pattern_small = r"^[\+x]\d{4}00$"
pattern_small_qp = r"^\+\d{4,5}00$"
pattern_normal = r"^[\+x][1-9]\d{0,5}$"
pattern_normal_qp = r"^\+[1-9]\d{0,4}0$"
logger.debug("base_line: %d", base_line)
if mode == "jp" and base_line < 170:
# JP Ver.2.37.0以降の新仕様
# 1-6桁の読み込み
font_size = FONTSIZE_NEWSTYLE
cut_width = 21
comma_width = 5
line = self.get_number2(cut_width, comma_width)
logger.debug("Read NORMAL: %s", line)
if self.id == ID_QP or self.category == "Point":
pattern_normal = pattern_normal_qp
m_normal = re.match(pattern_normal, line)
if m_normal:
logger.debug("Font Size: %d", font_size)
self.font_size = font_size
return line
# 6桁の読み込み
cut_width = 19
comma_width = 5
line = self.get_number2(cut_width, comma_width)
logger.debug("Read SMALL: %s", line)
if self.id == ID_QP or self.category == "Point":
pattern_small = pattern_small_qp
m_small = re.match(pattern_small, line)
if m_small:
logger.debug("Font Size: %d", font_size)
self.font_size = font_size
return line
# 7桁読み込み
cut_width = 19
comma_width = 4
line = self.get_number2(cut_width, comma_width)
logger.debug("Read TINY: %s", line)
if self.id == ID_QP or self.category == "Point":
pattern_tiny = pattern_tiny_qp
m_tiny = re.match(pattern_tiny, line)
if m_tiny:
logger.debug("Font Size: %d", font_size)
self.font_size = font_size
return line
elif mode == "jp" and self.id not in [ID_QP, ID_REWARD_QP] and self.category != "Point":
cut_width = 21
comma_width = 5
line = self.get_number2(cut_width, comma_width, base_line=base_line, margin_right=margin_right)
logger.debug("line: %s", line)
if len(line) <= 1:
return ""
elif not line[1:].isdigit():
return ""
return line
else:
# JP Ver.2.37.0以前の旧仕様
if self.font_size != FONTSIZE_UNDEFINED:
line = self.get_number(base_line, margin_right, self.font_size)
logger.debug("line: %s", line)
if len(line) <= 1:
return ""
elif not line[1:].isdigit():
return ""
return line
else:
# 1-6桁の読み込み
font_size = FONTSIZE_NORMAL
line = self.get_number(base_line, margin_right, font_size)
logger.debug("Read NORMAL: %s", line)
if self.id == ID_QP or self.category == "Point":
pattern_normal = pattern_normal_qp
m_normal = re.match(pattern_normal, line)
if m_normal:
logger.debug("Font Size: %d", font_size)
self.font_size = font_size
return line
# 6桁の読み込み
font_size = FONTSIZE_SMALL
line = self.get_number(base_line, margin_right, font_size)
logger.debug("Read SMALL: %s", line)
if self.id == ID_QP or self.category == "Point":
pattern_small = pattern_small_qp
m_small = re.match(pattern_small, line)
if m_small:
logger.debug("Font Size: %d", font_size)
self.font_size = font_size
return line
# 7桁読み込み
font_size = FONTSIZE_TINY
line = self.get_number(base_line, margin_right, font_size)
logger.debug("Read TINY: %s", line)
if self.id == ID_QP or self.category == "Point":
pattern_tiny = pattern_tiny_qp
m_tiny = re.match(pattern_tiny, line)
if m_tiny:
logger.debug("Font Size: %d", font_size)
self.font_size = font_size
return line
return ""
def read_item(self, pts):
"""
ボーナスの数値をOCRする(エラー訂正有)
"""
win_size = (120, 60)
block_size = (16, 16)
block_stride = (4, 4)
cell_size = (4, 4)
bins = 9
lines = ""
for pt in pts:
char = []
tmpimg = self.img_gray[pt[1]:pt[3], pt[0]:pt[2]]
tmpimg = cv2.resize(tmpimg, (win_size))
hog = cv2.HOGDescriptor(win_size, block_size, block_stride,
cell_size, bins)
char.append(hog.compute(tmpimg))
char = np.array(char)
pred = self.svm.predict(char)
result = int(pred[1][0][0])
if result != 0:
lines = lines + chr(result)
logger.debug("OCR Result: %s", lines)
# 以下エラー訂正
if not lines.endswith(")"):
lines = lines[:-1] + ")"
if not lines.startswith("(+") and not lines.startswith("(x"):
if lines[0] in ["+", 'x']:
lines = "(" + lines
elif lines.startswith("("):
lines = lines.replace("(", "(+")
else:
lines = ""
lines = lines.replace("()", "0")
if len(lines) > 1:
# エラー訂正 文字列左側
# 主にイベントのポイントドロップで左側にゴミができるが、
# 特定の記号がでてきたらそれより前はデータが無いはずなので削除する
point_lbra = lines.rfind("(")
point_plus = lines.rfind("+")
point_x = lines.rfind("x")
if point_lbra != -1:
lines = lines[point_lbra:]
elif point_plus != -1:
lines = lines[point_plus:]
elif point_x != -1:
lines = lines[point_x:]
if lines.isdigit():
if int(lines) == 0:
lines = "xErr"
elif self.name == "QP" or self.name == "クエストクリア報酬QP":
lines = '+' + lines
else:
if int(lines) >= 100:
lines = '+' + lines
else:
lines = 'x' + lines
if len(lines) == 1:
lines = "xErr"
return lines
def read_char(self, pt):
"""
戦利品の数値1文字をOCRする
白文字検出で使用
"""
win_size = (120, 60)
block_size = (16, 16)
block_stride = (4, 4)
cell_size = (4, 4)
bins = 9
char = []
tmpimg = self.img_gray[pt[1]:pt[3], pt[0]:pt[2]]
tmpimg = cv2.resize(tmpimg, (win_size))
hog = cv2.HOGDescriptor(win_size, block_size, block_stride,
cell_size, bins)
char.append(hog.compute(tmpimg))
char = np.array(char)
pred = self.svm.predict(char)
result = int(pred[1][0][0])
return chr(result)
def ocr_digit(self, mode='jp'):
"""
戦利品OCR
"""
self.font_size = FONTSIZE_UNDEFINED
if self.prev_item is None:
prev_id = -1
else:
prev_id = self.prev_item.id
logger.debug("self.id: %d", self.id)
logger.debug("prev_id: %d", prev_id)
if prev_id == self.id:
self.dropnum_cache = self.prev_item.dropnum_cache
if prev_id == self.id \
and not (ID_GEM_MAX <= self.id <= ID_MONUMENT_MAX):
# もしキャッシュ画像と一致したらOCRスキップ
logger.debug("dropnum_cache: %s", self.prev_item.dropnum_cache)
for dropnum_cache in self.prev_item.dropnum_cache:
pts = dropnum_cache["pts"]
img_gray = self.img_gray[pts[0][1]-2:pts[1][1]+2,
pts[0][0]-2:pts[1][0]+2]
template = dropnum_cache["img"]
res = cv2.matchTemplate(img_gray, template,
cv2.TM_CCOEFF_NORMED)
threshold = 0.97
loc = np.where(res >= threshold)
find_match = False
for pt in zip(*loc[::-1]):
find_match = True
break
if find_match:
logger.debug("find_match")
self.bonus = dropnum_cache["bonus"]
self.dropnum = dropnum_cache["dropnum"]
self.bonus_pts = dropnum_cache["bonus_pts"]
return
logger.debug("not find_match")
if ID_GEM_MAX <= self.id <= ID_MONUMENT_MAX:
# ボーナスが無いアイテム
self.bonus_pts = []
self.bonus = ""
self.font_size = FONTSIZE_NORMAL
elif prev_id == self.id \
and self.category != "Point" and self.name != "QP":
self.bonus_pts = self.prev_item.bonus_pts
self.bonus = self.prev_item.bonus
self.font_size = self.prev_item.font_size
elif self.fileextention.lower() == '.png':
self.bonus_pts = self.detect_bonus_char()
self.bonus = self.read_item(self.bonus_pts)
# フォントサイズを決定
if len(self.bonus_pts) > 0:
y_height = self.bonus_pts[-1][3] - self.bonus_pts[-1][1]
logger.debug("y_height: %s", y_height)
if self.position >= 14:
self.font_size = FONTSIZE_UNDEFINED
elif y_height < 25:
self.font_size = FONTSIZE_TINY
elif y_height > 27:
self.font_size = FONTSIZE_NORMAL
else:
self.font_size = FONTSIZE_SMALL
else:
if mode == "jp":
self.bonus, self.bonus_pts, self.font_size = self.detect_bonus_char4jpg2(mode)
else:
self.bonus, self.bonus_pts, self.font_size = self.detect_bonus_char4jpg(mode)
logger.debug("Bonus Font Size: %s", self.font_size)
# 実際の(ボーナス無し)ドロップ数が上段にあるか下段にあるか決定
offsset_y = 2 if mode == 'na' else 0
if (self.category in ["Quest Reward", "Point"] or self.name == "QP") \
and len(self.bonus) >= 5: # ボーナスは"(+*0)"なので
# 1桁目の上部からの距離を設定
base_line = self.bonus_pts[-2][1] - 3 + offsset_y
else:
base_line = int(180/206*self.height)
self.__bonus_string_into_int()
# 実際の(ボーナス無し)ドロップ数の右端の位置を決定
offset_x = -7 if mode == "na" else 0
if self.category in ["Quest Reward", "Point"] or self.name == "QP":
margin_right = 15 + offset_x
elif len(self.bonus_pts) > 0:
margin_right = self.width - self.bonus_pts[0][0] + 2
else:
margin_right = 15 + offset_x
logger.debug("margin_right: %d", margin_right)
self.dropnum = self.detect_white_char(base_line, margin_right, mode)
logger.debug("self.dropnum: %s", self.dropnum)
if len(self.dropnum) == 0:
self.dropnum = "x1"
if self.id != ID_REWARD_QP \
and not (ID_GEM_MAX <= self.id <= ID_MONUMENT_MAX):
dropnum_found = False
for cache_item in self.dropnum_cache:
if cache_item["dropnum"] == self.dropnum:
dropnum_found = True
break
if dropnum_found is False:
# キャッシュのために画像を取得する
_, width = self.img_gray.shape
_, cut_height, _ = self.define_fontsize(self.font_size)
logger.debug("base_line: %d", base_line)
logger.debug("cut_height: %d", cut_height)
logger.debug("margin_right: %d", margin_right)
pts = ((self.margin_left, base_line - cut_height),
(width - margin_right, base_line))
cached_img = self.img_gray[pts[0][1]:pts[1][1],
pts[0][0]:pts[1][0]]
tmp = {}
tmp["dropnum"] = self.dropnum
tmp["img"] = cached_img
tmp["pts"] = pts
tmp["bonus"] = self.bonus
tmp["bonus_pts"] = self.bonus_pts
self.dropnum_cache.append(tmp)
def __bonus_string_into_int(self):
try:
self.bonus = int(re.sub(r"\(|\)|\+", "", self.bonus))
except:
self.bonus = 0
def gem_img2id(self, img, gem_dict):
hash_gem = self.compute_gem_hash(img)
gems = {}
for i in gem_dict.keys():
d2 = hasher.compare(hash_gem, hex2hash(gem_dict[i]))
if d2 <= 20:
gems[i] = d2
gems = sorted(gems.items(), key=lambda x: x[1])
gem = next(iter(gems))
return gem[0]
def classify_item(self, img, currnet_dropPriority):
""")
imgとの距離を比較して近いアイテムを求める
id を返すように変更
"""
hash_item = self.hash_item # 画像の距離
if logger.isEnabledFor(logging.DEBUG):
hex = ""
for h in hash_item[0]:
hex = hex + "{:02x}".format(h)
logger.debug("phash: %s", hex)
def compare_distance(hash_item, background=True):
ids = {}
# 既存のアイテムとの距離を比較
for i in dist_item.keys():
itemid = dist_item[i]
item_bg = item_background[itemid]
d = hasher.compare(hash_item, hex2hash(i))
if background:
if d <= 13 and item_bg == self.background:
# ポイントと種の距離が8という例有り(IMG_0274)→16に
# バーガーと脂の距離が10という例有り(IMG_2354)→14に
ids[dist_item[i]] = d
else:
if d <= 13:
ids[dist_item[i]] = d
if len(ids) > 0:
ids = sorted(ids.items(), key=lambda x: x[1])
id_tupple = next(iter(ids))
id = id_tupple[0]
if ID_SECRET_GEM_MIN <= id <= ID_SECRET_GEM_MAX:
if currnet_dropPriority >= PRIORITY_SECRET_GEM_MIN:
id = self.gem_img2id(img, dist_secret_gem)
else:
return ""
elif ID_MAGIC_GEM_MIN <= id <= ID_MAGIC_GEM_MAX:
if currnet_dropPriority >= PRIORITY_MAGIC_GEM_MIN:
id = self.gem_img2id(img, dist_magic_gem)
else:
return ""
elif ID_GEM_MIN <= id <= ID_GEM_MAX:
if currnet_dropPriority >= PRIORITY_GEM_MIN:
id = self.gem_img2id(img, dist_gem)
else:
return ""
return id
return ""
id = compare_distance(hash_item, background=True)
if id == "":
id = compare_distance(hash_item, background=False)
return id
def classify_ce_sub(self, img, hasher_prog, dist_dic, threshold):
"""
imgとの距離を比較して近いアイテムを求める
"""
hash_item = hasher_prog(img) # 画像の距離
itemfiles = {}
if logger.isEnabledFor(logging.DEBUG):
hex = ""
for h in hash_item[0]:
hex = hex + "{:02x}".format(h)
# 既存のアイテムとの距離を比較
for i in dist_dic.keys():
d = hasher.compare(hash_item, hex2hash(i))
if d <= threshold:
itemfiles[dist_dic[i]] = d
if len(itemfiles) > 0:
itemfiles = sorted(itemfiles.items(), key=lambda x: x[1])
logger.debug("itemfiles: %s", itemfiles)
item = next(iter(itemfiles))
return item[0]
return ""
def classify_ce(self, img):
itemid = self.classify_ce_sub(img, compute_hash_ce, dist_ce, 12)
if itemid == "":
logger.debug("use narrow image")
itemid = self.classify_ce_sub(
img, compute_hash_ce_narrow, dist_ce_narrow, 15
)
return itemid
def classify_point(self, img):
"""
imgとの距離を比較して近いアイテムを求める
"""
hash_item = compute_hash(img) # 画像の距離
itemfiles = {}
if logger.isEnabledFor(logging.DEBUG):
hex = ""
for h in hash_item[0]:
hex = hex + "{:02x}".format(h)
logger.debug("phash: %s", hex)
# 既存のアイテムとの距離を比較
for i in dist_point.keys():
itemid = dist_point[i]
item_bg = item_background[itemid]
d = hasher.compare(hash_item, hex2hash(i))
if d <= 16 and item_bg == self.background:
itemfiles[itemid] = d
if len(itemfiles) > 0:
itemfiles = sorted(itemfiles.items(), key=lambda x: x[1])
item = next(iter(itemfiles))
return item[0]
return ""
def classify_exp(self, img):
hash_item = self.compute_exp_rarity_hash(img) # 画像の距離
exps = {}
for i in dist_exp_rarity.keys():
dt = hasher.compare(hash_item, hex2hash(i))
if dt <= 15: # IMG_1833で11 IMG_1837で15
exps[i] = dt
exps = sorted(exps.items(), key=lambda x: x[1])
if len(exps) > 0:
exp = next(iter(exps))
hash_exp_class = self.compute_exp_class_hash(img)
exp_classes = {}
for j in dist_exp_class.keys():
dtc = hasher.compare(hash_exp_class, hex2hash(j))
exp_classes[j] = dtc
exp_classes = sorted(exp_classes.items(), key=lambda x: x[1])
exp_class = next(iter(exp_classes))
return int(str(dist_exp_class[exp_class[0]])[:4]
+ str(dist_exp_rarity[exp[0]])[4] + "00")
return ""
def make_new_file(self, img, search_dir, dist_dic, dropPriority, category):
"""
ファイル名候補を探す
"""
i_dic = {"Item": "item", "Craft Essence": "ce", "Point": "point"}
initial = i_dic[category]
for i in range(999):
itemfile = search_dir / (initial + '{:0=3}'.format(i + 1) + '.png')
if itemfile.is_file():
continue
else:
cv2.imwrite(itemfile.as_posix(), img)
# id 候補を決める
for j in range(99999):
id = j + ID_START
if id in item_name.keys():
continue
break
if category == "Craft Essence":
hash = compute_hash_ce(img)
else:
hash = compute_hash(img)
hash_hex = ""
for h in hash[0]:
hash_hex = hash_hex + "{:02x}".format(h)
dist_dic[hash_hex] = id
if category == "Craft Essence":
hash_narrow = compute_hash_ce_narrow(img)
hash_hex_narrow = ""
for h in hash_narrow[0]:
hash_narrow = hash_narrow + "{:02x}".format(h)
dist_ce_narrow[hash_hex_narrow] = id
item_name[id] = itemfile.stem
item_background[id] = classify_background(img)
item_dropPriority[id] = dropPriority
item_type[id] = category
break
return id
def classify_category(self, svm_card):
"""
カード判別器
"""
"""
カード判別器
この場合は画像全域のハッシュをとる
"""
# Hog特徴のパラメータ
win_size = (120, 60)
block_size = (16, 16)
block_stride = (4, 4)
cell_size = (4, 4)
bins = 9
test = []
carddic = {0: 'Quest Reward', 1: 'Item', 2: 'Point',
3: 'Craft Essence', 4: 'Exp. UP', 99: ""}
tmpimg = self.img_rgb[int(189/206*self.height):
int(201/206*self.height),
int(78/188*self.width):
int(115/188*self.width)]
tmpimg = cv2.resize(tmpimg, (win_size))
hog = cv2.HOGDescriptor(win_size, block_size, block_stride,
cell_size, bins)
test.append(hog.compute(tmpimg)) # 特徴量の格納
test = np.array(test)
pred = svm_card.predict(test)
return carddic[pred[1][0][0]]
def classify_card(self, img, currnet_dropPriority):
"""
アイテム判別器
"""
if self.category == "Point":
id = self.classify_point(img)
if id == "":
id = self.make_new_file(img, Point_dir, dist_point,
PRIORITY_POINT, self.category)
return id
elif self.category == "Quest Reward":
return 5
elif self.category == "Craft Essence":
id = self.classify_ce(img)
if id == "":
id = self.make_new_file(img, CE_dir, dist_ce,
PRIORITY_CE, self.category)
return id
elif self.category == "Exp. UP":
return self.classify_exp(img)
elif self.category == "Item":
id = self.classify_item(img, currnet_dropPriority)
if id == "":
id = self.make_new_file(img, Item_dir, dist_item,
PRIORITY_ITEM, self.category)
else:
# ここで category が判別できないのは三行目かつ
# スクロール位置の関係で下部表示が消えている場合
id = self.classify_item(img, currnet_dropPriority)
if id != "":
return id
id = self.classify_point(img)
if id != "":
return id
id = self.classify_ce(img)
if id != "":
return id
id = self.classify_exp(img)
if id != "":
return id
if id == "":
id = self.make_new_file(img, Item_dir, dist_item,
PRIORITY_ITEM, "Item")
return id
def compute_exp_rarity_hash(self, img_rgb):
"""
種火レアリティ判別器
この場合は画像全域のハッシュをとる
"""
img = img_rgb[int(53/189*self.height):int(136/189*self.height),
int(37/206*self.width):int(149/206*self.width)]
return hasher.compute(img)
def compute_exp_class_hash(self, img_rgb):
"""
種火クラス判別器
左上のクラスマークぎりぎりのハッシュを取る
記述した比率はiPhone6S画像の実測値
"""
img = img_rgb[int((5+9)/135*self.height):int((30+2)/135*self.height),
int(5/135*self.width):int((30+6)/135*self.width)]
return hasher.compute(img)
def compute_gem_hash(self, img_rgb):
"""
スキル石クラス判別器
中央のクラスマークぎりぎりのハッシュを取る
記述した比率はiPhone6S画像の実測値
"""
height, width = img_rgb.shape[:2]
img = img_rgb[int((145-16-60*0.8)/2/145*height)+2:
int((145-16+60*0.8)/2/145*height)+2,
int((132-52*0.8)/2/132*width):
int((132+52*0.8)/2/132*width)]
return hasher.compute(img)
def classify_background(img_rgb):
"""
背景判別
"""
_, width = img_rgb.shape[:2]
img = img_rgb[30:119, width - 25:width - 7]
target_hist = img_hist(img)
bg_score = []
score_z = calc_hist_score(target_hist, hist_zero)
bg_score.append({"background": "zero", "dist": score_z})
score_g = calc_hist_score(target_hist, hist_gold)
bg_score.append({"background": "gold", "dist": score_g})
score_s = calc_hist_score(target_hist, hist_silver)
bg_score.append({"background": "silver", "dist": score_s})
score_b = calc_hist_score(target_hist, hist_bronze)
bg_score.append({"background": "bronze", "dist": score_b})
bg_score = sorted(bg_score, key=lambda x: x['dist'])
# logger.debug("background dist: %s", bg_score)
return (bg_score[0]["background"])
def compute_hash(img_rgb):
"""
判別器
この判別器は下部のドロップ数を除いた部分を比較するもの
記述した比率はiPhone6S画像の実測値
"""
height, width = img_rgb.shape[:2]
img = img_rgb[int(22/135*height):
int(77/135*height),
int(23/135*width):
int(112/135*width)]
return hasher.compute(img)
def compute_hash_ce(img_rgb):
"""
判別器
この判別器は下部のドロップ数を除いた部分を比較するもの
記述した比率はiPpd2018画像の実測値
"""
img = img_rgb[12:176, 9:182]
return hasher.compute(img)
def compute_hash_ce_narrow(img_rgb):
"""
CE Identifier for scrolled down screenshot
"""
height, width = img_rgb.shape[:2]
img = img_rgb[int(30/206*height):int(155/206*height),
int(5/188*width):int(183/188*width)]
return hasher.compute(img)
def search_file(search_dir, dist_dic, dropPriority, category):
"""
Item, Craft Essence, Pointの各ファイルを探す
"""
files = search_dir.glob('**/*.png')
for fname in files:
img = imread(fname)
# id 候補を決める
# 既存のデータがあったらそれを使用
if fname.stem in item_name.values():
id = [k for k, v in item_name.items() if v == fname.stem][0]
elif fname.stem in item_shortname.values():
id = [k for k, v in item_shortname.items() if v == fname.stem][0]
else:
for j in range(99999):
id = j + ID_START
if id in item_name.keys():
continue
break
# priotiry は固定
item_name[id] = fname.stem
item_dropPriority[id] = dropPriority
item_type[id] = category
if category == "Craft Essence":
hash = compute_hash_ce(img)
else:
hash = compute_hash(img)
hash_hex = ""
for h in hash[0]:
hash_hex = hash_hex + "{:02x}".format(h)
dist_dic[hash_hex] = id
if category == "Item" or category == "Point":
item_background[id] = classify_background(img)
if category == "Craft Essence":
hash_narrow = compute_hash_ce_narrow(img)
hash_hex_narrow = ""
for h in hash_narrow[0]:
hash_hex_narrow = hash_hex_narrow + "{:02x}".format(h)
dist_ce_narrow[hash_hex_narrow] = id
def calc_hist_score(hist1, hist2):
scores = []
for channel1, channel2 in zip(hist1, hist2):
score = cv2.compareHist(channel1, channel2, cv2.HISTCMP_BHATTACHARYYA)
scores.append(score)
return np.mean(scores)
def img_hist(src_img):
img = cv2.cvtColor(src_img, cv2.COLOR_BGR2HSV)
hist1 = cv2.calcHist([img], [0], None, [256], [0, 256])
hist2 = cv2.calcHist([img], [1], None, [256], [0, 256])
hist3 = cv2.calcHist([img], [2], None, [256], [0, 256])
return hist1, hist2, hist3
def calc_dist_local():
"""
既所持のアイテム画像の距離(一次元配列)の辞書を作成して保持
"""
search_file(Item_dir, dist_item, PRIORITY_ITEM, "Item")
search_file(CE_dir, dist_ce, PRIORITY_CE, "Craft Essence")
search_file(Point_dir, dist_point, PRIORITY_POINT, "Point")
def hex2hash(hexstr):
hashlist = []
for i in range(8):
hashlist.append(int('0x' + hexstr[i*2:i*2+2], 0))
return np.array([hashlist], dtype='uint8')
def out_name(args, id):
if args.lang == "eng":
if id in item_name_eng.keys():
return item_name_eng[id]
if id in item_shortname.keys():
name = item_shortname[id]
else:
name = item_name[id]
return name
def imread(filename, flags=cv2.IMREAD_COLOR, dtype=np.uint8):
"""
OpenCVのimreadが日本語ファイル名が読めない対策
"""
try:
n = np.fromfile(filename, dtype)
img = cv2.imdecode(n, flags)
return img
except Exception as e:
logger.exception(e)
return None
def get_exif(img):
exif = img._getexif()
try:
for id, val in exif.items():
tg = TAGS.get(id, id)
if tg == "DateTimeOriginal":
return datetime.datetime.strptime(val, '%Y:%m:%d %H:%M:%S')
except AttributeError:
return "NON"
return "NON"
def get_output(filenames, args):
"""
出力内容を作成
"""
calc_dist_local()
if train_item.exists() is False:
logger.critical("item.xml is not found")
logger.critical("Try to run 'python makeitem.py'")
sys.exit(1)
if train_chest.exists() is False:
logger.critical("chest.xml is not found")
logger.critical("Try to run 'python makechest.py'")
sys.exit(1)
if train_dcnt.exists() is False:
logger.critical("dcnt.xml is not found")
logger.critical("Try to run 'python makedcnt.py'")
sys.exit(1)
if train_card.exists() is False:
logger.critical("card.xml is not found")
logger.critical("Try to run 'python makecard.py'")
sys.exit(1)
svm = cv2.ml.SVM_load(str(train_item))
svm_chest = cv2.ml.SVM_load(str(train_chest))
svm_dcnt = cv2.ml.SVM_load(str(train_dcnt))
svm_card = cv2.ml.SVM_load(str(train_card))
fileoutput = [] # 出力
output = {}
prev_pages = 0
prev_pagenum = 0
prev_total_qp = QP_UNKNOWN
prev_itemlist = []
prev_datetime = datetime.datetime(year=2015, month=7, day=30, hour=0)
prev_qp_gained = 0
prev_chestnum = 0
all_list = []
for filename in filenames:
exLogger = CustomAdapter(logger, {"target": filename})
logger.debug("filename: %s", filename)
f = Path(filename)
if f.exists() is False:
output = {'filename': str(filename) + ': not found'}
all_list.append([])
elif f.is_dir(): # for ZIP file from MacOS
continue
elif f.suffix.upper() not in ['.PNG', '.JPG', '.JPEG']:
output = {'filename': str(filename) + ': Not Supported'}
all_list.append([])
else:
img_rgb = imread(filename)
fileextention = Path(filename).suffix
try:
sc = ScreenShot(args, img_rgb,
svm, svm_chest, svm_dcnt, svm_card,
fileextention, exLogger)
if sc.itemlist[0]["id"] != ID_REWARD_QP and sc.pagenum == 1:
logger.warning(
"Page count recognition is failing: %s",
filename
)
# ドロップ内容が同じで下記のとき、重複除外
# QPカンストじゃない時、QPが前と一緒
# QPカンストの時、Exif内のファイル作成時間が15秒未満
pilimg = Image.open(filename)
dt = get_exif(pilimg)
if dt == "NON" or prev_datetime == "NON":
td = datetime.timedelta(days=1)
else:
td = dt - prev_datetime
if sc.pages - sc.pagenum == 0:
sc.itemlist = sc.itemlist[14-(sc.lines+2) % 3*7:]
if prev_itemlist == sc.itemlist:
if (sc.total_qp != -1 and sc.total_qp != 2000000000
and sc.total_qp == prev_total_qp) \
or ((sc.total_qp == -1 or sc.total_qp == 2000000000)
and td.total_seconds() < args.timeout):
logger.debug("args.timeout: %s", args.timeout)
logger.debug("filename: %s", filename)
logger.debug("prev_itemlist: %s", prev_itemlist)
logger.debug("sc.itemlist: %s", sc.itemlist)
logger.debug("sc.total_qp: %s", sc.total_qp)
logger.debug("prev_total_qp: %s", prev_total_qp)
logger.debug("datetime: %s", dt)
logger.debug("prev_datetime: %s", prev_datetime)
logger.debug("td.total_second: %s", td.total_seconds())
fileoutput.append(
{'filename': str(filename) + ': duplicate'})
all_list.append([])
continue
# 2頁目以前のスクショが無い場合に migging と出力
# 1. 前頁が最終頁じゃない&前頁の続き頁数じゃない
# または前頁が最終頁なのに1頁じゃない
# 2. 前頁の続き頁なのに獲得QPが違う
if (
prev_pages - prev_pagenum > 0
and sc.pagenum - prev_pagenum != 1) \
or (prev_pages - prev_pagenum == 0
and sc.pagenum != 1) \
or sc.pagenum != 1 \
and sc.pagenum - prev_pagenum == 1 \
and (
prev_qp_gained != sc.qp_gained
):
logger.debug("prev_pages: %s", prev_pages)
logger.debug("prev_pagenum: %s", prev_pagenum)
logger.debug("sc.pagenum: %s", sc.pagenum)
logger.debug("prev_qp_gained: %s", prev_qp_gained)
logger.debug("sc.qp_gained: %s", sc.qp_gained)
logger.debug("prev_chestnum: %s", prev_chestnum)
logger.debug("sc.chestnum: %s", sc.chestnum)
fileoutput.append({'filename': 'missing'})
all_list.append([])
all_list.append(sc.itemlist)
prev_pages = sc.pages
prev_pagenum = sc.pagenum
prev_total_qp = sc.total_qp
prev_itemlist = sc.itemlist
prev_datetime = dt
prev_qp_gained = sc.qp_gained
prev_chestnum = sc.chestnum
sumdrop = len([d for d in sc.itemlist
if d["id"] != ID_REWARD_QP])
if args.lang == "jpn":
drop_count = "ドロ数"
item_count = "アイテム数"
else:
drop_count = "item_count"
item_count = "item_count"
output = {'filename': str(filename), drop_count: sc.chestnum, item_count: sumdrop}
except Exception as e:
logger.error(filename)
logger.error(e, exc_info=True)
output = ({'filename': str(filename) + ': not valid'})
all_list.append([])
fileoutput.append(output)
return fileoutput, all_list
def load_svms():
svm = cv2.ml.SVM_load(str(train_item))
svm_chest = cv2.ml.SVM_load(str(train_chest))
svm_dcnt = cv2.ml.SVM_load(str(train_dcnt))
svm_card = cv2.ml.SVM_load(str(train_card))
return (svm, svm_chest, svm_dcnt, svm_card)
def parse_img(
program_args,
svm,
svm_chest,
svm_dcnt,
svm_card,
file_path,
prev_pages=0,
prev_pagenum=0,
prev_total_qp=QP_UNKNOWN,
prev_gained_qp=QP_UNKNOWN,
prev_itemlist=[],
prev_datetime=datetime.datetime(year=2015, month=7, day=30, hour=0)):
parsed_img_data = {"status": "Incomplete"}
logger.debug("filename: %s", file_path)
file_loc = Path(file_path).resolve()
parsed_img_data["image_path"] = str(file_loc)
if not file_loc.exists():
# TODO: is this needed?
parsed_img_data["status"] = "File not found"
return parsed_img_data
img_rgb = imread(file_path)
file_extention = file_loc.suffix
exLogger = CustomAdapter(logger, {"target": file_loc.name})
try:
screenshot = ScreenShot(
program_args, img_rgb, svm, svm_chest, svm_dcnt, svm_card, file_extention, exLogger)
# If the previous image indicated more coming, check whether this is the fated one.
if (prev_pages - prev_pagenum > 0 and screenshot.pagenum - prev_pagenum != 1) \
or (prev_pages - prev_pagenum == 0 and screenshot.pagenum != 1):
parsed_img_data["status"] = "Missing page before this"
# Detect whether image is a duplicate
# Image is a candidate duplicate if drops and gained QP match previous image.
# Duplicate is confirmed if:
# - QP is not capped and drops are the same as in the previous image
# - QP is capped and previous image was taken within 15sec
# TODO: is this needed?
pilimg = Image.open(file_path)
date_time = get_exif(pilimg)
if date_time == "NON" or prev_datetime == "NON":
time_delta = datetime.timedelta(days=1)
else:
time_delta = date_time - prev_datetime
if prev_itemlist == screenshot.itemlist and prev_gained_qp == screenshot.qp_gained:
if (screenshot.total_qp != 999999999 and screenshot.total_qp == prev_total_qp) \
or (screenshot.total_qp == 999999999 and time_delta.total_seconds() < args.timeout):
logger.debug("args.timeout: {}".format(args.timeout))
logger.debug("filename: {}".format(file_path))
logger.debug("prev_itemlist: {}".format(prev_itemlist))
logger.debug("screenshot.itemlist: {}".format(
screenshot.itemlist))
logger.debug("screenshot.total_qp: {}".format(
screenshot.total_qp))
logger.debug("prev_total_qp: {}".format(prev_total_qp))
logger.debug("datetime: {}".format(date_time))
logger.debug("prev_datetime: {}".format(prev_datetime))
logger.debug("td.total_second: {}".format(
time_delta.total_seconds()))
parsed_img_data["status"] = "Duplicate file"
return parsed_img_data
# Prep next iter
prev_pages = screenshot.pages
prev_pagenum = screenshot.pagenum
prev_total_qp = screenshot.total_qp
prev_gained_qp = screenshot.qp_gained
prev_itemlist = screenshot.itemlist
prev_datetime = date_time
# Gather data
parsed_img_data["qp_total"] = screenshot.total_qp
parsed_img_data["qp_gained"] = screenshot.qp_gained
parsed_img_data["scroll_position"] = screenshot.scroll_position
parsed_img_data["drop_count"] = screenshot.chestnum
parsed_img_data["drops_found"] = len(screenshot.itemlist)
parsed_img_data["drops"] = screenshot.itemlist
parsed_img_data["status"] = "OK" if parsed_img_data["status"] == "Incomplete" else parsed_img_data["status"]
return parsed_img_data
except Exception as e:
logger.error("Error during parsing of {}\n{}\n".format(
file_path, e), exc_info=True)
parsed_img_data["status"] = "Invalid file"
return parsed_img_data
def move_file_to_out_dir(src_file_path, out_dir):
if out_dir is not None:
if not os.path.exists(out_dir):
os.makedirs(out_dir)
src_file_path = Path(src_file_path)
if not src_file_path.exists():
print("Cannot move {}. It does not exist.".format(src_file_path))
exit(1)
dst_file_path = "{}/{}".format(out_dir, src_file_path.name)
os.rename(src_file_path, dst_file_path)
return dst_file_path
return src_file_path
def check_svms_trained():
if train_item.exists() is False:
logger.critical("item.xml is not found")
logger.critical("Try to run 'python makeitem.py'")
sys.exit(1)
if train_chest.exists() is False:
logger.critical("chest.xml is not found")
logger.critical("Try to run 'python makechest.py'")
sys.exit(1)
if train_dcnt.exists() is False:
logger.critical("dcnt.xml is not found")
logger.critical("Try to run 'python makedcnt.py'")
sys.exit(1)
if train_card.exists() is False:
logger.critical("card.xml is not found")
logger.critical("Try to run 'python makecard.py'")
sys.exit(1)
def parse_into_json(input_file_paths, args):
"""
The version of output gathering used by AtlasAcademy. Made to resemble capy's output.
"""
calc_dist_local()
check_svms_trained()
(svm, svm_chest, svm_dcnt, svm_card) = load_svms()
prev_pages = 0
prev_pagenum = 0
prev_total_qp = QP_UNKNOWN
prev_gained_qp = QP_UNKNOWN
prev_itemlist = []
prev_datetime = datetime.datetime(year=2015, month=7, day=30, hour=0)
all_parsed_output = []
for file_path in input_file_paths:
file_path = move_file_to_out_dir(file_path, args.out_folder)
all_parsed_output.append(parse_img(
args,
svm,
svm_chest,
svm_dcnt,
svm_card,
file_path,
prev_pages,
prev_pagenum,
prev_total_qp,
prev_gained_qp,
prev_itemlist,
prev_datetime))
return all_parsed_output
def __parse_into_json_process(input_queue, args):
(svm, svm_chest, svm_dcnt, svm_card) = load_svms()
global watcher_running
while watcher_running or not input_queue.empty():
input_file_path = input_queue.get()
# Detection of missing screenshots/pages (e.g. scrolled down image with no previous
# image to go along with it), is dissabled with `prev_pages=-1`. This is because
# the technique depends on having the images sorted in chronological order. Sorting
# files and processing them in order is not possible in a multiprocess environment.
parsed_output = parse_img(
args,
svm,
svm_chest,
svm_dcnt,
svm_card,
input_file_path,
prev_pages=-1)
output_json([parsed_output], args.out_folder)
def __signal_handling(*_):
"""
Taken from capy-drop-parser
"""
global watcher_running
if not watcher_running:
sys.exit(1)
watcher_running = False
print(
"Notice: app may take up to polling frequency time and however long it takes to finish the queue before exiting."
)
def watch_parse_output_into_json(args):
"""
Continuously watch the given input directory for new files.
Processes any new images by parsing them, moving them to output dir, and writing parsed json to
output dir.
Works with a producer/consumer multiprocessing approach. This function watches and
fills the queue, while spawned processes use `__parse_into_json_process` to consume the
items.
"""
calc_dist_local()
check_svms_trained()
signal.signal(signal.SIGINT, __signal_handling)
# We estimate roughly 2secs per image parsing. Queue can hold as many images as can be
# processed by the given amount of processes in the given amount of poll time.
input_queue = multiprocessing.Queue(maxsize=int(
args.num_processes * args.polling_frequency / 2))
pool = multiprocessing.Pool(
args.num_processes, initializer=__parse_into_json_process, initargs=(input_queue, args))
global watcher_running
while watcher_running:
for f in Path(args.folder).iterdir():
if not f.is_file():
continue
file_path = move_file_to_out_dir(f, args.out_folder)
input_queue.put(file_path) # blocks when queue is full
time.sleep(int(args.polling_frequency))
input_queue.close()
input_queue.join_thread()
pool.close()
pool.join()
def sort_files(files, ordering):
if ordering == Ordering.NOTSPECIFIED:
return files
elif ordering == Ordering.FILENAME:
return sorted(files)
elif ordering == Ordering.TIMESTAMP:
return sorted(files, key=lambda f: Path(f).stat().st_ctime)
raise ValueError(f'Unsupported ordering: {ordering}')
def change_value(args, line):
if args.lang == 'jpn':
line = re.sub('000000$', "百万", str(line))
line = re.sub('0000$', "万", str(line))
line = re.sub('000$', "千", str(line))
else:
line = re.sub('000000$', "M", str(line))
line = re.sub('000$', "K", str(line))
return line
def make_quest_output(quest):
output = ""
if quest != "":
quest_list = [q["name"] for q in freequest
if q["place"] == quest["place"]]
if math.floor(quest["id"]/100)*100 == ID_NORTH_AMERICA:
output = quest["place"] + " " + quest["name"]
elif math.floor(quest["id"]/100)*100 == ID_SYURENJYO:
output = quest["chapter"] + " " + quest["place"]
elif math.floor(quest["id"]/100000)*100000 == ID_EVNET:
output = quest["shortname"]
else:
# クエストが0番目のときは場所を出力、それ以外はクエスト名を出力
if quest_list.index(quest["name"]) == 0:
output = quest["chapter"] + " " + quest["place"]
else:
output = quest["chapter"] + " " + quest["name"]
return output
UNKNOWN = -1
OTHER = 0
NOVICE = 1
INTERMEDIATE = 2
ADVANCED = 3
EXPERT = 4
MASTER = 5
def tv_quest_type(item_list):
quest_type = UNKNOWN
for item in item_list:
if item["id"] == ID_REWARD_QP:
if quest_type != UNKNOWN:
quest_type = OTHER
break
if item["dropnum"] == 1400:
quest_type = NOVICE
elif item["dropnum"] == 2900:
quest_type = INTERMEDIATE
elif item["dropnum"] == 4400:
quest_type = ADVANCED
elif item["dropnum"] == 6400:
quest_type = EXPERT
elif item["dropnum"] == 7400:
quest_type = MASTER
else:
quest_type = OTHER
break
return quest_type
def deside_tresure_valut_quest(item_list):
quest_type = tv_quest_type(item_list)
if quest_type in [UNKNOWN, OTHER]:
quest_candidate = ""
return quest_candidate
item_set = set()
for item in item_list:
if item["id"] == ID_REWARD_QP:
continue
elif item["id"] != ID_QP:
quest_candidate = ""
break
else:
item_set.add(item["dropnum"])
if quest_type == NOVICE and item_set == {10000, 15000, 30000, 45000}:
quest_candidate = {
"id": 94061636,
"name": "宝物庫の扉を開け 初級",
"place": "",
"chapter": "",
"qp": 1400,
"shortname": "宝物庫 初級",
}
elif quest_type == INTERMEDIATE and item_set == {10000, 15000, 30000, 45000, 90000, 135000}:
quest_candidate = {
"id": 94061637,
"name": "宝物庫の扉を開け 中級",
"place": "",
"chapter": "",
"qp": 2900,
"shortname": "宝物庫 中級",
}
elif quest_type == ADVANCED and item_set == {30000, 45000, 90000, 135000, 270000, 405000}:
quest_candidate = {
"id": 94061638,
"name": "宝物庫の扉を開け 上級",
"place": "",
"chapter": "",
"qp": 4400,
"shortname": "宝物庫 上級",
}
elif quest_type == EXPERT and item_set == {90000, 135000, 270000, 405000}:
quest_candidate = {
"id": 94061639,
"name": "宝物庫の扉を開け 超級",
"place": "",
"chapter": "",
"qp": 7400,
"shortname": "宝物庫 超級",
}
elif quest_type == MASTER and item_set == {270000, 405000, 1500000}:
quest_candidate = {
"id": 94061640,
"name": "宝物庫の扉を開け 極級",
"place": "",
"chapter": "",
"qp": 7400,
"shortname": "宝物庫 極級",
}
else:
quest_candidate = ""
return quest_candidate
def deside_quest(item_list):
quest_name = deside_tresure_valut_quest(item_list)
if quest_name != "":
return quest_name
item_set = set()
for item in item_list:
if item["id"] == ID_REWARD_QP:
item_set.add("QP(+" + str(item["dropnum"]) + ")")
elif item["id"] == 1 \
or item["category"] == "Craft Essence" \
or (9700 <= math.floor(item["id"]/1000) <= 9707
and str(item["id"])[4] not in ["4", "5"]):
continue
else:
item_set.add(item["name"])
quest_candidate = ""
for quest in reversed(freequest):
dropset = {i["name"] for i in quest["drop"]
if i["type"] != "Craft Essence"}
dropset.add("QP(+" + str(quest["qp"]) + ")")
if dropset == item_set:
quest_candidate = quest
break
return quest_candidate
def quest_name_recognition(item_list):
"""アイテムが全て埋まっていない場合のクエスト名の判別
Args:
item_list ([type]): [description]
Returns:
[type]: [description]
"""
reward_qp = 0
item_set = set()
for item in item_list:
if item["id"] == ID_REWARD_QP:
item_set.add("QP(+" + str(item["dropnum"]) + ")")
reward_qp = item["dropnum"]
elif item["id"] == 1 \
or item["category"] == "Craft Essence" \
or (9700 <= math.floor(item["id"]/1000) <= 9707
and str(item["id"])[4] not in ["4", "5"]):
continue
else:
item_set.add(item["name"])
if reward_qp == 0:
return "", []
quest_candidate = []
# 報酬QPが同じクエストの一覧を作る
for quest in reversed(freequest):
if quest["qp"] == reward_qp:
quest_candidate.append(quest)
# クエスト一覧に含まれるかチェック
# 含まれるクエストが一つだったら出力
quest_candidate2 = []
missing_items = []
for quest in quest_candidate:
dropset = {i["name"] for i in quest["drop"]
if i["type"] != "Craft Essence"}
dropset.add("QP(+" + str(quest["qp"]) + ")")
diff = item_set - dropset
if len(diff) == 0:
tmp_items = []
diff2 = dropset - item_set
quest_candidate2.append(quest)
for item in quest["drop"]:
if item["name"] in diff2:
item["dropnum"] = 0
item["category"] = "Item"
tmp_items.append(item)
missing_items.append(tmp_items)
if len(quest_candidate2) == 1:
return quest_candidate2[0], missing_items[0]
else:
return "", []
def make_csv_header(args, item_list):
"""
CSVのヘッダ情報を作成
礼装のドロップが無いかつ恒常以外のアイテムが有るとき礼装0をつける
"""
if args.lang == 'jpn':
drop_count = 'ドロ数'
item_count = 'アイテム数'
ce_str = '礼装'
else:
drop_count = 'drop_count'
item_count = 'item_count'
ce_str = 'CE'
if item_list == [[]]:
return ['filename', drop_count], False, ""
# リストを一次元に
flat_list = list(itertools.chain.from_iterable(item_list))
# 余計な要素を除く
short_list = [{"id": a["id"], "name": a["name"], "category": a["category"],
"dropPriority": a["dropPriority"], "dropnum": a["dropnum"]}
for a in flat_list]
# 概念礼装のカテゴリのアイテムが無くかつイベントアイテム(>ID_EXM_MAX)がある
if args.lang == 'jpn':
no_ce_exp_list = [
k for k in flat_list
if not k["name"].startswith("概念礼装EXPカード:")
]
else:
no_ce_exp_list = [
k for k in flat_list
if not k["name"].startswith("CE EXP Card:")
]
ce0_flag = ("Craft Essence"
not in [
d.get('category') for d in no_ce_exp_list
]
) and (
max([d.get("id") for d in flat_list]) > ID_EXP_MAX
)
if ce0_flag:
short_list.append({"id": 99999990, "name": ce_str,
"category": "Craft Essence",
"dropPriority": 9005, "dropnum": 0})
# 重複する要素を除く
unique_list = list(map(json.loads, set(map(json.dumps, short_list))))
# クエスト名判定
quest = deside_quest(unique_list)
if quest == "":
quest, items2 = quest_name_recognition(unique_list)
unique_list.extend(items2)
quest_output = make_quest_output(quest)
# ソート
new_list = sorted(sorted(sorted(unique_list, key=itemgetter('dropnum')),
key=itemgetter('id'), reverse=True),
key=itemgetter('dropPriority'), reverse=True)
header = []
for nlist in new_list:
if nlist['category'] in ['Quest Reward', 'Point'] \
or nlist["name"] == "QP":
tmp = out_name(args, nlist['id']) \
+ "(+" + change_value(args, nlist["dropnum"]) + ")"
elif nlist["dropnum"] > 1:
tmp = out_name(args, nlist['id']) \
+ "(x" + change_value(args, nlist["dropnum"]) + ")"
elif nlist["name"] == ce_str:
tmp = ce_str
else:
tmp = out_name(args, nlist['id'])
header.append(tmp)
return ['filename', drop_count, item_count] + header, ce0_flag, quest_output
def make_csv_data(args, sc_list, ce0_flag):
if sc_list == []:
return [{}], [{}]
csv_data = []
allitem = []
for sc in sc_list:
tmp = []
for item in sc:
if item['category'] in ['Quest Reward', 'Point'] \
or item["name"] == "QP":
tmp.append(out_name(args, item['id'])
+ "(+" + change_value(args, item["dropnum"]) + ")")
elif item["dropnum"] > 1:
tmp.append(out_name(args, item['id'])
+ "(x" + change_value(args, item["dropnum"]) + ")")
else:
tmp.append(out_name(args, item['id']))
allitem = allitem + tmp
csv_data.append(dict(Counter(tmp)))
csv_sum = dict(Counter(allitem))
if ce0_flag:
if args.lang == 'jpn':
ce_str = '礼装'
else:
ce_str = 'CE'
csv_sum.update({ce_str: 0})
return csv_sum, csv_data
def output_json(parsed_output, out_folder):
if out_folder is None:
sys.stdout.buffer.write(json.dumps(
parsed_output, ensure_ascii=False).encode('utf8'))
else:
if not os.path.exists(out_folder):
os.makedirs(out_folder)
for parsed_file in parsed_output:
title = Path(parsed_file["image_path"]).stem
with open(Path("{}/{}.json".format(out_folder, title)), "w", encoding="utf-8") as f:
json.dump(parsed_file, f, indent=4, ensure_ascii=False)
if __name__ == '__main__':
# オプションの解析
parser = argparse.ArgumentParser(
description='Image Parse for FGO Battle Results'
)
# 3. parser.add_argumentで受け取る引数を追加していく
parser.add_argument(
'-i', '--filenames', help='image file to parse', nargs='+') # 必須の引数を追加
parser.add_argument('--lang', default=DEFAULT_ITEM_LANG,
choices=('jpn', 'eng'),
help='Language to be used for output: Default '
+ DEFAULT_ITEM_LANG)
parser.add_argument('-f', '--folder', help='Specify by folder')
parser.add_argument('-o', '--out_folder',
help='folder to write parsed data to. If specified, parsed images will also be moved to here. Else, output will simply be written to stdout')
parser.add_argument('--ordering',
help='The order in which files are processed ',
type=Ordering,
choices=list(Ordering), default=Ordering.NOTSPECIFIED)
text_timeout = 'Duplicate check interval at QP MAX (sec): Default '
parser.add_argument('-t', '--timeout', type=int, default=TIMEOUT,
help=text_timeout + str(TIMEOUT) + ' sec')
parser.add_argument('--version', action='version',
version=PROGNAME + " " + VERSION)
parser.add_argument('-l', '--loglevel',
choices=('debug', 'info'), default='info')
subparsers = parser.add_subparsers(
title='subcommands', description='{subcommand} --help: show help message for the subcommand',)
watcher_parser = subparsers.add_parser(
'watch', help='continuously watch the folder specified by [-f FOLDER]')
watcher_parser.add_argument(
"-j",
"--num_processes",
required=False,
default=DEFAULT_AMT_PROCESSES,
type=int,
help="number of processes to allocate in the process pool. Default: {}".format(
DEFAULT_AMT_PROCESSES),
)
watcher_parser.add_argument(
"-p",
"--polling_frequency",
required=False,
default=DEFAULT_POLL_FREQ,
type=int,
help="how often to check for new images (in seconds). Default: {}s".format(
DEFAULT_POLL_FREQ),
)
args = parser.parse_args() # 引数を解析
lformat = '%(name)s <%(filename)s-L%(lineno)s> [%(levelname)s] %(message)s'
logging.basicConfig(
level=logging.INFO,
format=lformat,
)
logger.setLevel(args.loglevel.upper())
if args.out_folder is not None and not Path(args.out_folder):
print("{} is not a valid path".format(args.out_folder))
exit(1)
for ndir in [Item_dir, CE_dir, Point_dir]:
if not ndir.is_dir():
ndir.mkdir(parents=True)
# Attributes are only present if the watch subcommand has been invoked.
if hasattr(args, "num_processes") and hasattr(args, "polling_frequency"):
if args.folder is None or not Path(args.folder).exists():
print(
"The watch subcommands requires a valid input directory. Provide one with --folder.")
exit(1)
watch_parse_output_into_json(args)
else:
if args.filenames is None and args.folder is None:
print(
"No input files specified. Use --filenames or --folder to do so.")
exit(1)
# gather input image files
if args.folder:
inputs = [x for x in Path(args.folder).iterdir()]
else:
inputs = args.filenames
inputs = sort_files(inputs, args.ordering)
parsed_output = parse_into_json(inputs, args)
output_json(parsed_output, args.out_folder)
|
[
"argparse.ArgumentParser",
"cv2.approxPolyDP",
"cv2.arcLength",
"cv2.imdecode",
"numpy.ones",
"logging.getLogger",
"pageinfo.guess_lines",
"json.dumps",
"pathlib.Path",
"numpy.mean",
"cv2.rectangle",
"cv2.compareHist",
"cv2.HOGDescriptor",
"cv2.minMaxLoc",
"cv2.imshow",
"cv2.inRange",
"PIL.ExifTags.TAGS.get",
"cv2.matchTemplate",
"cv2.contourArea",
"cv2.img_hash.PHash_create",
"cv2.dilate",
"cv2.cvtColor",
"cv2.imwrite",
"os.path.exists",
"cv2.split",
"re.findall",
"datetime.timedelta",
"collections.Counter",
"cv2.boundingRect",
"cv2.destroyAllWindows",
"re.sub",
"cv2.resize",
"pageinfo.guess_pagenum",
"json.dump",
"cv2.bitwise_not",
"cv2.countNonZero",
"cv2.waitKey",
"cv2.calcHist",
"os.rename",
"re.match",
"datetime.datetime",
"datetime.datetime.strptime",
"multiprocessing.Pool",
"signal.signal",
"sys.exit",
"json.load",
"os.makedirs",
"logging.basicConfig",
"pageinfo.guess_pages",
"numpy.fromfile",
"cv2.threshold",
"math.floor",
"pytesseract.image_to_string",
"PIL.Image.open",
"pageinfo.guess_pageinfo",
"numpy.where",
"numpy.array",
"pageinfo.detect_qp_region",
"operator.itemgetter",
"itertools.chain.from_iterable",
"cv2.findContours"
] |
[((605, 632), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (622, 632), False, 'import logging\n'), ((1733, 1760), 'cv2.img_hash.PHash_create', 'cv2.img_hash.PHash_create', ([], {}), '()\n', (1758, 1760), False, 'import cv2\n'), ((1215, 1234), 'pathlib.Path', 'Path', (['"""item/equip/"""'], {}), "('item/equip/')\n", (1219, 1234), False, 'from pathlib import Path\n'), ((1254, 1270), 'pathlib.Path', 'Path', (['"""item/ce/"""'], {}), "('item/ce/')\n", (1258, 1270), False, 'from pathlib import Path\n'), ((1293, 1312), 'pathlib.Path', 'Path', (['"""item/point/"""'], {}), "('item/point/')\n", (1297, 1312), False, 'from pathlib import Path\n'), ((1336, 1352), 'pathlib.Path', 'Path', (['"""item.xml"""'], {}), "('item.xml')\n", (1340, 1352), False, 'from pathlib import Path\n'), ((1399, 1416), 'pathlib.Path', 'Path', (['"""chest.xml"""'], {}), "('chest.xml')\n", (1403, 1416), False, 'from pathlib import Path\n'), ((1464, 1480), 'pathlib.Path', 'Path', (['"""dcnt.xml"""'], {}), "('dcnt.xml')\n", (1468, 1480), False, 'from pathlib import Path\n'), ((1528, 1544), 'pathlib.Path', 'Path', (['"""card.xml"""'], {}), "('card.xml')\n", (1532, 1544), False, 'from pathlib import Path\n'), ((1580, 1612), 'pathlib.Path', 'Path', (['"""fgoscdata/hash_drop.json"""'], {}), "('fgoscdata/hash_drop.json')\n", (1584, 1612), False, 'from pathlib import Path\n'), ((1640, 1668), 'pathlib.Path', 'Path', (['"""fgoscdata/data/json/"""'], {}), "('fgoscdata/data/json/')\n", (1644, 1668), False, 'from pathlib import Path\n'), ((1691, 1722), 'pathlib.Path', 'Path', (['"""data/misc/items_img.png"""'], {}), "('data/misc/items_img.png')\n", (1695, 1722), False, 'from pathlib import Path\n'), ((2698, 2710), 'json.load', 'json.load', (['f'], {}), '(f)\n', (2707, 2710), False, 'import json\n'), ((5203, 5215), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5212, 5215), False, 'import json\n'), ((7779, 7816), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (7791, 7816), False, 'import cv2\n'), ((7939, 8001), 'cv2.threshold', 'cv2.threshold', (['img_gray', 'threshold', '(255)', 'cv2.THRESH_BINARY_INV'], {}), '(img_gray, threshold, 255, cv2.THRESH_BINARY_INV)\n', (7952, 8001), False, 'import cv2\n'), ((8124, 8183), 'cv2.findContours', 'cv2.findContours', (['inv', 'cv2.RETR_LIST', 'cv2.CHAIN_APPROX_NONE'], {}), '(inv, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n', (8140, 8183), False, 'import cv2\n'), ((8601, 8630), 'cv2.boundingRect', 'cv2.boundingRect', (['max_contour'], {}), '(max_contour)\n', (8617, 8630), False, 'import cv2\n'), ((9878, 9915), 'cv2.cvtColor', 'cv2.cvtColor', (['img', 'cv2.COLOR_BGR2GRAY'], {}), '(img, cv2.COLOR_BGR2GRAY)\n', (9890, 9915), False, 'import cv2\n'), ((10071, 10130), 'cv2.matchTemplate', 'cv2.matchTemplate', (['img_gray', 'template', 'cv2.TM_CCOEFF_NORMED'], {}), '(img_gray, template, cv2.TM_CCOEFF_NORMED)\n', (10088, 10130), False, 'import cv2\n'), ((10275, 10301), 'numpy.where', 'np.where', (['(res >= threshold)'], {}), '(res >= threshold)\n', (10283, 10301), True, 'import numpy as np\n'), ((86662, 86677), 'numpy.mean', 'np.mean', (['scores'], {}), '(scores)\n', (86669, 86677), True, 'import numpy as np\n'), ((86713, 86753), 'cv2.cvtColor', 'cv2.cvtColor', (['src_img', 'cv2.COLOR_BGR2HSV'], {}), '(src_img, cv2.COLOR_BGR2HSV)\n', (86725, 86753), False, 'import cv2\n'), ((86766, 86813), 'cv2.calcHist', 'cv2.calcHist', (['[img]', '[0]', 'None', '[256]', '[0, 256]'], {}), '([img], [0], None, [256], [0, 256])\n', (86778, 86813), False, 'import cv2\n'), ((86826, 86873), 'cv2.calcHist', 'cv2.calcHist', (['[img]', '[1]', 'None', '[256]', '[0, 256]'], {}), '([img], [1], None, [256], [0, 256])\n', (86838, 86873), False, 'import cv2\n'), ((86886, 86933), 'cv2.calcHist', 'cv2.calcHist', (['[img]', '[2]', 'None', '[256]', '[0, 256]'], {}), '([img], [2], None, [256], [0, 256])\n', (86898, 86933), False, 'import cv2\n'), ((87363, 87398), 'numpy.array', 'np.array', (['[hashlist]'], {'dtype': '"""uint8"""'}), "([hashlist], dtype='uint8')\n", (87371, 87398), True, 'import numpy as np\n'), ((89351, 89404), 'datetime.datetime', 'datetime.datetime', ([], {'year': '(2015)', 'month': '(7)', 'day': '(30)', 'hour': '(0)'}), '(year=2015, month=7, day=30, hour=0)\n', (89368, 89404), False, 'import datetime\n'), ((95037, 95090), 'datetime.datetime', 'datetime.datetime', ([], {'year': '(2015)', 'month': '(7)', 'day': '(30)', 'hour': '(0)'}), '(year=2015, month=7, day=30, hour=0)\n', (95054, 95090), False, 'import datetime\n'), ((100377, 100430), 'datetime.datetime', 'datetime.datetime', ([], {'year': '(2015)', 'month': '(7)', 'day': '(30)', 'hour': '(0)'}), '(year=2015, month=7, day=30, hour=0)\n', (100394, 100430), False, 'import datetime\n'), ((102569, 102616), 'signal.signal', 'signal.signal', (['signal.SIGINT', '__signal_handling'], {}), '(signal.SIGINT, __signal_handling)\n', (102582, 102616), False, 'import signal\n'), ((102914, 103028), 'multiprocessing.Pool', 'multiprocessing.Pool', (['args.num_processes'], {'initializer': '__parse_into_json_process', 'initargs': '(input_queue, args)'}), '(args.num_processes, initializer=\n __parse_into_json_process, initargs=(input_queue, args))\n', (102934, 103028), False, 'import multiprocessing\n'), ((115145, 115218), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Image Parse for FGO Battle Results"""'}), "(description='Image Parse for FGO Battle Results')\n", (115168, 115218), False, 'import argparse\n'), ((117512, 117567), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO', 'format': 'lformat'}), '(level=logging.INFO, format=lformat)\n', (117531, 117567), False, 'import logging\n'), ((5544, 5566), 'pathlib.Path', 'Path', (['"""background.npz"""'], {}), "('background.npz')\n", (5548, 5566), False, 'from pathlib import Path\n'), ((7841, 7870), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'img_gray'], {}), "('image', img_gray)\n", (7851, 7870), False, 'import cv2\n'), ((7879, 7893), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (7890, 7893), False, 'import cv2\n'), ((7902, 7925), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (7923, 7925), False, 'import cv2\n'), ((8026, 8050), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'inv'], {}), "('image', inv)\n", (8036, 8050), False, 'import cv2\n'), ((8059, 8073), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (8070, 8073), False, 'import cv2\n'), ((8082, 8105), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (8103, 8105), False, 'import cv2\n'), ((8249, 8270), 'cv2.boundingRect', 'cv2.boundingRect', (['cnt'], {}), '(cnt)\n', (8265, 8270), False, 'import cv2\n'), ((8286, 8306), 'cv2.contourArea', 'cv2.contourArea', (['cnt'], {}), '(cnt)\n', (8301, 8306), False, 'import cv2\n'), ((9146, 9244), 'cv2.resize', 'cv2.resize', (['frame_img', '(0, 0)'], {'fx': 'resize_scale', 'fy': 'resize_scale', 'interpolation': 'cv2.INTER_CUBIC'}), '(frame_img, (0, 0), fx=resize_scale, fy=resize_scale,\n interpolation=cv2.INTER_CUBIC)\n', (9156, 9244), False, 'import cv2\n'), ((9530, 9560), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'frame_img'], {}), "('image', frame_img)\n", (9540, 9560), False, 'import cv2\n'), ((9569, 9583), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (9580, 9583), False, 'import cv2\n'), ((9592, 9615), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (9613, 9615), False, 'import cv2\n'), ((9940, 9969), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'img_gray'], {}), "('image', img_gray)\n", (9950, 9969), False, 'import cv2\n'), ((9978, 9992), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (9989, 9992), False, 'import cv2\n'), ((10001, 10024), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (10022, 10024), False, 'import cv2\n'), ((11381, 11399), 'cv2.split', 'cv2.split', (['img_rgb'], {}), '(img_rgb)\n', (11390, 11399), False, 'import cv2\n'), ((11556, 11597), 'cv2.cvtColor', 'cv2.cvtColor', (['img_rgb', 'cv2.COLOR_BGR2GRAY'], {}), '(img_rgb, cv2.COLOR_BGR2GRAY)\n', (11568, 11597), False, 'import cv2\n'), ((11626, 11666), 'cv2.cvtColor', 'cv2.cvtColor', (['img_rgb', 'cv2.COLOR_BGR2HSV'], {}), '(img_rgb, cv2.COLOR_BGR2HSV)\n', (11638, 11666), False, 'import cv2\n'), ((11697, 11765), 'cv2.threshold', 'cv2.threshold', (['self.img_gray_orig', 'threshold', '(255)', 'cv2.THRESH_BINARY'], {}), '(self.img_gray_orig, threshold, 255, cv2.THRESH_BINARY)\n', (11710, 11765), False, 'import cv2\n'), ((12727, 12773), 'cv2.cvtColor', 'cv2.cvtColor', (['self.img_rgb', 'cv2.COLOR_BGR2GRAY'], {}), '(self.img_rgb, cv2.COLOR_BGR2GRAY)\n', (12739, 12773), False, 'import cv2\n'), ((12799, 12862), 'cv2.threshold', 'cv2.threshold', (['self.img_gray', 'threshold', '(255)', 'cv2.THRESH_BINARY'], {}), '(self.img_gray, threshold, 255, cv2.THRESH_BINARY)\n', (12812, 12862), False, 'import cv2\n'), ((19582, 19636), 'cv2.threshold', 'cv2.threshold', (['gray_image', '(200)', '(255)', 'cv2.THRESH_BINARY'], {}), '(gray_image, 200, 255, cv2.THRESH_BINARY)\n', (19595, 19636), False, 'import cv2\n'), ((21913, 21939), 'cv2.countNonZero', 'cv2.countNonZero', (['bw_image'], {}), '(bw_image)\n', (21929, 21939), False, 'import cv2\n'), ((22713, 22752), 'cv2.cvtColor', 'cv2.cvtColor', (['image', 'cv2.COLOR_BGR2GRAY'], {}), '(image, cv2.COLOR_BGR2GRAY)\n', (22725, 22752), False, 'import cv2\n'), ((22775, 22826), 'cv2.threshold', 'cv2.threshold', (['gray', '(65)', '(255)', 'cv2.THRESH_BINARY_INV'], {}), '(gray, 65, 255, cv2.THRESH_BINARY_INV)\n', (22788, 22826), False, 'import cv2\n'), ((22978, 23093), 'pytesseract.image_to_string', 'pytesseract.image_to_string', (['qp_image'], {'config': '"""-l eng --oem 1 --psm 7 -c tessedit_char_whitelist=+,0123456789"""'}), "(qp_image, config=\n '-l eng --oem 1 --psm 7 -c tessedit_char_whitelist=+,0123456789')\n", (23005, 23093), False, 'import pytesseract\n'), ((23309, 23359), 'pageinfo.detect_qp_region', 'pageinfo.detect_qp_region', (['self.img_rgb_orig', 'mode'], {}), '(self.img_rgb_orig, mode)\n', (23334, 23359), False, 'import pageinfo\n'), ((24592, 24642), 'pageinfo.detect_qp_region', 'pageinfo.detect_qp_region', (['self.img_rgb_orig', 'mode'], {}), '(self.img_rgb_orig, mode)\n', (24617, 24642), False, 'import pageinfo\n'), ((28149, 28171), 'cv2.bitwise_not', 'cv2.bitwise_not', (['im_th'], {}), '(im_th)\n', (28164, 28171), False, 'import cv2\n'), ((30484, 30532), 'cv2.cvtColor', 'cv2.cvtColor', (['drop_count_img', 'cv2.COLOR_BGR2GRAY'], {}), '(drop_count_img, cv2.COLOR_BGR2GRAY)\n', (30496, 30532), False, 'import cv2\n'), ((30554, 30612), 'cv2.threshold', 'cv2.threshold', (['img_gray', 'threshold', '(255)', 'cv2.THRESH_BINARY'], {}), '(img_gray, threshold, 255, cv2.THRESH_BINARY)\n', (30567, 30612), False, 'import cv2\n'), ((30664, 30688), 'cv2.bitwise_not', 'cv2.bitwise_not', (['img_num'], {}), '(img_num)\n', (30679, 30688), False, 'import cv2\n'), ((31194, 31219), 'cv2.resize', 'cv2.resize', (['img', 'win_size'], {}), '(img, win_size)\n', (31204, 31219), False, 'import cv2\n'), ((31236, 31306), 'cv2.HOGDescriptor', 'cv2.HOGDescriptor', (['win_size', 'block_size', 'block_stride', 'cell_size', 'bins'], {}), '(win_size, block_size, block_stride, cell_size, bins)\n', (31253, 31306), False, 'import cv2\n'), ((31405, 31419), 'numpy.array', 'np.array', (['char'], {}), '(char)\n', (31413, 31419), True, 'import numpy as np\n'), ((31933, 31990), 'cv2.threshold', 'cv2.threshold', (['newimg', 'threshold2', '(255)', 'cv2.THRESH_BINARY'], {}), '(newimg, threshold2, 255, cv2.THRESH_BINARY)\n', (31946, 31990), False, 'import cv2\n'), ((32810, 32835), 'numpy.ones', 'np.ones', (['(4, 4)', 'np.uint8'], {}), '((4, 4), np.uint8)\n', (32817, 32835), True, 'import numpy as np\n'), ((32850, 32898), 'cv2.cvtColor', 'cv2.cvtColor', (['drop_count_img', 'cv2.COLOR_BGR2GRAY'], {}), '(drop_count_img, cv2.COLOR_BGR2GRAY)\n', (32862, 32898), False, 'import cv2\n'), ((32919, 32972), 'cv2.threshold', 'cv2.threshold', (['img', 'threshold', '(255)', 'cv2.THRESH_BINARY'], {}), '(img, threshold, 255, cv2.THRESH_BINARY)\n', (32932, 32972), False, 'import cv2\n'), ((32990, 33030), 'cv2.dilate', 'cv2.dilate', (['img_th', 'kernel'], {'iterations': '(1)'}), '(img_th, kernel, iterations=1)\n', (33000, 33030), False, 'import cv2\n'), ((40146, 40186), 'cv2.cvtColor', 'cv2.cvtColor', (['img_rgb', 'cv2.COLOR_BGR2HSV'], {}), '(img_rgb, cv2.COLOR_BGR2HSV)\n', (40158, 40186), False, 'import cv2\n'), ((40207, 40264), 'cv2.threshold', 'cv2.threshold', (['self.img_gray', '(174)', '(255)', 'cv2.THRESH_BINARY'], {}), '(self.img_gray, 174, 255, cv2.THRESH_BINARY)\n', (40220, 40264), False, 'import cv2\n'), ((40287, 40310), 'cv2.bitwise_not', 'cv2.bitwise_not', (['img_th'], {}), '(img_th)\n', (40302, 40310), False, 'import cv2\n'), ((45370, 45400), 're.match', 're.match', (['pattern_normal', 'line'], {}), '(pattern_normal, line)\n', (45378, 45400), False, 'import re\n'), ((45812, 45841), 're.match', 're.match', (['pattern_small', 'line'], {}), '(pattern_small, line)\n', (45820, 45841), False, 'import re\n'), ((46248, 46276), 're.match', 're.match', (['pattern_tiny', 'line'], {}), '(pattern_tiny, line)\n', (46256, 46276), False, 'import re\n'), ((47384, 47414), 're.match', 're.match', (['pattern_normal', 'line'], {}), '(pattern_normal, line)\n', (47392, 47414), False, 'import re\n'), ((47754, 47783), 're.match', 're.match', (['pattern_small', 'line'], {}), '(pattern_small, line)\n', (47762, 47783), False, 'import re\n'), ((48119, 48147), 're.match', 're.match', (['pattern_tiny', 'line'], {}), '(pattern_tiny, line)\n', (48127, 48147), False, 'import re\n'), ((49061, 49085), 'numpy.array', 'np.array', (['[25, 175, 119]'], {}), '([25, 175, 119])\n', (49069, 49085), True, 'import numpy as np\n'), ((49109, 49133), 'numpy.array', 'np.array', (['[37, 255, 255]'], {}), '([37, 255, 255])\n', (49117, 49133), True, 'import numpy as np\n'), ((49164, 49218), 'cv2.inRange', 'cv2.inRange', (['img_hsv_lower', 'lower_yellow', 'upper_yellow'], {}), '(img_hsv_lower, lower_yellow, upper_yellow)\n', (49175, 49218), False, 'import cv2\n'), ((66867, 66895), 'cv2.resize', 'cv2.resize', (['tmpimg', 'win_size'], {}), '(tmpimg, win_size)\n', (66877, 66895), False, 'import cv2\n'), ((66912, 66982), 'cv2.HOGDescriptor', 'cv2.HOGDescriptor', (['win_size', 'block_size', 'block_stride', 'cell_size', 'bins'], {}), '(win_size, block_size, block_stride, cell_size, bins)\n', (66929, 66982), False, 'import cv2\n'), ((67071, 67085), 'numpy.array', 'np.array', (['char'], {}), '(char)\n', (67079, 67085), True, 'import numpy as np\n'), ((80282, 80310), 'cv2.resize', 'cv2.resize', (['tmpimg', 'win_size'], {}), '(tmpimg, win_size)\n', (80292, 80310), False, 'import cv2\n'), ((80327, 80397), 'cv2.HOGDescriptor', 'cv2.HOGDescriptor', (['win_size', 'block_size', 'block_stride', 'cell_size', 'bins'], {}), '(win_size, block_size, block_stride, cell_size, bins)\n', (80344, 80397), False, 'import cv2\n'), ((80496, 80510), 'numpy.array', 'np.array', (['test'], {}), '(test)\n', (80504, 80510), True, 'import numpy as np\n'), ((86559, 86621), 'cv2.compareHist', 'cv2.compareHist', (['channel1', 'channel2', 'cv2.HISTCMP_BHATTACHARYYA'], {}), '(channel1, channel2, cv2.HISTCMP_BHATTACHARYYA)\n', (86574, 86621), False, 'import cv2\n'), ((87788, 87816), 'numpy.fromfile', 'np.fromfile', (['filename', 'dtype'], {}), '(filename, dtype)\n', (87799, 87816), True, 'import numpy as np\n'), ((87831, 87853), 'cv2.imdecode', 'cv2.imdecode', (['n', 'flags'], {}), '(n, flags)\n', (87843, 87853), False, 'import cv2\n'), ((88495, 88506), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (88503, 88506), False, 'import sys\n'), ((88663, 88674), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (88671, 88674), False, 'import sys\n'), ((88828, 88839), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (88836, 88839), False, 'import sys\n'), ((88993, 89004), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (89001, 89004), False, 'import sys\n'), ((89623, 89637), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (89627, 89637), False, 'from pathlib import Path\n'), ((96390, 96411), 'PIL.Image.open', 'Image.open', (['file_path'], {}), '(file_path)\n', (96400, 96411), False, 'from PIL import Image\n'), ((98953, 98972), 'pathlib.Path', 'Path', (['src_file_path'], {}), '(src_file_path)\n', (98957, 98972), False, 'from pathlib import Path\n'), ((99187, 99226), 'os.rename', 'os.rename', (['src_file_path', 'dst_file_path'], {}), '(src_file_path, dst_file_path)\n', (99196, 99226), False, 'import os\n'), ((99464, 99475), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (99472, 99475), False, 'import sys\n'), ((99632, 99643), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (99640, 99643), False, 'import sys\n'), ((99797, 99808), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (99805, 99808), False, 'import sys\n'), ((99962, 99973), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (99970, 99973), False, 'import sys\n'), ((101910, 101921), 'sys.exit', 'sys.exit', (['(1)'], {}), '(1)\n', (101918, 101921), False, 'import sys\n'), ((111279, 111319), 'itertools.chain.from_iterable', 'itertools.chain.from_iterable', (['item_list'], {}), '(item_list)\n', (111308, 111319), False, 'import itertools\n'), ((114353, 114369), 'collections.Counter', 'Counter', (['allitem'], {}), '(allitem)\n', (114360, 114369), False, 'from collections import Counter\n'), ((1162, 1176), 'pathlib.Path', 'Path', (['__file__'], {}), '(__file__)\n', (1166, 1176), False, 'from pathlib import Path\n'), ((5389, 5401), 'json.load', 'json.load', (['f'], {}), '(f)\n', (5398, 5401), False, 'import json\n'), ((9350, 9447), 'cv2.resize', 'cv2.resize', (['frame_img', '(0, 0)'], {'fx': 'resize_scale', 'fy': 'resize_scale', 'interpolation': 'cv2.INTER_AREA'}), '(frame_img, (0, 0), fx=resize_scale, fy=resize_scale,\n interpolation=cv2.INTER_AREA)\n', (9360, 9447), False, 'import cv2\n'), ((11158, 11190), 'pageinfo.guess_pageinfo', 'pageinfo.guess_pageinfo', (['img_rgb'], {}), '(img_rgb)\n', (11181, 11190), False, 'import pageinfo\n'), ((12464, 12504), 'cv2.imwrite', 'cv2.imwrite', (['"""frame_img.png"""', 'img_resize'], {}), "('frame_img.png', img_resize)\n", (12475, 12504), False, 'import cv2\n'), ((12664, 12701), 'cv2.imwrite', 'cv2.imwrite', (['"""dcnt_new.png"""', 'dcnt_new'], {}), "('dcnt_new.png', dcnt_new)\n", (12675, 12701), False, 'import cv2\n'), ((16937, 16990), 'cv2.calcHist', 'cv2.calcHist', (['[img_hsv_x]', '[0]', 'None', '[256]', '[0, 256]'], {}), '([img_hsv_x], [0], None, [256], [0, 256])\n', (16949, 16990), False, 'import cv2\n'), ((17065, 17084), 'cv2.minMaxLoc', 'cv2.minMaxLoc', (['hist'], {}), '(hist)\n', (17078, 17084), False, 'import cv2\n'), ((17478, 17571), 'cv2.resize', 'cv2.resize', (['img', '(0, 0)'], {'fx': 'resize_scale', 'fy': 'resize_scale', 'interpolation': 'cv2.INTER_CUBIC'}), '(img, (0, 0), fx=resize_scale, fy=resize_scale, interpolation=cv2\n .INTER_CUBIC)\n', (17488, 17571), False, 'import cv2\n'), ((18787, 18816), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'dcnt_new'], {}), "('image', dcnt_new)\n", (18797, 18816), False, 'import cv2\n'), ((18829, 18843), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (18840, 18843), False, 'import cv2\n'), ((18856, 18879), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (18877, 18879), False, 'import cv2\n'), ((19237, 19298), 'cv2.rectangle', 'cv2.rectangle', (['img_copy', 'topleft', 'bottomright', '(0, 0, 255)', '(3)'], {}), '(img_copy, topleft, bottomright, (0, 0, 255), 3)\n', (19250, 19298), False, 'import cv2\n'), ((19311, 19362), 'cv2.imwrite', 'cv2.imwrite', (['"""./scroll_bar_selected2.jpg"""', 'img_copy'], {}), "('./scroll_bar_selected2.jpg', img_copy)\n", (19322, 19362), False, 'import cv2\n'), ((19696, 19741), 'cv2.imwrite', 'cv2.imwrite', (['"""scroll_bar_binary2.png"""', 'binary'], {}), "('scroll_bar_binary2.png', binary)\n", (19707, 19741), False, 'import cv2\n'), ((19761, 19823), 'cv2.findContours', 'cv2.findContours', (['binary', 'cv2.RETR_LIST', 'cv2.CHAIN_APPROX_NONE'], {}), '(binary, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)\n', (19777, 19823), False, 'import cv2\n'), ((20037, 20058), 'cv2.boundingRect', 'cv2.boundingRect', (['cnt'], {}), '(cnt)\n', (20053, 20058), False, 'import cv2\n'), ((21433, 21525), 'pageinfo.guess_pagenum', 'pageinfo.guess_pagenum', (['self.asr_y', 'esr_y', 'self.actual_height', 'entire_height', 'cap_height'], {}), '(self.asr_y, esr_y, self.actual_height, entire_height,\n cap_height)\n', (21455, 21525), False, 'import pageinfo\n'), ((21542, 21609), 'pageinfo.guess_pages', 'pageinfo.guess_pages', (['self.actual_height', 'entire_height', 'cap_height'], {}), '(self.actual_height, entire_height, cap_height)\n', (21562, 21609), False, 'import pageinfo\n'), ((21630, 21697), 'pageinfo.guess_lines', 'pageinfo.guess_lines', (['self.actual_height', 'entire_height', 'cap_height'], {}), '(self.actual_height, entire_height, cap_height)\n', (21650, 21697), False, 'import pageinfo\n'), ((22481, 22507), 're.findall', 're.findall', (['"""[0-9]+"""', 'text'], {}), "('[0-9]+', text)\n", (22491, 22507), False, 'import re\n'), ((23554, 23625), 'cv2.bitwise_not', 'cv2.bitwise_not', (['self.img_th_orig[pt[0][1]:pt[1][1], pt[0][0]:pt[1][0]]'], {}), '(self.img_th_orig[pt[0][1]:pt[1][1], pt[0][0]:pt[1][0]])\n', (23569, 23625), False, 'import cv2\n'), ((25695, 25756), 'cv2.rectangle', 'cv2.rectangle', (['img_copy', 'bounds[0]', 'bounds[1]', '(0, 0, 255)', '(3)'], {}), '(img_copy, bounds[0], bounds[1], (0, 0, 255), 3)\n', (25708, 25756), False, 'import cv2\n'), ((25769, 25817), 'cv2.imwrite', 'cv2.imwrite', (['"""./qp_gain_detection.jpg"""', 'img_copy'], {}), "('./qp_gain_detection.jpg', img_copy)\n", (25780, 25817), False, 'import cv2\n'), ((25895, 25987), 'cv2.bitwise_not', 'cv2.bitwise_not', (['self.img_th_orig[topleft[1]:bottomright[1], topleft[0]:bottomright[0]]'], {}), '(self.img_th_orig[topleft[1]:bottomright[1], topleft[0]:\n bottomright[0]])\n', (25910, 25987), False, 'import cv2\n'), ((26921, 26973), 'cv2.calcHist', 'cv2.calcHist', (['[img_th_x]', '[0]', 'None', '[256]', '[0, 256]'], {}), '([img_th_x], [0], None, [256], [0, 256])\n', (26933, 26973), False, 'import cv2\n'), ((27043, 27062), 'cv2.minMaxLoc', 'cv2.minMaxLoc', (['hist'], {}), '(hist)\n', (27056, 27062), False, 'import cv2\n'), ((27280, 27332), 'cv2.calcHist', 'cv2.calcHist', (['[img_th_x]', '[0]', 'None', '[256]', '[0, 256]'], {}), '([img_th_x], [0], None, [256], [0, 256])\n', (27292, 27332), False, 'import cv2\n'), ((27402, 27421), 'cv2.minMaxLoc', 'cv2.minMaxLoc', (['hist'], {}), '(hist)\n', (27415, 27421), False, 'import cv2\n'), ((28191, 28258), 'cv2.findContours', 'cv2.findContours', (['im_th', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(im_th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (28207, 28258), False, 'import cv2\n'), ((28403, 28424), 'cv2.boundingRect', 'cv2.boundingRect', (['cnt'], {}), '(cnt)\n', (28419, 28424), False, 'import cv2\n'), ((28444, 28464), 'cv2.contourArea', 'cv2.contourArea', (['cnt'], {}), '(cnt)\n', (28459, 28464), False, 'import cv2\n'), ((29982, 30010), 'cv2.resize', 'cv2.resize', (['tmpimg', 'win_size'], {}), '(tmpimg, win_size)\n', (29992, 30010), False, 'import cv2\n'), ((30031, 30101), 'cv2.HOGDescriptor', 'cv2.HOGDescriptor', (['win_size', 'block_size', 'block_stride', 'cell_size', 'bins'], {}), '(win_size, block_size, block_stride, cell_size, bins)\n', (30048, 30101), False, 'import cv2\n'), ((30212, 30226), 'numpy.array', 'np.array', (['test'], {}), '(test)\n', (30220, 30226), True, 'import numpy as np\n'), ((33406, 33474), 'cv2.findContours', 'cv2.findContours', (['img_th', 'cv2.RETR_EXTERNAL', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(img_th, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n', (33422, 33474), False, 'import cv2\n'), ((33619, 33640), 'cv2.boundingRect', 'cv2.boundingRect', (['cnt'], {}), '(cnt)\n', (33635, 33640), False, 'import cv2\n'), ((36177, 36245), 'cv2.findContours', 'cv2.findContours', (['img_1strow', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(img_1strow, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (36193, 36245), False, 'import cv2\n'), ((36360, 36380), 'cv2.contourArea', 'cv2.contourArea', (['cnt'], {}), '(cnt)\n', (36375, 36380), False, 'import cv2\n'), ((49280, 49356), 'cv2.findContours', 'cv2.findContours', (['img_hsv_lower_mask', 'cv2.RETR_TREE', 'cv2.CHAIN_APPROX_SIMPLE'], {}), '(img_hsv_lower_mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)\n', (49296, 49356), False, 'import cv2\n'), ((49501, 49522), 'cv2.boundingRect', 'cv2.boundingRect', (['cnt'], {}), '(cnt)\n', (49517, 49522), False, 'import cv2\n'), ((49542, 49562), 'cv2.contourArea', 'cv2.contourArea', (['cnt'], {}), '(cnt)\n', (49557, 49562), False, 'import cv2\n'), ((60736, 60766), 're.match', 're.match', (['pattern_normal', 'line'], {}), '(pattern_normal, line)\n', (60744, 60766), False, 'import re\n'), ((61238, 61267), 're.match', 're.match', (['pattern_small', 'line'], {}), '(pattern_small, line)\n', (61246, 61267), False, 'import re\n'), ((61733, 61761), 're.match', 're.match', (['pattern_tiny', 'line'], {}), '(pattern_tiny, line)\n', (61741, 61761), False, 'import re\n'), ((64779, 64807), 'cv2.resize', 'cv2.resize', (['tmpimg', 'win_size'], {}), '(tmpimg, win_size)\n', (64789, 64807), False, 'import cv2\n'), ((64828, 64898), 'cv2.HOGDescriptor', 'cv2.HOGDescriptor', (['win_size', 'block_size', 'block_stride', 'cell_size', 'bins'], {}), '(win_size, block_size, block_stride, cell_size, bins)\n', (64845, 64898), False, 'import cv2\n'), ((64999, 65013), 'numpy.array', 'np.array', (['char'], {}), '(char)\n', (65007, 65013), True, 'import numpy as np\n'), ((88058, 88074), 'PIL.ExifTags.TAGS.get', 'TAGS.get', (['id', 'id'], {}), '(id, id)\n', (88066, 88074), False, 'from PIL.ExifTags import TAGS\n'), ((95200, 95215), 'pathlib.Path', 'Path', (['file_path'], {}), '(file_path)\n', (95204, 95215), False, 'from pathlib import Path\n'), ((96531, 96557), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (96549, 96557), False, 'import datetime\n'), ((98870, 98893), 'os.path.exists', 'os.path.exists', (['out_dir'], {}), '(out_dir)\n', (98884, 98893), False, 'import os\n'), ((98907, 98927), 'os.makedirs', 'os.makedirs', (['out_dir'], {}), '(out_dir)\n', (98918, 98927), False, 'import os\n'), ((112905, 112931), 'operator.itemgetter', 'itemgetter', (['"""dropPriority"""'], {}), "('dropPriority')\n", (112915, 112931), False, 'from operator import itemgetter\n'), ((114755, 114781), 'os.path.exists', 'os.path.exists', (['out_folder'], {}), '(out_folder)\n', (114769, 114781), False, 'import os\n'), ((114795, 114818), 'os.makedirs', 'os.makedirs', (['out_folder'], {}), '(out_folder)\n', (114806, 114818), False, 'import os\n'), ((117678, 117699), 'pathlib.Path', 'Path', (['args.out_folder'], {}), '(args.out_folder)\n', (117682, 117699), False, 'from pathlib import Path\n'), ((8555, 8573), 'cv2.contourArea', 'cv2.contourArea', (['x'], {}), '(x)\n', (8570, 8573), False, 'import cv2\n'), ((12614, 12651), 'cv2.imwrite', 'cv2.imwrite', (['"""dcnt_old.png"""', 'dcnt_old'], {}), "('dcnt_old.png', dcnt_old)\n", (12625, 12651), False, 'import cv2\n'), ((17674, 17766), 'cv2.resize', 'cv2.resize', (['img', '(0, 0)'], {'fx': 'resize_scale', 'fy': 'resize_scale', 'interpolation': 'cv2.INTER_AREA'}), '(img, (0, 0), fx=resize_scale, fy=resize_scale, interpolation=cv2\n .INTER_AREA)\n', (17684, 17766), False, 'import cv2\n'), ((18186, 18215), 'cv2.imshow', 'cv2.imshow', (['"""image"""', 'dcnt_old'], {}), "('image', dcnt_old)\n", (18196, 18215), False, 'import cv2\n'), ((18232, 18246), 'cv2.waitKey', 'cv2.waitKey', (['(0)'], {}), '(0)\n', (18243, 18246), False, 'import cv2\n'), ((18263, 18286), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (18284, 18286), False, 'import cv2\n'), ((36578, 36614), 'cv2.approxPolyDP', 'cv2.approxPolyDP', (['cnt', 'epsilon', '(True)'], {}), '(cnt, epsilon, True)\n', (36594, 36614), False, 'import cv2\n'), ((68127, 68186), 'cv2.matchTemplate', 'cv2.matchTemplate', (['img_gray', 'template', 'cv2.TM_CCOEFF_NORMED'], {}), '(img_gray, template, cv2.TM_CCOEFF_NORMED)\n', (68144, 68186), False, 'import cv2\n'), ((68282, 68308), 'numpy.where', 'np.where', (['(res >= threshold)'], {}), '(res >= threshold)\n', (68290, 68308), True, 'import numpy as np\n'), ((72562, 72599), 're.sub', 're.sub', (['"""\\\\(|\\\\)|\\\\+"""', '""""""', 'self.bonus'], {}), "('\\\\(|\\\\)|\\\\+', '', self.bonus)\n", (72568, 72599), False, 'import re\n'), ((88139, 88191), 'datetime.datetime.strptime', 'datetime.datetime.strptime', (['val', '"""%Y:%m:%d %H:%M:%S"""'], {}), "(val, '%Y:%m:%d %H:%M:%S')\n", (88165, 88191), False, 'import datetime\n'), ((103105, 103122), 'pathlib.Path', 'Path', (['args.folder'], {}), '(args.folder)\n', (103109, 103122), False, 'from pathlib import Path\n'), ((104304, 104333), 'math.floor', 'math.floor', (["(quest['id'] / 100)"], {}), "(quest['id'] / 100)\n", (104314, 104333), False, 'import math\n'), ((112846, 112862), 'operator.itemgetter', 'itemgetter', (['"""id"""'], {}), "('id')\n", (112856, 112862), False, 'from operator import itemgetter\n'), ((114319, 114331), 'collections.Counter', 'Counter', (['tmp'], {}), '(tmp)\n', (114326, 114331), False, 'from collections import Counter\n'), ((114882, 114913), 'pathlib.Path', 'Path', (["parsed_file['image_path']"], {}), "(parsed_file['image_path'])\n", (114886, 114913), False, 'from pathlib import Path\n'), ((115032, 115087), 'json.dump', 'json.dump', (['parsed_file', 'f'], {'indent': '(4)', 'ensure_ascii': '(False)'}), '(parsed_file, f, indent=4, ensure_ascii=False)\n', (115041, 115087), False, 'import json\n'), ((36528, 36552), 'cv2.arcLength', 'cv2.arcLength', (['cnt', '(True)'], {}), '(cnt, True)\n', (36541, 36552), False, 'import cv2\n'), ((36694, 36715), 'cv2.boundingRect', 'cv2.boundingRect', (['cnt'], {}), '(cnt)\n', (36710, 36715), False, 'import cv2\n'), ((63126, 63156), 're.match', 're.match', (['pattern_normal', 'line'], {}), '(pattern_normal, line)\n', (63134, 63156), False, 'import re\n'), ((63667, 63696), 're.match', 're.match', (['pattern_small', 'line'], {}), '(pattern_small, line)\n', (63675, 63696), False, 'import re\n'), ((64200, 64228), 're.match', 're.match', (['pattern_tiny', 'line'], {}), '(pattern_tiny, line)\n', (64208, 64228), False, 'import re\n'), ((104428, 104457), 'math.floor', 'math.floor', (["(quest['id'] / 100)"], {}), "(quest['id'] / 100)\n", (104438, 104457), False, 'import math\n'), ((112789, 112810), 'operator.itemgetter', 'itemgetter', (['"""dropnum"""'], {}), "('dropnum')\n", (112799, 112810), False, 'from operator import itemgetter\n'), ((114655, 114700), 'json.dumps', 'json.dumps', (['parsed_output'], {'ensure_ascii': '(False)'}), '(parsed_output, ensure_ascii=False)\n', (114665, 114700), False, 'import json\n'), ((90087, 90101), 'pathlib.Path', 'Path', (['filename'], {}), '(filename)\n', (90091, 90101), False, 'from pathlib import Path\n'), ((90719, 90739), 'PIL.Image.open', 'Image.open', (['filename'], {}), '(filename)\n', (90729, 90739), False, 'from PIL import Image\n'), ((104551, 104583), 'math.floor', 'math.floor', (["(quest['id'] / 100000)"], {}), "(quest['id'] / 100000)\n", (104561, 104583), False, 'import math\n'), ((108643, 108672), 'math.floor', 'math.floor', (["(item['id'] / 1000)"], {}), "(item['id'] / 1000)\n", (108653, 108672), False, 'import math\n'), ((109639, 109668), 'math.floor', 'math.floor', (["(item['id'] / 1000)"], {}), "(item['id'] / 1000)\n", (109649, 109668), False, 'import math\n'), ((118089, 118106), 'pathlib.Path', 'Path', (['args.folder'], {}), '(args.folder)\n', (118093, 118106), False, 'from pathlib import Path\n'), ((90861, 90887), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': '(1)'}), '(days=1)\n', (90879, 90887), False, 'import datetime\n'), ((118584, 118601), 'pathlib.Path', 'Path', (['args.folder'], {}), '(args.folder)\n', (118588, 118601), False, 'from pathlib import Path\n'), ((103713, 103720), 'pathlib.Path', 'Path', (['f'], {}), '(f)\n', (103717, 103720), False, 'from pathlib import Path\n')]
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
"""Execution Callbacks for Eager Mode."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import functools
import numpy as np
from tensorflow.python import pywrap_tensorflow
from tensorflow.python.eager import context
from tensorflow.python.eager import core
from tensorflow.python.platform import tf_logging as logging
_DEFAULT_CALLBACK_ACTION = "raise"
_VALID_CALLBACK_ACTIONS = (None, "ignore", "print", "raise", "warn")
# TODO(cais): Consider moving this exception class to errors_impl.py.
class InfOrNanError(Exception):
"""Exception for inf and/or nan being present in tensor."""
def __init__(self,
op_type,
op_name,
output_index,
num_outputs,
value):
"""Constructor of InfOrNanError.
Args:
op_type: Type name of the op that generated the tensor that generated the
`inf`(s) or `nan`(s) (e.g., `Div`).
op_name: Name of the op that generated the tensor with `inf`(s) or
`nan`(s). This name is set by client and can be `None` if it is unset.
output_index: The 0-based output index of the tensor that contains
`inf`(s) or `nan`(s).
num_outputs: Total number of outputs of the operation.
value: The tensor value that contains `inf`(s) or `nan`(s).
"""
self._op_type = op_type
self._op_name = op_name
self._output_index = output_index
self._num_outputs = num_outputs
self._value = value
self._total_count = np.size(value)
self._inf_count = np.count_nonzero(np.isinf(value))
self._nan_count = np.count_nonzero(np.isnan(value))
super(InfOrNanError, self).__init__(self._get_error_message())
def _get_error_message(self):
"""Get the error message describing this InfOrNanError object."""
name_str = (("'%s'" % self._op_name) if self._op_name is not None
else str(self._op_name))
msg = "Output %d of %d of TFE operation %s (name: %s) contains " % (
self._output_index + 1, self._num_outputs, self._op_type, name_str)
if self._inf_count and self._nan_count:
msg += "%d inf(s) and %d nan(s) " % (self._inf_count, self._nan_count)
elif self._inf_count:
msg += "%d inf(s) " % self._inf_count
else:
msg += "%d nan(s) " % self._nan_count
msg += "out of a total of %d element(s). Tensor value: %s" % (
self._total_count, self._value)
return msg
@property
def op_type(self):
return self._op_type
@property
def op_name(self):
return self._op_name
@property
def output_index(self):
return self._output_index
@property
def num_outputs(self):
return self._num_outputs
@property
def value(self):
return self._value
def inf_nan_callback(op_type,
op_name,
attrs,
inputs,
outputs,
check_inf=True,
check_nan=True,
action=_DEFAULT_CALLBACK_ACTION):
"""An execution callback that checks for `inf`s and `nan`s in output tensors.
This callback can be used with `tfe.add_execute_callback` to check for invalid
numeric values. E.g.,
```python
tfe.add_execute_callback(tfe.inf_nan_callback)
```
Args:
op_type: Name of the TFE operation type (e.g., `MatMul`).
op_name: Name of the TFE operation. This name is set by client and can be
`None` if it unset.
attrs: Attributes of the TFE operation, as a tuple of alternating attribute
names and attribute values.
inputs: The `list` of input tensors to the operation, currently unused by
this callback.
outputs: The `list` of output tensors from the operation, checked by this
callback for `inf` and `nan` values.
check_inf: (`bool`) Whether this callback should check for `inf` values in
the output tensor values.
check_nan: (`bool`) Whether this callback should check for `nan` values in
the output tensor values.
action: (`str`) Action to be taken by the callback when `inf` or `nan`
values are detected. Possible values {"raise", "warn", "print"}
`"raise"`: Raise a `InfOrNanError`.
`"warn"`: Log a warning using `tf.logging.warn`.
`"print"`: Print a message to `sys.stdout`.
Raises:
InfOrNanError: iff `inf` or `nan` values are seen in any of `outputs` and
`action` is `"raise"`.
ValueError: iff the value of `action` is invalid.
"""
del attrs, inputs # Not used.
ctx = context.get_default_context()
for index, output in enumerate(outputs):
if not output.dtype.is_numpy_compatible:
continue
numpy_dtype = output.dtype.as_numpy_dtype
if (np.issubdtype(numpy_dtype, np.float) or
np.issubdtype(numpy_dtype, np.complex) or
np.issubdtype(numpy_dtype, np.integer)):
try:
check_numerics_op_attrs = (
"message", "Eager-mode inf/nan check",
"T", outputs[0].dtype.as_datatype_enum)
# TODO(cais): Consider moving this into execute.py.
# pylint: disable=protected-access
pywrap_tensorflow.TFE_Py_Execute(
ctx._handle, output.device, "CheckNumerics", [output],
check_numerics_op_attrs, 1)
# pylint: enable=protected-access
except core._NotOkStatusException: # pylint: disable=protected-access
value = output.numpy()
inf_detected = np.any(np.isinf(value)) and check_inf
nan_detected = np.any(np.isnan(value)) and check_nan
if not inf_detected and not nan_detected:
continue
error = InfOrNanError(op_type, op_name, index, len(outputs), value)
if action == "print":
print("Warning: %s" % str(error))
elif action == "warn":
logging.warn(str(error))
elif action == "raise":
raise error
else:
raise ValueError(
"Invalid action for inf_nan_callback: %s. Valid actions are: "
"{print | warn | raise}" % action)
def inf_callback(op_type,
op_name,
attrs,
inputs,
outputs,
action=_DEFAULT_CALLBACK_ACTION):
"""A specialization of `inf_nan_callback` that checks for `inf`s only."""
inf_nan_callback(
op_type, op_name, attrs, inputs, outputs, check_inf=True, check_nan=False,
action=action)
def nan_callback(op_type,
op_name,
attrs,
inputs,
outputs,
action=_DEFAULT_CALLBACK_ACTION):
"""A specialization of `inf_nan_callback` that checks for `nan`s only."""
inf_nan_callback(
op_type, op_name, attrs, inputs, outputs, check_inf=False, check_nan=True,
action=action)
def add_execution_callback(callback):
"""Add an execution callback to the default eager context.
An execution callback is invoked immediately after an eager operation or
function has finished execution, providing access to the op's type, name
input and output tensors. Multiple execution callbacks can be added, in
which case the callbacks will be invoked in the order in which they are
added. To clear all execution callbacks that have been added, use
`clear_execution_callbacks()`.
Example:
```python
def print_even_callback(op_type, op_name, attrs, inputs, outputs):
# A callback that prints only the even output values.
if outputs[0].numpy() % 2 == 0:
print("Even output from %s: %s" % (op_name or op_type, outputs))
tfe.add_execution_callback(print_even_callback)
x = tf.pow(2.0, 3.0) - 3.0
y = tf.multiply(x, tf.add(1.0, 5.0))
# When the line above is run, you will see all intermediate outputs that are
# even numbers printed to the console.
tfe.clear_execution_callbacks()
```
Args:
callback: a callable of the signature
`f(op_type, op_name, attrs, inputs, outputs)`.
`op_type` is the type of the operation that was just executed (e.g.,
`MatMul`).
`op_name` is the name of the operation that has was just executed. This
name is set by the client who created the operation and can be `None` if
it is unset.
`attrs` contains the attributes of the operation as a `tuple` of
alternating attribute name and attribute value.
`inputs` is the `list` of input `Tensor`(s) to the op.
`outputs` is the `list` of output `Tensor`(s) from the op.
Return value(s) from the callback are ignored.
"""
context.get_default_context().add_post_execution_callback(callback)
def clear_execution_callbacks():
"""Clear all execution callbacks from the default eager context."""
context.get_default_context().clear_post_execution_callbacks()
def seterr(inf_or_nan=None):
"""Set how abnormal conditions are handled by the default eager context.
Example:
```python
tfe.seterr(inf_or_nan="raise")
a = tf.constant(10.0)
b = tf.constant(0.0)
try:
c = a / b # <-- Raises InfOrNanError.
except Exception as e:
print("Caught Exception: %s" % e)
tfe.seterr(inf_or_nan="ignore")
c = a / b # <-- Does NOT raise exception anymore.
```
Args:
inf_or_nan: Set action for infinity (`inf`) and NaN (`nan`) values.
Possible values: `{"ignore", "print", "raise", "warn"}`.
`"ignore"`: take no action when `inf` values appear.
`"print"`: print a warning to `stdout`.
`"raise"`: raise an `InfOrNanError`.
`"warn"`: print a warning using `tf.logging.warn`.
A value of `None` leads to no change in the action of the condition.
Returns:
A dictionary of old actions.
Raises:
ValueError: If the value of any keyword arguments is invalid.
"""
if inf_or_nan not in _VALID_CALLBACK_ACTIONS:
raise ValueError(
"Invalid action value for inf_or_nan: %s. "
"Valid actions are %s." % (inf_or_nan, _VALID_CALLBACK_ACTIONS))
old_settings = {"inf_or_nan": "ignore"}
default_context = context.get_default_context()
carryover_callbacks = []
for callback in default_context.post_execution_callbacks:
# Check whether the callback is inf_nan_callback or a partial object of
# inf_nan_callback.
if (callback == inf_nan_callback or
isinstance(callback, functools.partial) and
callback.func == inf_nan_callback):
if callback == inf_nan_callback:
old_settings["inf_or_nan"] = _DEFAULT_CALLBACK_ACTION
else:
old_settings["inf_or_nan"] = callback.keywords.get(
"action", _DEFAULT_CALLBACK_ACTION)
elif inf_or_nan is not None:
carryover_callbacks.append(callback)
if inf_or_nan is not None:
default_context.clear_post_execution_callbacks()
for callback in carryover_callbacks:
default_context.add_post_execution_callback(callback)
if inf_or_nan != "ignore":
default_context.add_post_execution_callback(
functools.partial(inf_nan_callback, action=inf_or_nan))
return old_settings
|
[
"functools.partial",
"numpy.size",
"tensorflow.python.eager.context.get_default_context",
"tensorflow.python.pywrap_tensorflow.TFE_Py_Execute",
"numpy.isinf",
"numpy.isnan",
"numpy.issubdtype"
] |
[((5244, 5273), 'tensorflow.python.eager.context.get_default_context', 'context.get_default_context', ([], {}), '()\n', (5271, 5273), False, 'from tensorflow.python.eager import context\n'), ((10708, 10737), 'tensorflow.python.eager.context.get_default_context', 'context.get_default_context', ([], {}), '()\n', (10735, 10737), False, 'from tensorflow.python.eager import context\n'), ((2236, 2250), 'numpy.size', 'np.size', (['value'], {}), '(value)\n', (2243, 2250), True, 'import numpy as np\n'), ((2290, 2305), 'numpy.isinf', 'np.isinf', (['value'], {}), '(value)\n', (2298, 2305), True, 'import numpy as np\n'), ((2346, 2361), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (2354, 2361), True, 'import numpy as np\n'), ((5433, 5469), 'numpy.issubdtype', 'np.issubdtype', (['numpy_dtype', 'np.float'], {}), '(numpy_dtype, np.float)\n', (5446, 5469), True, 'import numpy as np\n'), ((5481, 5519), 'numpy.issubdtype', 'np.issubdtype', (['numpy_dtype', 'np.complex'], {}), '(numpy_dtype, np.complex)\n', (5494, 5519), True, 'import numpy as np\n'), ((5531, 5569), 'numpy.issubdtype', 'np.issubdtype', (['numpy_dtype', 'np.integer'], {}), '(numpy_dtype, np.integer)\n', (5544, 5569), True, 'import numpy as np\n'), ((9243, 9272), 'tensorflow.python.eager.context.get_default_context', 'context.get_default_context', ([], {}), '()\n', (9270, 9272), False, 'from tensorflow.python.eager import context\n'), ((9418, 9447), 'tensorflow.python.eager.context.get_default_context', 'context.get_default_context', ([], {}), '()\n', (9445, 9447), False, 'from tensorflow.python.eager import context\n'), ((5833, 5952), 'tensorflow.python.pywrap_tensorflow.TFE_Py_Execute', 'pywrap_tensorflow.TFE_Py_Execute', (['ctx._handle', 'output.device', '"""CheckNumerics"""', '[output]', 'check_numerics_op_attrs', '(1)'], {}), "(ctx._handle, output.device,\n 'CheckNumerics', [output], check_numerics_op_attrs, 1)\n", (5865, 5952), False, 'from tensorflow.python import pywrap_tensorflow\n'), ((11635, 11689), 'functools.partial', 'functools.partial', (['inf_nan_callback'], {'action': 'inf_or_nan'}), '(inf_nan_callback, action=inf_or_nan)\n', (11652, 11689), False, 'import functools\n'), ((6154, 6169), 'numpy.isinf', 'np.isinf', (['value'], {}), '(value)\n', (6162, 6169), True, 'import numpy as np\n'), ((6215, 6230), 'numpy.isnan', 'np.isnan', (['value'], {}), '(value)\n', (6223, 6230), True, 'import numpy as np\n')]
|
import numpy as np
from .distribution import NoDistribution
__all__ = ["Simulator"]
class Simulator(NoDistribution):
def __init__(self, function, *args, **kwargs):
"""
This class stores a function defined by the user in python language.
function : function
Simulation function defined by the user.
*args and **kwargs :
Arguments and keywords arguments that the function takes.
"""
self.function = function
observed = self.data
super().__init__(shape=np.prod(observed.shape), dtype=observed.dtype, *args, **kwargs)
def random(self, point=None, size=None):
"""
Draw random values from Simulator
Parameters
----------
point : dict, optional
Dict of variable values on which random values are to be
conditioned (uses default point if not specified).
size : int, optional
Desired size of random sample (returns one sample if not
specified).
Returns
-------
array
"""
raise NotImplementedError("Not implemented yet")
def _repr_latex_(self, name=None, dist=None):
if dist is None:
dist = self
name = r"\text{%s}" % name
function = dist.function
params = dist.parameters
sum_stat = dist.sum_stat
return r"${} \sim \text{{Simulator}}(\mathit{{function}}={},~\mathit{{parameters}}={},~\mathit{{summary statistics}}={})$".format(
name, function, params, sum_stat
)
|
[
"numpy.prod"
] |
[((556, 579), 'numpy.prod', 'np.prod', (['observed.shape'], {}), '(observed.shape)\n', (563, 579), True, 'import numpy as np\n')]
|
import copy
import os
import random
import re
import time
from os.path import join
from threading import Thread
import cv2
import gym
import numpy as np
from filelock import FileLock, Timeout
from gym.utils import seeding
from vizdoom.vizdoom import ScreenResolution, DoomGame, Mode, AutomapMode
from algorithms.utils.spaces.discretized import Discretized
from utils.utils import log, project_tmp_dir
def doom_lock_file(max_parallel):
"""
Doom instances tend to have problems starting when a lot of them are initialized in parallel.
This is not a problem during normal execution once the envs are initialized.
The "sweet spot" for the number of envs that can be initialized in parallel is about 5-10.
Here we use file locking mechanism to ensure that only a limited amount of envs are being initialized at the same
time.
This tends to be more of a problem for multiplayer envs.
This also has an advantage of working across completely independent process groups, e.g. different experiments.
"""
lock_filename = f'doom_{random.randrange(0, max_parallel):03d}.lockfile'
tmp_dir = project_tmp_dir()
lock_path = join(tmp_dir, lock_filename)
return lock_path
def key_to_action_default(key):
"""
MOVE_FORWARD
MOVE_BACKWARD
MOVE_RIGHT
MOVE_LEFT
SELECT_WEAPON1
SELECT_WEAPON2
SELECT_WEAPON3
SELECT_WEAPON4
SELECT_WEAPON5
SELECT_WEAPON6
SELECT_WEAPON7
ATTACK
SPEED
TURN_LEFT_RIGHT_DELTA
"""
from pynput.keyboard import Key
# health gathering
action_table = {
Key.left: 0,
Key.right: 1,
Key.up: 2,
Key.down: 3,
}
# action_table = {
# Key.up: 0,
# Key.down: 1,
# Key.alt: 6,
# Key.ctrl: 11,
# Key.shift: 12,
# Key.space: 13,
# Key.right: 'turn_right',
# Key.left: 'turn_left',
# }
return action_table.get(key, None)
class VizdoomEnv(gym.Env):
def __init__(self,
action_space,
config_file,
coord_limits=None,
max_histogram_length=200,
show_automap=False,
skip_frames=1,
async_mode=False,
record_to=None):
self.initialized = False
# essential game data
self.game = None
self.state = None
self.curr_seed = 0
self.rng = None
self.skip_frames = skip_frames
self.async_mode = async_mode
# optional - for topdown view rendering and visitation heatmaps
self.show_automap = show_automap
self.coord_limits = coord_limits
# can be adjusted after the environment is created (but before any reset() call) via observation space wrapper
self.screen_w, self.screen_h, self.channels = 640, 480, 3
self.screen_resolution = ScreenResolution.RES_640X480
self.calc_observation_space()
self.black_screen = None
# provided as a part of environment definition, since these depend on the scenario and
# can be quite complex multi-discrete spaces
self.action_space = action_space
self.composite_action_space = hasattr(self.action_space, 'spaces')
self.delta_actions_scaling_factor = 7.5
scenarios_dir = join(os.path.dirname(__file__), 'scenarios')
self.config_path = join(scenarios_dir, config_file)
self.variable_indices = self._parse_variable_indices(self.config_path)
# only created if we call render() method
self.viewer = None
# record full episodes using VizDoom recording functionality
self.record_to = record_to
self.is_multiplayer = False # overridden in derived classes
# (optional) histogram to track positional coverage
# do not pass coord_limits if you don't need this, to avoid extra calculation
self.max_histogram_length = max_histogram_length
self.current_histogram, self.previous_histogram = None, None
if self.coord_limits:
x = (self.coord_limits[2] - self.coord_limits[0])
y = (self.coord_limits[3] - self.coord_limits[1])
if x > y:
len_x = self.max_histogram_length
len_y = int((y / x) * self.max_histogram_length)
else:
len_x = int((x / y) * self.max_histogram_length)
len_y = self.max_histogram_length
self.current_histogram = np.zeros((len_x, len_y), dtype=np.int32)
self.previous_histogram = np.zeros_like(self.current_histogram)
# helpers for human play with pynput keyboard input
self._terminate = False
self._current_actions = []
self._actions_flattened = None
self._prev_info = None
self._last_episode_info = None
self._num_episodes = 0
self.mode = 'algo'
self.seed()
def seed(self, seed=None):
self.curr_seed = seeding.hash_seed(seed, max_bytes=4)
self.rng, _ = seeding.np_random(seed=self.curr_seed)
return [self.curr_seed, self.rng]
def calc_observation_space(self):
self.observation_space = gym.spaces.Box(0, 255, (self.screen_h, self.screen_w, self.channels), dtype=np.uint8)
def _set_game_mode(self, mode):
if mode == 'replay':
self.game.set_mode(Mode.PLAYER)
else:
if self.async_mode:
log.info('Starting in async mode! Use this only for testing, otherwise PLAYER mode is much faster')
self.game.set_mode(Mode.ASYNC_PLAYER)
else:
self.game.set_mode(Mode.PLAYER)
def _create_doom_game(self, mode):
self.game = DoomGame()
self.game.load_config(self.config_path)
self.game.set_screen_resolution(self.screen_resolution)
self.game.set_seed(self.rng.randint(0, 2**32 - 1))
if mode == 'algo':
self.game.set_window_visible(False)
elif mode == 'human' or mode == 'replay':
self.game.add_game_args('+freelook 1')
self.game.set_window_visible(True)
else:
raise Exception('Unsupported mode')
self._set_game_mode(mode)
def _game_init(self, with_locking=True, max_parallel=10):
lock_file = lock = None
if with_locking:
lock_file = doom_lock_file(max_parallel)
lock = FileLock(lock_file)
init_attempt = 0
while True:
init_attempt += 1
try:
if with_locking:
with lock.acquire(timeout=20):
self.game.init()
else:
self.game.init()
break
except Timeout:
if with_locking:
log.debug(
'Another process currently holds the lock %s, attempt: %d', lock_file, init_attempt,
)
except Exception as exc:
log.warning('VizDoom game.init() threw an exception %r. Terminate process...', exc)
from envs.env_utils import EnvCriticalError
raise EnvCriticalError()
def initialize(self):
self._create_doom_game(self.mode)
# (optional) top-down view provided by the game engine
if self.show_automap:
self.game.set_automap_buffer_enabled(True)
self.game.set_automap_mode(AutomapMode.OBJECTS)
self.game.set_automap_rotate(False)
self.game.set_automap_render_textures(False)
# self.game.add_game_args("+am_restorecolors")
# self.game.add_game_args("+am_followplayer 1")
background_color = 'ffffff'
self.game.add_game_args('+viz_am_center 1')
self.game.add_game_args('+am_backcolor ' + background_color)
self.game.add_game_args('+am_tswallcolor dddddd')
# self.game.add_game_args("+am_showthingsprites 0")
self.game.add_game_args('+am_yourcolor ' + background_color)
self.game.add_game_args('+am_cheat 0')
self.game.add_game_args('+am_thingcolor 0000ff') # player color
self.game.add_game_args('+am_thingcolor_item 00ff00')
# self.game.add_game_args("+am_thingcolor_citem 00ff00")
self._game_init()
self.initialized = True
def _ensure_initialized(self):
if not self.initialized:
self.initialize()
@staticmethod
def _parse_variable_indices(config):
with open(config, 'r') as config_file:
lines = config_file.readlines()
lines = [l.strip() for l in lines]
variable_indices = {}
for line in lines:
if line.startswith('#'):
continue # comment
variables_syntax = r'available_game_variables[\s]*=[\s]*\{(.*)\}'
match = re.match(variables_syntax, line)
if match is not None:
variables_str = match.groups()[0]
variables_str = variables_str.strip()
variables = variables_str.split(' ')
for i, variable in enumerate(variables):
variable_indices[variable] = i
break
return variable_indices
def _black_screen(self):
if self.black_screen is None:
self.black_screen = np.zeros(self.observation_space.shape, dtype=np.uint8)
return self.black_screen
def _game_variables_dict(self, state):
game_variables = state.game_variables
variables = {}
for variable, idx in self.variable_indices.items():
variables[variable] = game_variables[idx]
return variables
def demo_path(self, episode_idx):
demo_name = f'e{episode_idx:03d}.lmp'
demo_path = join(self.record_to, demo_name)
demo_path = os.path.normpath(demo_path)
return demo_path
def reset(self):
self._ensure_initialized()
if self.record_to is not None and not self.is_multiplayer:
# does not work in multiplayer (uses different mechanism)
if not os.path.exists(self.record_to):
os.makedirs(self.record_to)
demo_path = self.demo_path(self._num_episodes)
log.warning('Recording episode demo to %s', demo_path)
self.game.new_episode(demo_path)
else:
if self._num_episodes > 0:
# no demo recording (default)
self.game.new_episode()
self.state = self.game.get_state()
img = None
try:
img = self.state.screen_buffer
except AttributeError:
# sometimes Doom does not return screen buffer at all??? Rare bug
pass
if img is None:
log.error('Game returned None screen buffer! This is not supposed to happen!')
img = self._black_screen()
# Swap current and previous histogram
if self.current_histogram is not None and self.previous_histogram is not None:
swap = self.current_histogram
self.current_histogram = self.previous_histogram
self.previous_histogram = swap
self.current_histogram.fill(0)
self._actions_flattened = None
self._last_episode_info = copy.deepcopy(self._prev_info)
self._prev_info = None
self._num_episodes += 1
return np.transpose(img, (1, 2, 0))
def _convert_actions(self, actions):
"""Convert actions from gym action space to the action space expected by Doom game."""
if self.composite_action_space:
# composite action space with multiple subspaces
spaces = self.action_space.spaces
else:
# simple action space, e.g. Discrete. We still treat it like composite of length 1
spaces = (self.action_space, )
actions = (actions, )
actions_flattened = []
for i, action in enumerate(actions):
if isinstance(spaces[i], Discretized):
# discretized continuous action
# check discretized first because it's a subclass of gym.spaces.Discrete
# the order of if clauses here matters! DON'T CHANGE THE ORDER OF IFS!
continuous_action = spaces[i].to_continuous(action)
actions_flattened.append(continuous_action)
elif isinstance(spaces[i], gym.spaces.Discrete):
# standard discrete action
num_non_idle_actions = spaces[i].n - 1
action_one_hot = np.zeros(num_non_idle_actions, dtype=np.uint8)
if action > 0:
action_one_hot[action - 1] = 1 # 0th action in each subspace is a no-op
actions_flattened.extend(action_one_hot)
elif isinstance(spaces[i], gym.spaces.Box):
# continuous action
actions_flattened.extend(list(action * self.delta_actions_scaling_factor))
else:
raise NotImplementedError(f'Action subspace type {type(spaces[i])} is not supported!')
return actions_flattened
def _vizdoom_variables_bug_workaround(self, info, done):
"""Some variables don't get reset to zero on game.new_episode(). This fixes it (also check overflow?)."""
if done and 'DAMAGECOUNT' in info:
log.info('DAMAGECOUNT value on done: %r', info.get('DAMAGECOUNT'))
if self._last_episode_info is not None:
bugged_vars = ['DEATHCOUNT', 'HITCOUNT', 'DAMAGECOUNT']
for v in bugged_vars:
if v in info:
info[v] -= self._last_episode_info.get(v, 0)
def _process_game_step(self, state, done, info):
if not done:
observation = np.transpose(state.screen_buffer, (1, 2, 0))
game_variables = self._game_variables_dict(state)
info.update(self.get_info(game_variables))
self._update_histogram(info)
self._prev_info = copy.deepcopy(info)
else:
observation = self._black_screen()
# when done=True Doom does not allow us to call get_info, so we provide info from the last frame
info.update(self._prev_info)
self._vizdoom_variables_bug_workaround(info, done)
return observation, done, info
def step(self, actions):
"""
Action is either a single value (discrete, one-hot), or a tuple with an action for each of the
discrete action subspaces.
"""
if self._actions_flattened is not None:
# provided externally, e.g. via human play
actions_flattened = self._actions_flattened
self._actions_flattened = None
else:
actions_flattened = self._convert_actions(actions)
default_info = {'num_frames': self.skip_frames}
reward = self.game.make_action(actions_flattened, self.skip_frames)
state = self.game.get_state()
done = self.game.is_episode_finished()
observation, done, info = self._process_game_step(state, done, default_info)
return observation, reward, done, info
def render(self, mode='human'):
try:
img = self.game.get_state().screen_buffer
img = np.transpose(img, [1, 2, 0])
if mode == 'rgb_array':
return img
h, w = img.shape[:2]
render_w = 1280
if w < render_w:
render_h = int(render_w * h / w)
img = cv2.resize(img, (render_w, render_h))
if self.viewer is None:
from gym.envs.classic_control import rendering
self.viewer = rendering.SimpleImageViewer(maxwidth=render_w)
self.viewer.imshow(img)
return img
except AttributeError:
return None
def close(self):
try:
if self.game is not None:
self.game.close()
except RuntimeError as exc:
log.warning('Runtime error in VizDoom game close(): %r', exc)
if self.viewer is not None:
self.viewer.close()
def get_info(self, variables=None):
if variables is None:
variables = self._game_variables_dict(self.game.get_state())
info_dict = {'pos': self.get_positions(variables)}
info_dict.update(variables)
return info_dict
def get_info_all(self, variables=None):
if variables is None:
variables = self._game_variables_dict(self.game.get_state())
info = self.get_info(variables)
if self.previous_histogram is not None:
info['previous_histogram'] = self.previous_histogram
return info
def get_positions(self, variables):
return self._get_positions(variables)
@staticmethod
def _get_positions(variables):
have_coord_data = True
required_vars = ['POSITION_X', 'POSITION_Y', 'ANGLE']
for required_var in required_vars:
if required_var not in variables:
have_coord_data = False
break
x = y = a = np.nan
if have_coord_data:
x = variables['POSITION_X']
y = variables['POSITION_Y']
a = variables['ANGLE']
return {'agent_x': x, 'agent_y': y, 'agent_a': a}
def get_automap_buffer(self):
if self.game.is_episode_finished():
return None
state = self.game.get_state()
map_ = state.automap_buffer
map_ = np.swapaxes(map_, 0, 2)
map_ = np.swapaxes(map_, 0, 1)
return map_
def _update_histogram(self, info, eps=1e-8):
if self.current_histogram is None:
return
agent_x, agent_y = info['pos']['agent_x'], info['pos']['agent_y']
# Get agent coordinates normalized to [0, 1]
dx = (agent_x - self.coord_limits[0]) / (self.coord_limits[2] - self.coord_limits[0])
dy = (agent_y - self.coord_limits[1]) / (self.coord_limits[3] - self.coord_limits[1])
# Rescale coordinates to histogram dimensions
# Subtract eps to exclude upper bound of dx, dy
dx = int((dx - eps) * self.current_histogram.shape[0])
dy = int((dy - eps) * self.current_histogram.shape[1])
self.current_histogram[dx, dy] += 1
def _key_to_action(self, key):
if hasattr(self.action_space, 'key_to_action'):
return self.action_space.key_to_action(key)
else:
return key_to_action_default(key)
def _keyboard_on_press(self, key):
from pynput.keyboard import Key
if key == Key.esc:
self._terminate = True
return False
action = self._key_to_action(key)
if action is not None:
if action not in self._current_actions:
self._current_actions.append(action)
def _keyboard_on_release(self, key):
action = self._key_to_action(key)
if action is not None:
if action in self._current_actions:
self._current_actions.remove(action)
# noinspection PyProtectedMember
@staticmethod
def play_human_mode(env, skip_frames=1, num_episodes=3, num_actions=None):
from pynput.keyboard import Listener
doom = env.unwrapped
doom.skip_frames = 1 # handled by this script separately
# noinspection PyProtectedMember
def start_listener():
with Listener(on_press=doom._keyboard_on_press, on_release=doom._keyboard_on_release) as listener:
listener.join()
listener_thread = Thread(target=start_listener)
listener_thread.start()
for episode in range(num_episodes):
doom.mode = 'human'
env.reset()
last_render_time = time.time()
time_between_frames = 1.0 / 35.0
total_rew = 0.0
while not doom.game.is_episode_finished() and not doom._terminate:
num_actions = 14 if num_actions is None else num_actions
turn_delta_action_idx = num_actions - 1
actions = [0] * num_actions
for action in doom._current_actions:
if isinstance(action, int):
actions[action] = 1 # 1 for buttons currently pressed, 0 otherwise
else:
if action == 'turn_left':
actions[turn_delta_action_idx] = -doom.delta_actions_scaling_factor
elif action == 'turn_right':
actions[turn_delta_action_idx] = doom.delta_actions_scaling_factor
for frame in range(skip_frames):
doom._actions_flattened = actions
_, rew, _, _ = env.step(actions)
new_total_rew = total_rew + rew
if new_total_rew != total_rew:
log.info('Reward: %.3f, total: %.3f', rew, new_total_rew)
total_rew = new_total_rew
state = doom.game.get_state()
verbose = True
if state is not None and verbose:
info = doom.get_info()
print(
'Health:', info['HEALTH'],
# 'Weapon:', info['SELECTED_WEAPON'],
# 'ready:', info['ATTACK_READY'],
# 'ammo:', info['SELECTED_WEAPON_AMMO'],
# 'pc:', info['PLAYER_COUNT'],
# 'dmg:', info['DAMAGECOUNT'],
)
time_since_last_render = time.time() - last_render_time
time_wait = time_between_frames - time_since_last_render
if doom.show_automap and state.automap_buffer is not None:
map_ = state.automap_buffer
map_ = np.swapaxes(map_, 0, 2)
map_ = np.swapaxes(map_, 0, 1)
cv2.imshow('ViZDoom Automap Buffer', map_)
if time_wait > 0:
cv2.waitKey(int(time_wait) * 1000)
else:
if time_wait > 0:
time.sleep(time_wait)
last_render_time = time.time()
if doom.show_automap:
cv2.destroyAllWindows()
log.debug('Press ESC to exit...')
listener_thread.join()
# noinspection PyProtectedMember
@staticmethod
def replay(env, rec_path):
doom = env.unwrapped
doom.mode = 'replay'
doom._ensure_initialized()
doom.game.replay_episode(rec_path)
episode_reward = 0
start = time.time()
while not doom.game.is_episode_finished():
doom.game.advance_action()
r = doom.game.get_last_reward()
episode_reward += r
log.info('Episode reward: %.3f, time so far: %.1f s', episode_reward, time.time() - start)
log.info('Finishing replay')
doom.close()
|
[
"vizdoom.vizdoom.DoomGame",
"utils.utils.log.warning",
"utils.utils.log.info",
"cv2.imshow",
"os.path.join",
"gym.utils.seeding.np_random",
"numpy.zeros_like",
"os.path.dirname",
"numpy.transpose",
"os.path.exists",
"utils.utils.log.debug",
"gym.utils.seeding.hash_seed",
"os.path.normpath",
"numpy.swapaxes",
"cv2.destroyAllWindows",
"cv2.resize",
"gym.envs.classic_control.rendering.SimpleImageViewer",
"threading.Thread",
"copy.deepcopy",
"envs.env_utils.EnvCriticalError",
"pynput.keyboard.Listener",
"re.match",
"time.sleep",
"utils.utils.project_tmp_dir",
"os.makedirs",
"filelock.FileLock",
"numpy.zeros",
"time.time",
"random.randrange",
"gym.spaces.Box",
"utils.utils.log.error"
] |
[((1128, 1145), 'utils.utils.project_tmp_dir', 'project_tmp_dir', ([], {}), '()\n', (1143, 1145), False, 'from utils.utils import log, project_tmp_dir\n'), ((1162, 1190), 'os.path.join', 'join', (['tmp_dir', 'lock_filename'], {}), '(tmp_dir, lock_filename)\n', (1166, 1190), False, 'from os.path import join\n'), ((3471, 3503), 'os.path.join', 'join', (['scenarios_dir', 'config_file'], {}), '(scenarios_dir, config_file)\n', (3475, 3503), False, 'from os.path import join\n'), ((5063, 5099), 'gym.utils.seeding.hash_seed', 'seeding.hash_seed', (['seed'], {'max_bytes': '(4)'}), '(seed, max_bytes=4)\n', (5080, 5099), False, 'from gym.utils import seeding\n'), ((5122, 5160), 'gym.utils.seeding.np_random', 'seeding.np_random', ([], {'seed': 'self.curr_seed'}), '(seed=self.curr_seed)\n', (5139, 5160), False, 'from gym.utils import seeding\n'), ((5275, 5365), 'gym.spaces.Box', 'gym.spaces.Box', (['(0)', '(255)', '(self.screen_h, self.screen_w, self.channels)'], {'dtype': 'np.uint8'}), '(0, 255, (self.screen_h, self.screen_w, self.channels), dtype\n =np.uint8)\n', (5289, 5365), False, 'import gym\n'), ((5813, 5823), 'vizdoom.vizdoom.DoomGame', 'DoomGame', ([], {}), '()\n', (5821, 5823), False, 'from vizdoom.vizdoom import ScreenResolution, DoomGame, Mode, AutomapMode\n'), ((9939, 9970), 'os.path.join', 'join', (['self.record_to', 'demo_name'], {}), '(self.record_to, demo_name)\n', (9943, 9970), False, 'from os.path import join\n'), ((9991, 10018), 'os.path.normpath', 'os.path.normpath', (['demo_path'], {}), '(demo_path)\n', (10007, 10018), False, 'import os\n'), ((11442, 11472), 'copy.deepcopy', 'copy.deepcopy', (['self._prev_info'], {}), '(self._prev_info)\n', (11455, 11472), False, 'import copy\n'), ((11553, 11581), 'numpy.transpose', 'np.transpose', (['img', '(1, 2, 0)'], {}), '(img, (1, 2, 0))\n', (11565, 11581), True, 'import numpy as np\n'), ((17710, 17733), 'numpy.swapaxes', 'np.swapaxes', (['map_', '(0)', '(2)'], {}), '(map_, 0, 2)\n', (17721, 17733), True, 'import numpy as np\n'), ((17749, 17772), 'numpy.swapaxes', 'np.swapaxes', (['map_', '(0)', '(1)'], {}), '(map_, 0, 1)\n', (17760, 17772), True, 'import numpy as np\n'), ((19791, 19820), 'threading.Thread', 'Thread', ([], {'target': 'start_listener'}), '(target=start_listener)\n', (19797, 19820), False, 'from threading import Thread\n'), ((22663, 22696), 'utils.utils.log.debug', 'log.debug', (['"""Press ESC to exit..."""'], {}), "('Press ESC to exit...')\n", (22672, 22696), False, 'from utils.utils import log, project_tmp_dir\n'), ((22995, 23006), 'time.time', 'time.time', ([], {}), '()\n', (23004, 23006), False, 'import time\n'), ((23286, 23314), 'utils.utils.log.info', 'log.info', (['"""Finishing replay"""'], {}), "('Finishing replay')\n", (23294, 23314), False, 'from utils.utils import log, project_tmp_dir\n'), ((1064, 1097), 'random.randrange', 'random.randrange', (['(0)', 'max_parallel'], {}), '(0, max_parallel)\n', (1080, 1097), False, 'import random\n'), ((3404, 3429), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (3419, 3429), False, 'import os\n'), ((4570, 4610), 'numpy.zeros', 'np.zeros', (['(len_x, len_y)'], {'dtype': 'np.int32'}), '((len_x, len_y), dtype=np.int32)\n', (4578, 4610), True, 'import numpy as np\n'), ((4649, 4686), 'numpy.zeros_like', 'np.zeros_like', (['self.current_histogram'], {}), '(self.current_histogram)\n', (4662, 4686), True, 'import numpy as np\n'), ((6509, 6528), 'filelock.FileLock', 'FileLock', (['lock_file'], {}), '(lock_file)\n', (6517, 6528), False, 'from filelock import FileLock, Timeout\n'), ((9007, 9039), 're.match', 're.match', (['variables_syntax', 'line'], {}), '(variables_syntax, line)\n', (9015, 9039), False, 'import re\n'), ((9494, 9548), 'numpy.zeros', 'np.zeros', (['self.observation_space.shape'], {'dtype': 'np.uint8'}), '(self.observation_space.shape, dtype=np.uint8)\n', (9502, 9548), True, 'import numpy as np\n'), ((10406, 10460), 'utils.utils.log.warning', 'log.warning', (['"""Recording episode demo to %s"""', 'demo_path'], {}), "('Recording episode demo to %s', demo_path)\n", (10417, 10460), False, 'from utils.utils import log, project_tmp_dir\n'), ((10927, 11005), 'utils.utils.log.error', 'log.error', (['"""Game returned None screen buffer! This is not supposed to happen!"""'], {}), "('Game returned None screen buffer! This is not supposed to happen!')\n", (10936, 11005), False, 'from utils.utils import log, project_tmp_dir\n'), ((13938, 13982), 'numpy.transpose', 'np.transpose', (['state.screen_buffer', '(1, 2, 0)'], {}), '(state.screen_buffer, (1, 2, 0))\n', (13950, 13982), True, 'import numpy as np\n'), ((14171, 14190), 'copy.deepcopy', 'copy.deepcopy', (['info'], {}), '(info)\n', (14184, 14190), False, 'import copy\n'), ((15447, 15475), 'numpy.transpose', 'np.transpose', (['img', '[1, 2, 0]'], {}), '(img, [1, 2, 0])\n', (15459, 15475), True, 'import numpy as np\n'), ((19985, 19996), 'time.time', 'time.time', ([], {}), '()\n', (19994, 19996), False, 'import time\n'), ((5533, 5642), 'utils.utils.log.info', 'log.info', (['"""Starting in async mode! Use this only for testing, otherwise PLAYER mode is much faster"""'], {}), "(\n 'Starting in async mode! Use this only for testing, otherwise PLAYER mode is much faster'\n )\n", (5541, 5642), False, 'from utils.utils import log, project_tmp_dir\n'), ((10258, 10288), 'os.path.exists', 'os.path.exists', (['self.record_to'], {}), '(self.record_to)\n', (10272, 10288), False, 'import os\n'), ((10306, 10333), 'os.makedirs', 'os.makedirs', (['self.record_to'], {}), '(self.record_to)\n', (10317, 10333), False, 'import os\n'), ((15702, 15739), 'cv2.resize', 'cv2.resize', (['img', '(render_w, render_h)'], {}), '(img, (render_w, render_h))\n', (15712, 15739), False, 'import cv2\n'), ((15870, 15916), 'gym.envs.classic_control.rendering.SimpleImageViewer', 'rendering.SimpleImageViewer', ([], {'maxwidth': 'render_w'}), '(maxwidth=render_w)\n', (15897, 15916), False, 'from gym.envs.classic_control import rendering\n'), ((16186, 16247), 'utils.utils.log.warning', 'log.warning', (['"""Runtime error in VizDoom game close(): %r"""', 'exc'], {}), "('Runtime error in VizDoom game close(): %r', exc)\n", (16197, 16247), False, 'from utils.utils import log, project_tmp_dir\n'), ((19638, 19723), 'pynput.keyboard.Listener', 'Listener', ([], {'on_press': 'doom._keyboard_on_press', 'on_release': 'doom._keyboard_on_release'}), '(on_press=doom._keyboard_on_press, on_release=doom._keyboard_on_release\n )\n', (19646, 19723), False, 'from pynput.keyboard import Listener\n'), ((22630, 22653), 'cv2.destroyAllWindows', 'cv2.destroyAllWindows', ([], {}), '()\n', (22651, 22653), False, 'import cv2\n'), ((7105, 7192), 'utils.utils.log.warning', 'log.warning', (['"""VizDoom game.init() threw an exception %r. Terminate process..."""', 'exc'], {}), "('VizDoom game.init() threw an exception %r. Terminate process...',\n exc)\n", (7116, 7192), False, 'from utils.utils import log, project_tmp_dir\n'), ((7271, 7289), 'envs.env_utils.EnvCriticalError', 'EnvCriticalError', ([], {}), '()\n', (7287, 7289), False, 'from envs.env_utils import EnvCriticalError\n'), ((12726, 12772), 'numpy.zeros', 'np.zeros', (['num_non_idle_actions'], {'dtype': 'np.uint8'}), '(num_non_idle_actions, dtype=np.uint8)\n', (12734, 12772), True, 'import numpy as np\n'), ((22567, 22578), 'time.time', 'time.time', ([], {}), '()\n', (22576, 22578), False, 'import time\n'), ((23256, 23267), 'time.time', 'time.time', ([], {}), '()\n', (23265, 23267), False, 'import time\n'), ((6910, 7008), 'utils.utils.log.debug', 'log.debug', (['"""Another process currently holds the lock %s, attempt: %d"""', 'lock_file', 'init_attempt'], {}), "('Another process currently holds the lock %s, attempt: %d',\n lock_file, init_attempt)\n", (6919, 7008), False, 'from utils.utils import log, project_tmp_dir\n'), ((21123, 21180), 'utils.utils.log.info', 'log.info', (['"""Reward: %.3f, total: %.3f"""', 'rew', 'new_total_rew'], {}), "('Reward: %.3f, total: %.3f', rew, new_total_rew)\n", (21131, 21180), False, 'from utils.utils import log, project_tmp_dir\n'), ((21887, 21898), 'time.time', 'time.time', ([], {}), '()\n', (21896, 21898), False, 'import time\n'), ((22158, 22181), 'numpy.swapaxes', 'np.swapaxes', (['map_', '(0)', '(2)'], {}), '(map_, 0, 2)\n', (22169, 22181), True, 'import numpy as np\n'), ((22213, 22236), 'numpy.swapaxes', 'np.swapaxes', (['map_', '(0)', '(1)'], {}), '(map_, 0, 1)\n', (22224, 22236), True, 'import numpy as np\n'), ((22261, 22303), 'cv2.imshow', 'cv2.imshow', (['"""ViZDoom Automap Buffer"""', 'map_'], {}), "('ViZDoom Automap Buffer', map_)\n", (22271, 22303), False, 'import cv2\n'), ((22505, 22526), 'time.sleep', 'time.sleep', (['time_wait'], {}), '(time_wait)\n', (22515, 22526), False, 'import time\n')]
|
import unittest
import tensorflow.contrib.keras as keras
import numpy as np
from vixstructure.models import term_structure_to_spread_price, term_structure_to_spread_price_v2
from vixstructure.models import term_structure_to_single_spread_price
from vixstructure.models import mask_output
from vixstructure.data import LongPricesDataset
class TestModels(unittest.TestCase):
def setUp(self):
self.dataset = LongPricesDataset("../../data/8_m_settle.csv", "../../data/expirations.csv")
def test_term_structure_to_spread_price(self):
model = term_structure_to_spread_price(5, 9)
self.assertEqual(len(model.layers), 7)
def test_mask_output_function_for_lambda_layers(self):
input = keras.layers.Input(shape=(9,))
output = keras.layers.Lambda(mask_output)(input)
model = keras.models.Model(inputs=input, outputs=output)
x, y = self.dataset.dataset()
preds = model.predict(x)
self.assertEqual(preds.shape, (2655, 6))
self.assertEqual(np.all(preds, axis=0).sum(), 5)
self.assertEqual(np.all(preds, axis=1).sum(), 2529)
self.assertEqual((preds == 0.).sum(), 126)
def test_term_structure_to_spread_prices_v2(self):
model = term_structure_to_spread_price_v2(5, 9)
x, y = self.dataset.dataset()
preds = model.predict(x)
self.assertEqual(preds.shape, (2655, 6))
self.assertEqual(np.all(preds, axis=0).sum(), 5)
self.assertEqual(np.all(preds, axis=1).sum(), 2529)
def test_term_structure_to_single_spread_price(self):
"""Just test model construction."""
model = term_structure_to_single_spread_price(5, 9)
self.assertEqual([layer.output_shape[1] for layer in model.layers], [8, 9, 9, 9, 9, 9, 1])
for distribution in (layer.kernel_initializer.distribution for layer in model.layers
if isinstance(layer, keras.layers.Dense)):
self.assertEqual(distribution, "uniform")
model_reduced_widths = term_structure_to_single_spread_price(5, 9, reduce_width=True)
self.assertEqual([layer.output_shape[1] for layer in model_reduced_widths.layers], [8, 9, 7, 6, 4, 3, 1])
for distribution in (layer.kernel_initializer.distribution for layer in model_reduced_widths.layers
if isinstance(layer, keras.layers.Dense)):
self.assertEqual(distribution, "uniform")
def test_term_structure_to_single_spread_price_with_selu(self):
model = term_structure_to_single_spread_price(5, 9, activation_function="selu")
self.assertEqual([layer.output_shape[1] for layer in model.layers], [8, 9, 9, 9, 9, 9, 1])
vars = [np.square(layer.kernel_initializer.stddev) for layer in model.layers
if isinstance(layer, keras.layers.Dense)]
self.assertAlmostEqual(1 / vars[0], 8 / 2)
for fst, snd in zip(vars[1:], [9, 9, 9, 9, 9]):
self.assertAlmostEqual(1 / fst, snd)
model_reduced_widths = term_structure_to_single_spread_price(5, 9, reduce_width=True, activation_function="selu")
self.assertEqual([layer.output_shape[1] for layer in model_reduced_widths.layers], [8, 9, 7, 6, 4, 3, 1])
vars_reduced_widths = [np.square(layer.kernel_initializer.stddev) for layer in model_reduced_widths.layers
if isinstance(layer, keras.layers.Dense)]
self.assertAlmostEqual(1 / vars[0], 8 / 2)
for fst, snd in zip(vars_reduced_widths[1:], [9, 7, 6, 4, 3]):
self.assertAlmostEqual(1 / fst, snd)
if __name__ == '__main__':
unittest.main()
|
[
"unittest.main",
"numpy.square",
"vixstructure.models.term_structure_to_single_spread_price",
"tensorflow.contrib.keras.layers.Lambda",
"numpy.all",
"tensorflow.contrib.keras.layers.Input",
"tensorflow.contrib.keras.models.Model",
"vixstructure.models.term_structure_to_spread_price_v2",
"vixstructure.data.LongPricesDataset",
"vixstructure.models.term_structure_to_spread_price"
] |
[((3622, 3637), 'unittest.main', 'unittest.main', ([], {}), '()\n', (3635, 3637), False, 'import unittest\n'), ((421, 497), 'vixstructure.data.LongPricesDataset', 'LongPricesDataset', (['"""../../data/8_m_settle.csv"""', '"""../../data/expirations.csv"""'], {}), "('../../data/8_m_settle.csv', '../../data/expirations.csv')\n", (438, 497), False, 'from vixstructure.data import LongPricesDataset\n'), ((566, 602), 'vixstructure.models.term_structure_to_spread_price', 'term_structure_to_spread_price', (['(5)', '(9)'], {}), '(5, 9)\n', (596, 602), False, 'from vixstructure.models import term_structure_to_spread_price, term_structure_to_spread_price_v2\n'), ((726, 756), 'tensorflow.contrib.keras.layers.Input', 'keras.layers.Input', ([], {'shape': '(9,)'}), '(shape=(9,))\n', (744, 756), True, 'import tensorflow.contrib.keras as keras\n'), ((830, 878), 'tensorflow.contrib.keras.models.Model', 'keras.models.Model', ([], {'inputs': 'input', 'outputs': 'output'}), '(inputs=input, outputs=output)\n', (848, 878), True, 'import tensorflow.contrib.keras as keras\n'), ((1239, 1278), 'vixstructure.models.term_structure_to_spread_price_v2', 'term_structure_to_spread_price_v2', (['(5)', '(9)'], {}), '(5, 9)\n', (1272, 1278), False, 'from vixstructure.models import term_structure_to_spread_price, term_structure_to_spread_price_v2\n'), ((1635, 1678), 'vixstructure.models.term_structure_to_single_spread_price', 'term_structure_to_single_spread_price', (['(5)', '(9)'], {}), '(5, 9)\n', (1672, 1678), False, 'from vixstructure.models import term_structure_to_single_spread_price\n'), ((2028, 2090), 'vixstructure.models.term_structure_to_single_spread_price', 'term_structure_to_single_spread_price', (['(5)', '(9)'], {'reduce_width': '(True)'}), '(5, 9, reduce_width=True)\n', (2065, 2090), False, 'from vixstructure.models import term_structure_to_single_spread_price\n'), ((2524, 2595), 'vixstructure.models.term_structure_to_single_spread_price', 'term_structure_to_single_spread_price', (['(5)', '(9)'], {'activation_function': '"""selu"""'}), "(5, 9, activation_function='selu')\n", (2561, 2595), False, 'from vixstructure.models import term_structure_to_single_spread_price\n'), ((3025, 3119), 'vixstructure.models.term_structure_to_single_spread_price', 'term_structure_to_single_spread_price', (['(5)', '(9)'], {'reduce_width': '(True)', 'activation_function': '"""selu"""'}), "(5, 9, reduce_width=True,\n activation_function='selu')\n", (3062, 3119), False, 'from vixstructure.models import term_structure_to_single_spread_price\n'), ((774, 806), 'tensorflow.contrib.keras.layers.Lambda', 'keras.layers.Lambda', (['mask_output'], {}), '(mask_output)\n', (793, 806), True, 'import tensorflow.contrib.keras as keras\n'), ((2711, 2753), 'numpy.square', 'np.square', (['layer.kernel_initializer.stddev'], {}), '(layer.kernel_initializer.stddev)\n', (2720, 2753), True, 'import numpy as np\n'), ((3261, 3303), 'numpy.square', 'np.square', (['layer.kernel_initializer.stddev'], {}), '(layer.kernel_initializer.stddev)\n', (3270, 3303), True, 'import numpy as np\n'), ((1024, 1045), 'numpy.all', 'np.all', (['preds'], {'axis': '(0)'}), '(preds, axis=0)\n', (1030, 1045), True, 'import numpy as np\n'), ((1081, 1102), 'numpy.all', 'np.all', (['preds'], {'axis': '(1)'}), '(preds, axis=1)\n', (1087, 1102), True, 'import numpy as np\n'), ((1424, 1445), 'numpy.all', 'np.all', (['preds'], {'axis': '(0)'}), '(preds, axis=0)\n', (1430, 1445), True, 'import numpy as np\n'), ((1481, 1502), 'numpy.all', 'np.all', (['preds'], {'axis': '(1)'}), '(preds, axis=1)\n', (1487, 1502), True, 'import numpy as np\n')]
|
from sklearn.utils.sparsefuncs import mean_variance_axis
from scipy.sparse import issparse
from scipy.special import loggamma
import numpy as np
def log_binom(n, k):
"""
log (n choose k)
Parameters
----------
n, k: int
Output
------
log_binom: float
"""
return loggamma(n + 1) - loggamma(k + 1) - loggamma(n - k + 1)
# TODO: add this test
# import numpy as np
# from scipy.special import binom
# n = 10
# k = 3
# abs(np.log(binom(n, k)) - log_binom(n, k)) < 1e-8
def weighted_mean_std(X, sample_weight=None, ddof=0):
"""
Computes possible weighted mean and standard deviations of each column of a data matrix. It is safe to call this function on either a sparse or dense matrix.
Parameters
-----------
X: array-like, shape (n_samples, n_features)
The data matrix.
sample_weight: None, array-like shape (n_samples)
The optional sample weights to use.
ddof: int
The divisor used in calculations
is ``TOT_WEIGHT - ddof``, where ``TOT_WEIGHT`` is the total weight.
If sample_weight is None or norm_weight=True then TOT_WEIGHT = n_samples.
Otherwise, TOT_WEIGHT = sample_weight.sum()
Output
------
mean, std
mean: array-like, shape (n_features, )
The weighted mean for each feature.
std: array-like, shape (n_features, )
The weighted standard deviation for each feature.
"""
n_samples = X.shape[0]
# process sample weights
if sample_weight is not None:
_sample_weight = np.array(sample_weight).reshape(-1).astype(X.dtype)
assert len(_sample_weight) == n_samples
# normalize the weights
_sample_weight /= _sample_weight.sum()
_sample_weight *= n_samples
TOT_WEIGHT = _sample_weight.sum()
else:
TOT_WEIGHT = n_samples
_sample_weight = None
# sklearn has this built in for sparse matrices
# TODO: can we find this somewhere for dense?
if issparse(X):
# TODO: handle ddof
MEAN, VAR, SUM_WEIGHTS = \
mean_variance_axis(X=X, axis=0, weights=_sample_weight,
return_sum_weights=True)
VAR *= SUM_WEIGHTS / (TOT_WEIGHT - ddof)
return MEAN, np.sqrt(VAR)
# unweighted, dense case
if sample_weight is None:
return X.mean(axis=0), X.std(axis=0, ddof=ddof)
else: # weighted, dense case
MEAN = X.T @ _sample_weight / TOT_WEIGHT
VAR = ((X - MEAN) ** 2).T @ _sample_weight
VAR = VAR / (TOT_WEIGHT - ddof)
return MEAN, np.sqrt(VAR)
|
[
"scipy.special.loggamma",
"scipy.sparse.issparse",
"numpy.array",
"sklearn.utils.sparsefuncs.mean_variance_axis",
"numpy.sqrt"
] |
[((1997, 2008), 'scipy.sparse.issparse', 'issparse', (['X'], {}), '(X)\n', (2005, 2008), False, 'from scipy.sparse import issparse\n'), ((341, 360), 'scipy.special.loggamma', 'loggamma', (['(n - k + 1)'], {}), '(n - k + 1)\n', (349, 360), False, 'from scipy.special import loggamma\n'), ((2086, 2171), 'sklearn.utils.sparsefuncs.mean_variance_axis', 'mean_variance_axis', ([], {'X': 'X', 'axis': '(0)', 'weights': '_sample_weight', 'return_sum_weights': '(True)'}), '(X=X, axis=0, weights=_sample_weight, return_sum_weights=True\n )\n', (2104, 2171), False, 'from sklearn.utils.sparsefuncs import mean_variance_axis\n'), ((305, 320), 'scipy.special.loggamma', 'loggamma', (['(n + 1)'], {}), '(n + 1)\n', (313, 320), False, 'from scipy.special import loggamma\n'), ((323, 338), 'scipy.special.loggamma', 'loggamma', (['(k + 1)'], {}), '(k + 1)\n', (331, 338), False, 'from scipy.special import loggamma\n'), ((2269, 2281), 'numpy.sqrt', 'np.sqrt', (['VAR'], {}), '(VAR)\n', (2276, 2281), True, 'import numpy as np\n'), ((2595, 2607), 'numpy.sqrt', 'np.sqrt', (['VAR'], {}), '(VAR)\n', (2602, 2607), True, 'import numpy as np\n'), ((1556, 1579), 'numpy.array', 'np.array', (['sample_weight'], {}), '(sample_weight)\n', (1564, 1579), True, 'import numpy as np\n')]
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# A tf.keras implementation of ghostnet
#
#
import os, sys
import warnings
import math
from keras_applications.imagenet_utils import _obtain_input_shape
from keras_applications.imagenet_utils import preprocess_input as _preprocess_input
from tensorflow.keras.utils import get_source_inputs, get_file
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation
from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply
from tensorflow.keras import backend as K
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..'))
from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization
BASE_WEIGHT_PATH = (
'https://github.com/david8862/tf-keras-image-classifier/'
'releases/download/v1.0.0/')
def preprocess_input(x):
"""
"mode" option description in preprocess_input
mode: One of "caffe", "tf" or "torch".
- caffe: will convert the images from RGB to BGR,
then will zero-center each color channel with
respect to the ImageNet dataset,
without scaling.
- tf: will scale pixels between -1 and 1,
sample-wise.
- torch: will scale pixels between 0 and 1 and then
will normalize each channel with respect to the
ImageNet dataset.
"""
# here we use pytorch mode preprocess to align with origin
#x = _preprocess_input(x, mode='torch', backend=K)
x /= 255.
mean = [0.485, 0.456, 0.406]
std = [0.229, 0.224, 0.225]
x[..., 0] -= mean[0]
x[..., 1] -= mean[1]
x[..., 2] -= mean[2]
if std is not None:
x[..., 0] /= std[0]
x[..., 1] /= std[1]
x[..., 2] /= std[2]
return x
# This function is taken from the original tf repo.
# It ensures that all layers have a channel number that is divisible by 8
# It can be seen here:
# https://github.com/tensorflow/models/blob/master/research/slim/nets/mobilenet/mobilenet.py
def _make_divisible(v, divisor, min_value=None):
if min_value is None:
min_value = divisor
new_v = max(min_value, int(v + divisor / 2) // divisor * divisor)
# Make sure that round down does not go down by more than 10%.
if new_v < 0.9 * v:
new_v += divisor
return new_v
def hard_sigmoid(x):
return ReLU(6.0)(x + 3.0) / 6.0
def primary_conv(x, output_filters, kernel_size, strides=(1,1), padding='same', act=True, use_bias=False, name=None):
x = YoloConv2D(filters=output_filters,
kernel_size=kernel_size,
strides=strides,
padding=padding,
use_bias=use_bias,
name=name + '_0')(x)
x = CustomBatchNormalization(name=name+'_1')(x)
x = ReLU(name=name+'_relu')(x) if act else x
return x
def cheap_operations(x, output_filters, kernel_size, strides=(1,1), padding='same', act=True, use_bias=False, name=None):
x = YoloDepthwiseConv2D(kernel_size=kernel_size,
strides=strides,
padding=padding,
use_bias=use_bias,
name=name+'_0')(x)
x = CustomBatchNormalization(name=name+'_1')(x)
x = ReLU(name=name+'_relu')(x) if act else x
return x
def SqueezeExcite(input_x, se_ratio=0.25, reduced_base_chs=None, divisor=4, name=None):
reduce_chs =_make_divisible((reduced_base_chs or int(input_x.shape[-1]))*se_ratio, divisor)
x = GlobalAveragePooling2D(name=name+'_avg_pool2d')(input_x)
if K.image_data_format() == 'channels_first':
x = Reshape((int(input_x.shape[-1]), 1, 1))(x)
else:
x = Reshape((1, 1, int(input_x.shape[-1])))(x)
x = YoloConv2D(filters=reduce_chs, kernel_size=1, use_bias=True, name=name+'_conv_reduce')(x)
x = ReLU(name=name+'_act')(x)
x = YoloConv2D(filters=int(input_x.shape[-1]), kernel_size=1, use_bias=True, name=name+'_conv_expand')(x)
x = Activation(hard_sigmoid, name=name+'_hard_sigmoid')(x)
x = Multiply()([input_x, x])
return x
def ConvBnAct(input_x, out_chs, kernel_size, stride=(1,1), name=None):
x = YoloConv2D(filters=out_chs,
kernel_size=kernel_size,
strides=stride,
padding='valid',
use_bias=False,
name=name+'_conv')(input_x)
x = CustomBatchNormalization(name=name+'_bn1')(x)
x = ReLU(name=name+'_relu')(x)
return x
def GhostModule(input_x, output_chs, kernel_size=1, ratio=2, dw_size=3, stride=(1,1), act=True, name=None):
init_channels = int(math.ceil(output_chs / ratio))
new_channels = int(init_channels * (ratio - 1))
x1 = primary_conv(input_x,
init_channels,
kernel_size=kernel_size,
strides=stride,
padding='valid',
act=act,
name = name + '_primary_conv')
x2 = cheap_operations(x1,
new_channels,
kernel_size=dw_size,
strides=(1,1),
padding= 'same',
act=act,
name = name + '_cheap_operation')
x = Concatenate(axis=3,name=name+'_concat')([x1,x2])
return x
def GhostBottleneck(input_x, mid_chs, out_chs, dw_kernel_size=3, stride=(1,1), se_ratio=0., name=None):
'''ghostnet bottleneck w/optional se'''
has_se = se_ratio is not None and se_ratio > 0.
#1st ghost bottleneck
x = GhostModule(input_x, mid_chs, act=True, name=name+'_ghost1')
#depth_with convolution
if stride[0] > 1:
x = YoloDepthwiseConv2D(kernel_size=dw_kernel_size,
strides=stride,
padding='same',
use_bias=False,
name=name+'_conv_dw')(x)
x = CustomBatchNormalization(name=name+'_bn_dw')(x)
#Squeeze_and_excitation
if has_se:
x = SqueezeExcite(x, se_ratio=se_ratio, name=name+'_se')
#2nd ghost bottleneck
x = GhostModule(x, out_chs, act=False, name=name+'_ghost2')
#short cut
if (input_x.shape[-1] == out_chs and stride[0] == 1):
sc = input_x
else:
name1 = name + '_shortcut'
sc = YoloDepthwiseConv2D(kernel_size=dw_kernel_size,
strides=stride,
padding='same',
use_bias=False,
name=name1+'_0')(input_x)
sc = CustomBatchNormalization(name=name1+'_1')(sc)
sc = YoloConv2D(filters=out_chs,
kernel_size=1,
strides=(1,1),
padding='valid',
use_bias=False,
name=name1+'_2')(sc)
sc = CustomBatchNormalization(name=name1+'_3')(sc)
x = Add(name=name+'_add')([x, sc])
return x
DEFAULT_CFGS = [
# k, t, c, SE, s
# stage1
[[3, 16, 16, 0, 1]],
# stage2
[[3, 48, 24, 0, 2]],
[[3, 72, 24, 0, 1]],
# stage3
[[5, 72, 40, 0.25, 2]],
[[5, 120, 40, 0.25, 1]],
# stage4
[[3, 240, 80, 0, 2]],
[[3, 200, 80, 0, 1],
[3, 184, 80, 0, 1],
[3, 184, 80, 0, 1],
[3, 480, 112, 0.25, 1],
[3, 672, 112, 0.25, 1]
],
# stage5
[[5, 672, 160, 0.25, 2]],
[[5, 960, 160, 0, 1],
[5, 960, 160, 0.25, 1],
[5, 960, 160, 0, 1],
[5, 960, 160, 0.25, 1]
]
]
def GhostNet(input_shape=None,
include_top=True,
weights='imagenet',
input_tensor=None,
cfgs=DEFAULT_CFGS,
width=1.0,
dropout_rate=0.2,
pooling=None,
classes=1000,
**kwargs):
"""Instantiates the GhostNet architecture.
# Arguments
input_shape: optional shape tuple, to be specified if you would
like to use a model with an input img resolution that is not
(224, 224, 3).
It should have exactly 3 inputs channels (224, 224, 3).
You can also omit this option if you would like
to infer input_shape from an input_tensor.
If you choose to include both input_tensor and input_shape then
input_shape will be used if they match, if the shapes
do not match then we will throw an error.
E.g. `(160, 160, 3)` would be one valid value.
include_top: whether to include the fully-connected
layer at the top of the network.
weights: one of `None` (random initialization),
'imagenet' (pre-training on ImageNet),
or the path to the weights file to be loaded.
input_tensor: optional Keras tensor (i.e. output of
`layers.Input()`)
to use as image input for the model.
cfgs: model structure config list
width: controls the width of the network
dropout_rate: fraction of the input units to drop on the last layer
pooling: Optional pooling mode for feature extraction
when `include_top` is `False`.
- `None` means that the output of the model
will be the 4D tensor output of the
last convolutional block.
- `avg` means that global average pooling
will be applied to the output of the
last convolutional block, and thus
the output of the model will be a
2D tensor.
- `max` means that global max pooling will
be applied.
classes: optional number of classes to classify images
into, only to be specified if `include_top` is True, and
if no `weights` argument is specified.
# Returns
A Keras model instance.
# Raises
ValueError: in case of invalid argument for `weights`,
or invalid input shape or invalid alpha, rows when
weights='imagenet'
"""
if not (weights in {'imagenet', None} or os.path.exists(weights)):
raise ValueError('The `weights` argument should be either '
'`None` (random initialization), `imagenet` '
'(pre-training on ImageNet), '
'or the path to the weights file to be loaded.')
if weights == 'imagenet' and include_top and classes != 1000:
raise ValueError('If using `weights` as `"imagenet"` with `include_top` '
'as true, `classes` should be 1000')
# Determine proper input shape
input_shape = _obtain_input_shape(input_shape,
default_size=224,
min_size=32,
data_format=K.image_data_format(),
require_flatten=include_top,
weights=weights)
# If input_shape is None and input_tensor is None using standard shape
if input_shape is None and input_tensor is None:
input_shape = (None, None, 3)
if input_tensor is None:
img_input = Input(shape=input_shape)
else:
#if not K.is_keras_tensor(input_tensor):
#img_input = Input(tensor=input_tensor, shape=input_shape)
#else:
#img_input = input_tensor
img_input = input_tensor
channel_axis = 1 if K.image_data_format() == 'channels_first' else -1
# building first layer
output_channel = int(_make_divisible(16 * width, 4))
x = YoloConv2D(filters=output_channel,
kernel_size=3,
strides=(2, 2),
padding='same',
use_bias=False,
name='conv_stem')(img_input)
x = CustomBatchNormalization(name='bn1')(x)
x = ReLU(name='Conv2D_1_act')(x)
# building inverted residual blocks
for index, cfg in enumerate(cfgs):
sub_index = 0
for k,exp_size,c,se_ratio,s in cfg:
output_channel = int(_make_divisible(c * width, 4))
hidden_channel = int(_make_divisible(exp_size * width, 4))
x = GhostBottleneck(x, hidden_channel, output_channel, k, (s,s),
se_ratio=se_ratio,
name='blocks_'+str(index)+'_'+str(sub_index))
sub_index += 1
output_channel = _make_divisible(exp_size * width, 4)
x = ConvBnAct(x, output_channel, kernel_size=1, name='blocks_9_0')
if include_top:
x = GlobalAveragePooling2D(name='global_avg_pooling2D')(x)
if K.image_data_format() == 'channels_first':
x = Reshape((output_channel, 1, 1))(x)
else:
x = Reshape((1, 1, output_channel))(x)
# building last several layers
output_channel = 1280
x = YoloConv2D(filters=output_channel,
kernel_size=1,
strides=(1,1),
padding='valid',
use_bias=True,
name='conv_head')(x)
x = ReLU(name='relu_head')(x)
if dropout_rate > 0.:
x = Dropout(dropout_rate, name='dropout_1')(x)
x = Flatten()(x)
x = Dense(units=classes, activation='softmax',
use_bias=True, name='classifier')(x)
else:
if pooling == 'avg':
x = GlobalAveragePooling2D()(x)
elif pooling == 'max':
x = GlobalMaxPooling2D()(x)
# Ensure that the model takes into account
# any potential predecessors of `input_tensor`.
if input_tensor is not None:
inputs = get_source_inputs(input_tensor)
else:
inputs = img_input
# Create model.
model = Model(inputs, x, name='ghostnet_%0.2f' % (width))
# Load weights.
if weights == 'imagenet':
if include_top:
file_name = 'ghostnet_weights_tf_dim_ordering_tf_kernels_224.h5'
weight_path = BASE_WEIGHT_PATH + file_name
else:
file_name = 'ghostnet_weights_tf_dim_ordering_tf_kernels_224_no_top.h5'
weight_path = BASE_WEIGHT_PATH + file_name
weights_path = get_file(file_name, weight_path, cache_subdir='models')
model.load_weights(weights_path)
elif weights is not None:
model.load_weights(weights)
return model
if __name__ == '__main__':
input_tensor = Input(shape=(None, None, 3), name='image_input')
#model = GhostNet(include_top=False, input_tensor=input_tensor, weights='imagenet')
model = GhostNet(include_top=True, input_shape=(224, 224, 3), weights='imagenet')
model.summary()
K.set_learning_phase(0)
import numpy as np
from tensorflow.keras.applications.resnet50 import decode_predictions
from keras_preprocessing import image
img = image.load_img('../../example/eagle.jpg', target_size=(224, 224))
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
print('Predicted:', decode_predictions(preds))
|
[
"keras_preprocessing.image.load_img",
"tensorflow.keras.layers.Reshape",
"tensorflow.keras.layers.Dense",
"tensorflow.keras.layers.Multiply",
"common.backbones.layers.YoloConv2D",
"tensorflow.keras.backend.set_learning_phase",
"common.backbones.layers.YoloDepthwiseConv2D",
"tensorflow.keras.layers.Flatten",
"tensorflow.keras.layers.Concatenate",
"os.path.exists",
"tensorflow.keras.layers.Activation",
"tensorflow.keras.layers.Input",
"tensorflow.keras.utils.get_file",
"tensorflow.keras.layers.GlobalAveragePooling2D",
"tensorflow.keras.layers.Dropout",
"math.ceil",
"os.path.realpath",
"keras_preprocessing.image.img_to_array",
"tensorflow.keras.models.Model",
"tensorflow.keras.backend.image_data_format",
"tensorflow.keras.applications.resnet50.decode_predictions",
"tensorflow.keras.layers.GlobalMaxPooling2D",
"common.backbones.layers.CustomBatchNormalization",
"tensorflow.keras.layers.ReLU",
"numpy.expand_dims",
"tensorflow.keras.utils.get_source_inputs",
"tensorflow.keras.layers.Add"
] |
[((14029, 14076), 'tensorflow.keras.models.Model', 'Model', (['inputs', 'x'], {'name': "('ghostnet_%0.2f' % width)"}), "(inputs, x, name='ghostnet_%0.2f' % width)\n", (14034, 14076), False, 'from tensorflow.keras.models import Model\n'), ((14692, 14740), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': '(None, None, 3)', 'name': '"""image_input"""'}), "(shape=(None, None, 3), name='image_input')\n", (14697, 14740), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((14939, 14962), 'tensorflow.keras.backend.set_learning_phase', 'K.set_learning_phase', (['(0)'], {}), '(0)\n', (14959, 14962), True, 'from tensorflow.keras import backend as K\n'), ((15114, 15179), 'keras_preprocessing.image.load_img', 'image.load_img', (['"""../../example/eagle.jpg"""'], {'target_size': '(224, 224)'}), "('../../example/eagle.jpg', target_size=(224, 224))\n", (15128, 15179), False, 'from keras_preprocessing import image\n'), ((15188, 15211), 'keras_preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (15206, 15211), False, 'from keras_preprocessing import image\n'), ((15220, 15245), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (15234, 15245), True, 'import numpy as np\n'), ((2664, 2798), 'common.backbones.layers.YoloConv2D', 'YoloConv2D', ([], {'filters': 'output_filters', 'kernel_size': 'kernel_size', 'strides': 'strides', 'padding': 'padding', 'use_bias': 'use_bias', 'name': "(name + '_0')"}), "(filters=output_filters, kernel_size=kernel_size, strides=strides,\n padding=padding, use_bias=use_bias, name=name + '_0')\n", (2674, 2798), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((2881, 2923), 'common.backbones.layers.CustomBatchNormalization', 'CustomBatchNormalization', ([], {'name': "(name + '_1')"}), "(name=name + '_1')\n", (2905, 2923), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((3119, 3239), 'common.backbones.layers.YoloDepthwiseConv2D', 'YoloDepthwiseConv2D', ([], {'kernel_size': 'kernel_size', 'strides': 'strides', 'padding': 'padding', 'use_bias': 'use_bias', 'name': "(name + '_0')"}), "(kernel_size=kernel_size, strides=strides, padding=\n padding, use_bias=use_bias, name=name + '_0')\n", (3138, 3239), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((3340, 3382), 'common.backbones.layers.CustomBatchNormalization', 'CustomBatchNormalization', ([], {'name': "(name + '_1')"}), "(name=name + '_1')\n", (3364, 3382), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((3641, 3690), 'tensorflow.keras.layers.GlobalAveragePooling2D', 'GlobalAveragePooling2D', ([], {'name': "(name + '_avg_pool2d')"}), "(name=name + '_avg_pool2d')\n", (3663, 3690), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((3705, 3726), 'tensorflow.keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (3724, 3726), True, 'from tensorflow.keras import backend as K\n'), ((3877, 3969), 'common.backbones.layers.YoloConv2D', 'YoloConv2D', ([], {'filters': 'reduce_chs', 'kernel_size': '(1)', 'use_bias': '(True)', 'name': "(name + '_conv_reduce')"}), "(filters=reduce_chs, kernel_size=1, use_bias=True, name=name +\n '_conv_reduce')\n", (3887, 3969), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((3975, 3999), 'tensorflow.keras.layers.ReLU', 'ReLU', ([], {'name': "(name + '_act')"}), "(name=name + '_act')\n", (3979, 3999), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((4120, 4173), 'tensorflow.keras.layers.Activation', 'Activation', (['hard_sigmoid'], {'name': "(name + '_hard_sigmoid')"}), "(hard_sigmoid, name=name + '_hard_sigmoid')\n", (4130, 4173), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((4183, 4193), 'tensorflow.keras.layers.Multiply', 'Multiply', ([], {}), '()\n', (4191, 4193), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((4303, 4429), 'common.backbones.layers.YoloConv2D', 'YoloConv2D', ([], {'filters': 'out_chs', 'kernel_size': 'kernel_size', 'strides': 'stride', 'padding': '"""valid"""', 'use_bias': '(False)', 'name': "(name + '_conv')"}), "(filters=out_chs, kernel_size=kernel_size, strides=stride,\n padding='valid', use_bias=False, name=name + '_conv')\n", (4313, 4429), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((4516, 4560), 'common.backbones.layers.CustomBatchNormalization', 'CustomBatchNormalization', ([], {'name': "(name + '_bn1')"}), "(name=name + '_bn1')\n", (4540, 4560), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((4570, 4595), 'tensorflow.keras.layers.ReLU', 'ReLU', ([], {'name': "(name + '_relu')"}), "(name=name + '_relu')\n", (4574, 4595), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((4744, 4773), 'math.ceil', 'math.ceil', (['(output_chs / ratio)'], {}), '(output_chs / ratio)\n', (4753, 4773), False, 'import math\n'), ((5407, 5449), 'tensorflow.keras.layers.Concatenate', 'Concatenate', ([], {'axis': '(3)', 'name': "(name + '_concat')"}), "(axis=3, name=name + '_concat')\n", (5418, 5449), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((7066, 7089), 'tensorflow.keras.layers.Add', 'Add', ([], {'name': "(name + '_add')"}), "(name=name + '_add')\n", (7069, 7089), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((11460, 11484), 'tensorflow.keras.layers.Input', 'Input', ([], {'shape': 'input_shape'}), '(shape=input_shape)\n', (11465, 11484), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((11869, 11989), 'common.backbones.layers.YoloConv2D', 'YoloConv2D', ([], {'filters': 'output_channel', 'kernel_size': '(3)', 'strides': '(2, 2)', 'padding': '"""same"""', 'use_bias': '(False)', 'name': '"""conv_stem"""'}), "(filters=output_channel, kernel_size=3, strides=(2, 2), padding=\n 'same', use_bias=False, name='conv_stem')\n", (11879, 11989), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((12079, 12115), 'common.backbones.layers.CustomBatchNormalization', 'CustomBatchNormalization', ([], {'name': '"""bn1"""'}), "(name='bn1')\n", (12103, 12115), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((12127, 12152), 'tensorflow.keras.layers.ReLU', 'ReLU', ([], {'name': '"""Conv2D_1_act"""'}), "(name='Conv2D_1_act')\n", (12131, 12152), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((13927, 13958), 'tensorflow.keras.utils.get_source_inputs', 'get_source_inputs', (['input_tensor'], {}), '(input_tensor)\n', (13944, 13958), False, 'from tensorflow.keras.utils import get_source_inputs, get_file\n'), ((14463, 14518), 'tensorflow.keras.utils.get_file', 'get_file', (['file_name', 'weight_path'], {'cache_subdir': '"""models"""'}), "(file_name, weight_path, cache_subdir='models')\n", (14471, 14518), False, 'from tensorflow.keras.utils import get_source_inputs, get_file\n'), ((15328, 15353), 'tensorflow.keras.applications.resnet50.decode_predictions', 'decode_predictions', (['preds'], {}), '(preds)\n', (15346, 15353), False, 'from tensorflow.keras.applications.resnet50 import decode_predictions\n'), ((726, 752), 'os.path.realpath', 'os.path.realpath', (['__file__'], {}), '(__file__)\n', (742, 752), False, 'import os, sys\n'), ((2511, 2520), 'tensorflow.keras.layers.ReLU', 'ReLU', (['(6.0)'], {}), '(6.0)\n', (2515, 2520), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((2933, 2958), 'tensorflow.keras.layers.ReLU', 'ReLU', ([], {'name': "(name + '_relu')"}), "(name=name + '_relu')\n", (2937, 2958), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((3392, 3417), 'tensorflow.keras.layers.ReLU', 'ReLU', ([], {'name': "(name + '_relu')"}), "(name=name + '_relu')\n", (3396, 3417), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((5830, 5954), 'common.backbones.layers.YoloDepthwiseConv2D', 'YoloDepthwiseConv2D', ([], {'kernel_size': 'dw_kernel_size', 'strides': 'stride', 'padding': '"""same"""', 'use_bias': '(False)', 'name': "(name + '_conv_dw')"}), "(kernel_size=dw_kernel_size, strides=stride, padding=\n 'same', use_bias=False, name=name + '_conv_dw')\n", (5849, 5954), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((6075, 6121), 'common.backbones.layers.CustomBatchNormalization', 'CustomBatchNormalization', ([], {'name': "(name + '_bn_dw')"}), "(name=name + '_bn_dw')\n", (6099, 6121), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((6476, 6595), 'common.backbones.layers.YoloDepthwiseConv2D', 'YoloDepthwiseConv2D', ([], {'kernel_size': 'dw_kernel_size', 'strides': 'stride', 'padding': '"""same"""', 'use_bias': '(False)', 'name': "(name1 + '_0')"}), "(kernel_size=dw_kernel_size, strides=stride, padding=\n 'same', use_bias=False, name=name1 + '_0')\n", (6495, 6595), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((6727, 6770), 'common.backbones.layers.CustomBatchNormalization', 'CustomBatchNormalization', ([], {'name': "(name1 + '_1')"}), "(name=name1 + '_1')\n", (6751, 6770), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((6786, 6900), 'common.backbones.layers.YoloConv2D', 'YoloConv2D', ([], {'filters': 'out_chs', 'kernel_size': '(1)', 'strides': '(1, 1)', 'padding': '"""valid"""', 'use_bias': '(False)', 'name': "(name1 + '_2')"}), "(filters=out_chs, kernel_size=1, strides=(1, 1), padding='valid',\n use_bias=False, name=name1 + '_2')\n", (6796, 6900), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((7011, 7054), 'common.backbones.layers.CustomBatchNormalization', 'CustomBatchNormalization', ([], {'name': "(name1 + '_3')"}), "(name=name1 + '_3')\n", (7035, 7054), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((10347, 10370), 'os.path.exists', 'os.path.exists', (['weights'], {}), '(weights)\n', (10361, 10370), False, 'import os, sys\n'), ((11097, 11118), 'tensorflow.keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (11116, 11118), True, 'from tensorflow.keras import backend as K\n'), ((11726, 11747), 'tensorflow.keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (11745, 11747), True, 'from tensorflow.keras import backend as K\n'), ((12833, 12884), 'tensorflow.keras.layers.GlobalAveragePooling2D', 'GlobalAveragePooling2D', ([], {'name': '"""global_avg_pooling2D"""'}), "(name='global_avg_pooling2D')\n", (12855, 12884), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((12899, 12920), 'tensorflow.keras.backend.image_data_format', 'K.image_data_format', ([], {}), '()\n', (12918, 12920), True, 'from tensorflow.keras import backend as K\n'), ((13140, 13260), 'common.backbones.layers.YoloConv2D', 'YoloConv2D', ([], {'filters': 'output_channel', 'kernel_size': '(1)', 'strides': '(1, 1)', 'padding': '"""valid"""', 'use_bias': '(True)', 'name': '"""conv_head"""'}), "(filters=output_channel, kernel_size=1, strides=(1, 1), padding=\n 'valid', use_bias=True, name='conv_head')\n", (13150, 13260), False, 'from common.backbones.layers import YoloConv2D, YoloDepthwiseConv2D, CustomBatchNormalization\n'), ((13365, 13387), 'tensorflow.keras.layers.ReLU', 'ReLU', ([], {'name': '"""relu_head"""'}), "(name='relu_head')\n", (13369, 13387), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((13493, 13502), 'tensorflow.keras.layers.Flatten', 'Flatten', ([], {}), '()\n', (13500, 13502), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((13518, 13594), 'tensorflow.keras.layers.Dense', 'Dense', ([], {'units': 'classes', 'activation': '"""softmax"""', 'use_bias': '(True)', 'name': '"""classifier"""'}), "(units=classes, activation='softmax', use_bias=True, name='classifier')\n", (13523, 13594), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((12958, 12989), 'tensorflow.keras.layers.Reshape', 'Reshape', (['(output_channel, 1, 1)'], {}), '((output_channel, 1, 1))\n', (12965, 12989), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((13023, 13054), 'tensorflow.keras.layers.Reshape', 'Reshape', (['(1, 1, output_channel)'], {}), '((1, 1, output_channel))\n', (13030, 13054), False, 'from tensorflow.keras.layers import Conv2D, DepthwiseConv2D, BatchNormalization, Dense, Flatten, ReLU, Reshape, Activation\n'), ((13438, 13477), 'tensorflow.keras.layers.Dropout', 'Dropout', (['dropout_rate'], {'name': '"""dropout_1"""'}), "(dropout_rate, name='dropout_1')\n", (13445, 13477), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((13678, 13702), 'tensorflow.keras.layers.GlobalAveragePooling2D', 'GlobalAveragePooling2D', ([], {}), '()\n', (13700, 13702), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n'), ((13753, 13773), 'tensorflow.keras.layers.GlobalMaxPooling2D', 'GlobalMaxPooling2D', ([], {}), '()\n', (13771, 13773), False, 'from tensorflow.keras.layers import Input, GlobalAveragePooling2D, GlobalMaxPooling2D, Concatenate, Dropout, Add, Multiply\n')]
|
"""
Copyright (c) 2019 NAVER Corp.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""
import torch
import torch.nn as nn
import numpy as np
def get_wav(in_channels, pool=True):
"""wavelet decomposition using conv2d"""
harr_wav_L = 1 / np.sqrt(2) * np.ones((1, 2))
harr_wav_H = 1 / np.sqrt(2) * np.ones((1, 2))
harr_wav_H[0, 0] = -1 * harr_wav_H[0, 0]
harr_wav_LL = np.transpose(harr_wav_L) * harr_wav_L
harr_wav_LH = np.transpose(harr_wav_L) * harr_wav_H
harr_wav_HL = np.transpose(harr_wav_H) * harr_wav_L
harr_wav_HH = np.transpose(harr_wav_H) * harr_wav_H
filter_LL = torch.from_numpy(harr_wav_LL).unsqueeze(0)
filter_LH = torch.from_numpy(harr_wav_LH).unsqueeze(0)
filter_HL = torch.from_numpy(harr_wav_HL).unsqueeze(0)
filter_HH = torch.from_numpy(harr_wav_HH).unsqueeze(0)
if pool:
net = nn.Conv2d
else:
net = nn.ConvTranspose2d
LL = net(in_channels, in_channels,
kernel_size=2, stride=2, padding=0, bias=False,
groups=in_channels)
LH = net(in_channels, in_channels,
kernel_size=2, stride=2, padding=0, bias=False,
groups=in_channels)
HL = net(in_channels, in_channels,
kernel_size=2, stride=2, padding=0, bias=False,
groups=in_channels)
HH = net(in_channels, in_channels,
kernel_size=2, stride=2, padding=0, bias=False,
groups=in_channels)
LL.weight.requires_grad = False
LH.weight.requires_grad = False
HL.weight.requires_grad = False
HH.weight.requires_grad = False
LL.weight.data = filter_LL.float().unsqueeze(0).expand(in_channels, -1, -1, -1).clone()
LH.weight.data = filter_LH.float().unsqueeze(0).expand(in_channels, -1, -1, -1).clone()
HL.weight.data = filter_HL.float().unsqueeze(0).expand(in_channels, -1, -1, -1).clone()
HH.weight.data = filter_HH.float().unsqueeze(0).expand(in_channels, -1, -1, -1).clone()
return LL, LH, HL, HH
class WavePool(nn.Module):
def __init__(self, in_channels):
super(WavePool, self).__init__()
self.LL, self.LH, self.HL, self.HH = get_wav(in_channels)
def forward(self, x):
return self.LL(x), self.LH(x), self.HL(x), self.HH(x)
class WaveUnpool(nn.Module):
def __init__(self, in_channels, option_unpool='cat5'):
super(WaveUnpool, self).__init__()
self.in_channels = in_channels
self.option_unpool = option_unpool
self.LL, self.LH, self.HL, self.HH = get_wav(self.in_channels, pool=False)
def forward(self, LL, LH, HL, HH, original=None):
if self.option_unpool == 'sum':
return self.LL(LL) + self.LH(LH) + self.HL(HL) + self.HH(HH)
elif self.option_unpool == 'cat5' and original is not None:
return torch.cat([self.LL(LL), self.LH(LH), self.HL(HL), self.HH(HH), original], dim=1)
else:
raise NotImplementedError
class WaveEncoder(nn.Module):
def __init__(self, option_unpool):
super(WaveEncoder, self).__init__()
self.option_unpool = option_unpool
self.pad = nn.ReflectionPad2d(1)
self.relu = nn.ReLU(inplace=True)
self.conv0 = nn.Conv2d(3, 3, 1, 1, 0)
self.conv1_1 = nn.Conv2d(3, 64, 3, 1, 0)
self.conv1_2 = nn.Conv2d(64, 64, 3, 1, 0)
self.pool1 = WavePool(64)
self.conv2_1 = nn.Conv2d(64, 128, 3, 1, 0)
self.conv2_2 = nn.Conv2d(128, 128, 3, 1, 0)
self.pool2 = WavePool(128)
self.conv3_1 = nn.Conv2d(128, 256, 3, 1, 0)
self.conv3_2 = nn.Conv2d(256, 256, 3, 1, 0)
self.conv3_3 = nn.Conv2d(256, 256, 3, 1, 0)
self.conv3_4 = nn.Conv2d(256, 256, 3, 1, 0)
self.pool3 = WavePool(256)
self.conv4_1 = nn.Conv2d(256, 512, 3, 1, 0)
def forward(self, x):
skips = {}
for level in [1, 2, 3, 4]:
x = self.encode(x, skips, level)
return x
def encode(self, x, skips, level):
assert level in {1, 2, 3, 4}
if self.option_unpool == 'sum':
if level == 1:
out = self.conv0(x)
out = self.relu(self.conv1_1(self.pad(out)))
out = self.relu(self.conv1_2(self.pad(out)))
skips['conv1_2'] = out
LL, LH, HL, HH = self.pool1(out)
skips['pool1'] = [LH, HL, HH]
return LL
elif level == 2:
out = self.relu(self.conv2_1(self.pad(x)))
out = self.relu(self.conv2_2(self.pad(out)))
skips['conv2_2'] = out
LL, LH, HL, HH = self.pool2(out)
skips['pool2'] = [LH, HL, HH]
return LL
elif level == 3:
out = self.relu(self.conv3_1(self.pad(x)))
out = self.relu(self.conv3_2(self.pad(out)))
out = self.relu(self.conv3_3(self.pad(out)))
out = self.relu(self.conv3_4(self.pad(out)))
skips['conv3_4'] = out
LL, LH, HL, HH = self.pool3(out)
skips['pool3'] = [LH, HL, HH]
return LL
else:
return self.relu(self.conv4_1(self.pad(x)))
elif self.option_unpool == 'cat5':
if level == 1:
out = self.conv0(x)
out = self.relu(self.conv1_1(self.pad(out)))
return out
elif level == 2:
out = self.relu(self.conv1_2(self.pad(x)))
skips['conv1_2'] = out
LL, LH, HL, HH = self.pool1(out)
skips['pool1'] = [LH, HL, HH]
out = self.relu(self.conv2_1(self.pad(LL)))
return out
elif level == 3:
out = self.relu(self.conv2_2(self.pad(x)))
skips['conv2_2'] = out
LL, LH, HL, HH = self.pool2(out)
skips['pool2'] = [LH, HL, HH]
out = self.relu(self.conv3_1(self.pad(LL)))
return out
else:
out = self.relu(self.conv3_2(self.pad(x)))
out = self.relu(self.conv3_3(self.pad(out)))
out = self.relu(self.conv3_4(self.pad(out)))
skips['conv3_4'] = out
LL, LH, HL, HH = self.pool3(out)
skips['pool3'] = [LH, HL, HH]
out = self.relu(self.conv4_1(self.pad(LL)))
return out
else:
raise NotImplementedError
class WaveDecoder(nn.Module):
def __init__(self, option_unpool):
super(WaveDecoder, self).__init__()
self.option_unpool = option_unpool
if option_unpool == 'sum':
multiply_in = 1
elif option_unpool == 'cat5':
multiply_in = 5
else:
raise NotImplementedError
self.pad = nn.ReflectionPad2d(1)
self.relu = nn.ReLU(inplace=True)
self.conv4_1 = nn.Conv2d(512, 256, 3, 1, 0)
self.recon_block3 = WaveUnpool(256, option_unpool)
if option_unpool == 'sum':
self.conv3_4 = nn.Conv2d(256*multiply_in, 256, 3, 1, 0)
else:
self.conv3_4_2 = nn.Conv2d(256*multiply_in, 256, 3, 1, 0)
self.conv3_3 = nn.Conv2d(256, 256, 3, 1, 0)
self.conv3_2 = nn.Conv2d(256, 256, 3, 1, 0)
self.conv3_1 = nn.Conv2d(256, 128, 3, 1, 0)
self.recon_block2 = WaveUnpool(128, option_unpool)
if option_unpool == 'sum':
self.conv2_2 = nn.Conv2d(128*multiply_in, 128, 3, 1, 0)
else:
self.conv2_2_2 = nn.Conv2d(128*multiply_in, 128, 3, 1, 0)
self.conv2_1 = nn.Conv2d(128, 64, 3, 1, 0)
self.recon_block1 = WaveUnpool(64, option_unpool)
if option_unpool == 'sum':
self.conv1_2 = nn.Conv2d(64*multiply_in, 64, 3, 1, 0)
else:
self.conv1_2_2 = nn.Conv2d(64*multiply_in, 64, 3, 1, 0)
self.conv1_1 = nn.Conv2d(64, 3, 3, 1, 0)
def forward(self, x, skips):
for level in [4, 3, 2, 1]:
x = self.decode(x, skips, level)
return x
def decode(self, x, skips, level):
assert level in {4, 3, 2, 1}
if level == 4:
out = self.relu(self.conv4_1(self.pad(x)))
LH, HL, HH = skips['pool3']
original = skips['conv3_4'] if 'conv3_4' in skips.keys() else None
out = self.recon_block3(out, LH, HL, HH, original)
_conv3_4 = self.conv3_4 if self.option_unpool == 'sum' else self.conv3_4_2
out = self.relu(_conv3_4(self.pad(out)))
out = self.relu(self.conv3_3(self.pad(out)))
return self.relu(self.conv3_2(self.pad(out)))
elif level == 3:
out = self.relu(self.conv3_1(self.pad(x)))
LH, HL, HH = skips['pool2']
original = skips['conv2_2'] if 'conv2_2' in skips.keys() else None
out = self.recon_block2(out, LH, HL, HH, original)
_conv2_2 = self.conv2_2 if self.option_unpool == 'sum' else self.conv2_2_2
return self.relu(_conv2_2(self.pad(out)))
elif level == 2:
out = self.relu(self.conv2_1(self.pad(x)))
LH, HL, HH = skips['pool1']
original = skips['conv1_2'] if 'conv1_2' in skips.keys() else None
out = self.recon_block1(out, LH, HL, HH, original)
_conv1_2 = self.conv1_2 if self.option_unpool == 'sum' else self.conv1_2_2
return self.relu(_conv1_2(self.pad(out)))
else:
return self.conv1_1(self.pad(x))
|
[
"torch.from_numpy",
"torch.nn.ReLU",
"torch.nn.ReflectionPad2d",
"torch.nn.Conv2d",
"numpy.transpose",
"numpy.ones",
"numpy.sqrt"
] |
[((1237, 1252), 'numpy.ones', 'np.ones', (['(1, 2)'], {}), '((1, 2))\n', (1244, 1252), True, 'import numpy as np\n'), ((1287, 1302), 'numpy.ones', 'np.ones', (['(1, 2)'], {}), '((1, 2))\n', (1294, 1302), True, 'import numpy as np\n'), ((1367, 1391), 'numpy.transpose', 'np.transpose', (['harr_wav_L'], {}), '(harr_wav_L)\n', (1379, 1391), True, 'import numpy as np\n'), ((1423, 1447), 'numpy.transpose', 'np.transpose', (['harr_wav_L'], {}), '(harr_wav_L)\n', (1435, 1447), True, 'import numpy as np\n'), ((1479, 1503), 'numpy.transpose', 'np.transpose', (['harr_wav_H'], {}), '(harr_wav_H)\n', (1491, 1503), True, 'import numpy as np\n'), ((1535, 1559), 'numpy.transpose', 'np.transpose', (['harr_wav_H'], {}), '(harr_wav_H)\n', (1547, 1559), True, 'import numpy as np\n'), ((4091, 4112), 'torch.nn.ReflectionPad2d', 'nn.ReflectionPad2d', (['(1)'], {}), '(1)\n', (4109, 4112), True, 'import torch.nn as nn\n'), ((4133, 4154), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4140, 4154), True, 'import torch.nn as nn\n'), ((4177, 4201), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', '(3)', '(1)', '(1)', '(0)'], {}), '(3, 3, 1, 1, 0)\n', (4186, 4201), True, 'import torch.nn as nn\n'), ((4225, 4250), 'torch.nn.Conv2d', 'nn.Conv2d', (['(3)', '(64)', '(3)', '(1)', '(0)'], {}), '(3, 64, 3, 1, 0)\n', (4234, 4250), True, 'import torch.nn as nn\n'), ((4274, 4300), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(64)', '(3)', '(1)', '(0)'], {}), '(64, 64, 3, 1, 0)\n', (4283, 4300), True, 'import torch.nn as nn\n'), ((4359, 4386), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(128)', '(3)', '(1)', '(0)'], {}), '(64, 128, 3, 1, 0)\n', (4368, 4386), True, 'import torch.nn as nn\n'), ((4410, 4438), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128)', '(128)', '(3)', '(1)', '(0)'], {}), '(128, 128, 3, 1, 0)\n', (4419, 4438), True, 'import torch.nn as nn\n'), ((4498, 4526), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128)', '(256)', '(3)', '(1)', '(0)'], {}), '(128, 256, 3, 1, 0)\n', (4507, 4526), True, 'import torch.nn as nn\n'), ((4550, 4578), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', '(256)', '(3)', '(1)', '(0)'], {}), '(256, 256, 3, 1, 0)\n', (4559, 4578), True, 'import torch.nn as nn\n'), ((4602, 4630), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', '(256)', '(3)', '(1)', '(0)'], {}), '(256, 256, 3, 1, 0)\n', (4611, 4630), True, 'import torch.nn as nn\n'), ((4654, 4682), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', '(256)', '(3)', '(1)', '(0)'], {}), '(256, 256, 3, 1, 0)\n', (4663, 4682), True, 'import torch.nn as nn\n'), ((4742, 4770), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', '(512)', '(3)', '(1)', '(0)'], {}), '(256, 512, 3, 1, 0)\n', (4751, 4770), True, 'import torch.nn as nn\n'), ((7842, 7863), 'torch.nn.ReflectionPad2d', 'nn.ReflectionPad2d', (['(1)'], {}), '(1)\n', (7860, 7863), True, 'import torch.nn as nn\n'), ((7884, 7905), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (7891, 7905), True, 'import torch.nn as nn\n'), ((7929, 7957), 'torch.nn.Conv2d', 'nn.Conv2d', (['(512)', '(256)', '(3)', '(1)', '(0)'], {}), '(512, 256, 3, 1, 0)\n', (7938, 7957), True, 'import torch.nn as nn\n'), ((8228, 8256), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', '(256)', '(3)', '(1)', '(0)'], {}), '(256, 256, 3, 1, 0)\n', (8237, 8256), True, 'import torch.nn as nn\n'), ((8280, 8308), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', '(256)', '(3)', '(1)', '(0)'], {}), '(256, 256, 3, 1, 0)\n', (8289, 8308), True, 'import torch.nn as nn\n'), ((8332, 8360), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256)', '(128)', '(3)', '(1)', '(0)'], {}), '(256, 128, 3, 1, 0)\n', (8341, 8360), True, 'import torch.nn as nn\n'), ((8631, 8658), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128)', '(64)', '(3)', '(1)', '(0)'], {}), '(128, 64, 3, 1, 0)\n', (8640, 8658), True, 'import torch.nn as nn\n'), ((8924, 8949), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64)', '(3)', '(3)', '(1)', '(0)'], {}), '(64, 3, 3, 1, 0)\n', (8933, 8949), True, 'import torch.nn as nn\n'), ((1224, 1234), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (1231, 1234), True, 'import numpy as np\n'), ((1274, 1284), 'numpy.sqrt', 'np.sqrt', (['(2)'], {}), '(2)\n', (1281, 1284), True, 'import numpy as np\n'), ((1590, 1619), 'torch.from_numpy', 'torch.from_numpy', (['harr_wav_LL'], {}), '(harr_wav_LL)\n', (1606, 1619), False, 'import torch\n'), ((1649, 1678), 'torch.from_numpy', 'torch.from_numpy', (['harr_wav_LH'], {}), '(harr_wav_LH)\n', (1665, 1678), False, 'import torch\n'), ((1708, 1737), 'torch.from_numpy', 'torch.from_numpy', (['harr_wav_HL'], {}), '(harr_wav_HL)\n', (1724, 1737), False, 'import torch\n'), ((1767, 1796), 'torch.from_numpy', 'torch.from_numpy', (['harr_wav_HH'], {}), '(harr_wav_HH)\n', (1783, 1796), False, 'import torch\n'), ((8080, 8122), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256 * multiply_in)', '(256)', '(3)', '(1)', '(0)'], {}), '(256 * multiply_in, 256, 3, 1, 0)\n', (8089, 8122), True, 'import torch.nn as nn\n'), ((8164, 8206), 'torch.nn.Conv2d', 'nn.Conv2d', (['(256 * multiply_in)', '(256)', '(3)', '(1)', '(0)'], {}), '(256 * multiply_in, 256, 3, 1, 0)\n', (8173, 8206), True, 'import torch.nn as nn\n'), ((8483, 8525), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128 * multiply_in)', '(128)', '(3)', '(1)', '(0)'], {}), '(128 * multiply_in, 128, 3, 1, 0)\n', (8492, 8525), True, 'import torch.nn as nn\n'), ((8567, 8609), 'torch.nn.Conv2d', 'nn.Conv2d', (['(128 * multiply_in)', '(128)', '(3)', '(1)', '(0)'], {}), '(128 * multiply_in, 128, 3, 1, 0)\n', (8576, 8609), True, 'import torch.nn as nn\n'), ((8780, 8820), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64 * multiply_in)', '(64)', '(3)', '(1)', '(0)'], {}), '(64 * multiply_in, 64, 3, 1, 0)\n', (8789, 8820), True, 'import torch.nn as nn\n'), ((8862, 8902), 'torch.nn.Conv2d', 'nn.Conv2d', (['(64 * multiply_in)', '(64)', '(3)', '(1)', '(0)'], {}), '(64 * multiply_in, 64, 3, 1, 0)\n', (8871, 8902), True, 'import torch.nn as nn\n')]
|
import numpy
class ReverseProjection:
"""
I suppose that
the photo is xy plane having z=0.
coordinates of a point of laser plane having laser_position=0 are (p_1, p_2, p_3).
normal vector of laser plane is (n_1, n_2, n_3).
focus is in (width/2, heigth/2, -f).
"""
def __init__(self, laser_plane_normal, a_point_at_laser_plane, photo_size_px, up, focal_point_z):
self.laser_plane_normal = laser_plane_normal
self.a_point_at_laser_plane = a_point_at_laser_plane
self.photo_size = photo_size_px
# focal point
self.focal_point = numpy.array([photo_size_px[0]/2, photo_size_px[1]/2, focal_point_z])
self.normal_unit = laser_plane_normal / numpy.linalg.norm(laser_plane_normal)
self.up = up
# Normalized up vector
self.up_unit = up / numpy.linalg.norm(up)
# axis X is orthogonal to Y and Z
self.axis_x = numpy.cross(self.up_unit, self.normal_unit)
self.axis_x_unit = self.axis_x / numpy.linalg.norm(self.axis_x)
def get3D(self, photo_x, photo_y, laser_position):
"""
:param photo_x:
:param photo_y:
:param laser_position:
:return:
"""
laser_point = self.a_point_at_laser_plane + laser_position * self.normal_unit # is a point in laser plane
photo_point = numpy.array([photo_x, photo_y, 0])
line_direction = photo_point - self.focal_point
# line containing points photo_point and focus has equation focus + line_param * line_direction
# laser plane has equation normal.(x, y, z) - normal.laser_point = 0, so the intersection is defined by
line_param = (numpy.dot(self.normal_unit,laser_point) - numpy.dot(self.normal_unit, self.focal_point)) / (numpy.dot(self.normal_unit, line_direction))
coordinates = self.focal_point + line_param * line_direction
return coordinates
def coordinate_change(self, old_coordinates):
"""
:param old_coordinates:
:return:
"""
# from photo coordinates the cuboid coordinates are obtained using change of basis matrix
new_basis = numpy.transpose(numpy.array([self.axis_x, self.up, self.laser_plane_normal]))
print(new_basis)
new_basis_inversion = numpy.linalg.inv(new_basis)
print(new_basis_inversion)
new_coordinates = numpy.dot(new_basis_inversion, old_coordinates)
return new_coordinates
|
[
"numpy.cross",
"numpy.linalg.inv",
"numpy.array",
"numpy.linalg.norm",
"numpy.dot"
] |
[((602, 674), 'numpy.array', 'numpy.array', (['[photo_size_px[0] / 2, photo_size_px[1] / 2, focal_point_z]'], {}), '([photo_size_px[0] / 2, photo_size_px[1] / 2, focal_point_z])\n', (613, 674), False, 'import numpy\n'), ((923, 966), 'numpy.cross', 'numpy.cross', (['self.up_unit', 'self.normal_unit'], {}), '(self.up_unit, self.normal_unit)\n', (934, 966), False, 'import numpy\n'), ((1352, 1386), 'numpy.array', 'numpy.array', (['[photo_x, photo_y, 0]'], {}), '([photo_x, photo_y, 0])\n', (1363, 1386), False, 'import numpy\n'), ((2291, 2318), 'numpy.linalg.inv', 'numpy.linalg.inv', (['new_basis'], {}), '(new_basis)\n', (2307, 2318), False, 'import numpy\n'), ((2380, 2427), 'numpy.dot', 'numpy.dot', (['new_basis_inversion', 'old_coordinates'], {}), '(new_basis_inversion, old_coordinates)\n', (2389, 2427), False, 'import numpy\n'), ((719, 756), 'numpy.linalg.norm', 'numpy.linalg.norm', (['laser_plane_normal'], {}), '(laser_plane_normal)\n', (736, 756), False, 'import numpy\n'), ((837, 858), 'numpy.linalg.norm', 'numpy.linalg.norm', (['up'], {}), '(up)\n', (854, 858), False, 'import numpy\n'), ((1008, 1038), 'numpy.linalg.norm', 'numpy.linalg.norm', (['self.axis_x'], {}), '(self.axis_x)\n', (1025, 1038), False, 'import numpy\n'), ((1773, 1816), 'numpy.dot', 'numpy.dot', (['self.normal_unit', 'line_direction'], {}), '(self.normal_unit, line_direction)\n', (1782, 1816), False, 'import numpy\n'), ((2174, 2234), 'numpy.array', 'numpy.array', (['[self.axis_x, self.up, self.laser_plane_normal]'], {}), '([self.axis_x, self.up, self.laser_plane_normal])\n', (2185, 2234), False, 'import numpy\n'), ((1681, 1721), 'numpy.dot', 'numpy.dot', (['self.normal_unit', 'laser_point'], {}), '(self.normal_unit, laser_point)\n', (1690, 1721), False, 'import numpy\n'), ((1723, 1768), 'numpy.dot', 'numpy.dot', (['self.normal_unit', 'self.focal_point'], {}), '(self.normal_unit, self.focal_point)\n', (1732, 1768), False, 'import numpy\n')]
|
#!/usr/bin/env python
'''
Feature homography
==================
Example of using features2d framework for interactive video homography matching.
ORB features and FLANN matcher are used. The actual tracking is implemented by
PlaneTracker class in plane_tracker.py
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
# local modules
from tst_scene_render import TestSceneRender
def intersectionRate(s1, s2):
x1, y1, x2, y2 = s1
s1 = np.array([[x1, y1], [x2,y1], [x2, y2], [x1, y2]])
area, intersection = cv2.intersectConvexConvex(s1, np.array(s2))
return 2 * area / (cv2.contourArea(s1) + cv2.contourArea(np.array(s2)))
from tests_common import NewOpenCVTests
class feature_homography_test(NewOpenCVTests):
render = None
tracker = None
framesCounter = 0
frame = None
def test_feature_homography(self):
self.render = TestSceneRender(self.get_sample('samples/data/graf1.png'),
self.get_sample('samples/data/box.png'), noise = 0.5, speed = 0.5)
self.frame = self.render.getNextFrame()
self.tracker = PlaneTracker()
self.tracker.clear()
self.tracker.add_target(self.frame, self.render.getCurrentRect())
while self.framesCounter < 100:
self.framesCounter += 1
tracked = self.tracker.track(self.frame)
if len(tracked) > 0:
tracked = tracked[0]
self.assertGreater(intersectionRate(self.render.getCurrentRect(), np.int32(tracked.quad)), 0.6)
else:
self.assertEqual(0, 1, 'Tracking error')
self.frame = self.render.getNextFrame()
# built-in modules
from collections import namedtuple
FLANN_INDEX_KDTREE = 1
FLANN_INDEX_LSH = 6
flann_params= dict(algorithm = FLANN_INDEX_LSH,
table_number = 6, # 12
key_size = 12, # 20
multi_probe_level = 1) #2
MIN_MATCH_COUNT = 10
'''
image - image to track
rect - tracked rectangle (x1, y1, x2, y2)
keypoints - keypoints detected inside rect
descrs - their descriptors
data - some user-provided data
'''
PlanarTarget = namedtuple('PlaneTarget', 'image, rect, keypoints, descrs, data')
'''
target - reference to PlanarTarget
p0 - matched points coords in target image
p1 - matched points coords in input frame
H - homography matrix from p0 to p1
quad - target bounary quad in input frame
'''
TrackedTarget = namedtuple('TrackedTarget', 'target, p0, p1, H, quad')
class PlaneTracker:
def __init__(self):
self.detector = cv2.AKAZE_create(threshold = 0.003)
self.matcher = cv2.FlannBasedMatcher(flann_params, {}) # bug : need to pass empty dict (#1329)
self.targets = []
self.frame_points = []
def add_target(self, image, rect, data=None):
'''Add a new tracking target.'''
x0, y0, x1, y1 = rect
raw_points, raw_descrs = self.detect_features(image)
points, descs = [], []
for kp, desc in zip(raw_points, raw_descrs):
x, y = kp.pt
if x0 <= x <= x1 and y0 <= y <= y1:
points.append(kp)
descs.append(desc)
descs = np.uint8(descs)
self.matcher.add([descs])
target = PlanarTarget(image = image, rect=rect, keypoints = points, descrs=descs, data=data)
self.targets.append(target)
def clear(self):
'''Remove all targets'''
self.targets = []
self.matcher.clear()
def track(self, frame):
'''Returns a list of detected TrackedTarget objects'''
self.frame_points, frame_descrs = self.detect_features(frame)
if len(self.frame_points) < MIN_MATCH_COUNT:
return []
matches = self.matcher.knnMatch(frame_descrs, k = 2)
matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < m[1].distance * 0.75]
if len(matches) < MIN_MATCH_COUNT:
return []
matches_by_id = [[] for _ in xrange(len(self.targets))]
for m in matches:
matches_by_id[m.imgIdx].append(m)
tracked = []
for imgIdx, matches in enumerate(matches_by_id):
if len(matches) < MIN_MATCH_COUNT:
continue
target = self.targets[imgIdx]
p0 = [target.keypoints[m.trainIdx].pt for m in matches]
p1 = [self.frame_points[m.queryIdx].pt for m in matches]
p0, p1 = np.float32((p0, p1))
H, status = cv2.findHomography(p0, p1, cv2.RANSAC, 3.0)
status = status.ravel() != 0
if status.sum() < MIN_MATCH_COUNT:
continue
p0, p1 = p0[status], p1[status]
x0, y0, x1, y1 = target.rect
quad = np.float32([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
quad = cv2.perspectiveTransform(quad.reshape(1, -1, 2), H).reshape(-1, 2)
track = TrackedTarget(target=target, p0=p0, p1=p1, H=H, quad=quad)
tracked.append(track)
tracked.sort(key = lambda t: len(t.p0), reverse=True)
return tracked
def detect_features(self, frame):
'''detect_features(self, frame) -> keypoints, descrs'''
keypoints, descrs = self.detector.detectAndCompute(frame, None)
if descrs is None: # detectAndCompute returns descs=None if no keypoints found
descrs = []
return keypoints, descrs
|
[
"cv2.contourArea",
"numpy.uint8",
"numpy.float32",
"cv2.AKAZE_create",
"cv2.FlannBasedMatcher",
"numpy.array",
"collections.namedtuple",
"numpy.int32",
"cv2.findHomography"
] |
[((2274, 2339), 'collections.namedtuple', 'namedtuple', (['"""PlaneTarget"""', '"""image, rect, keypoints, descrs, data"""'], {}), "('PlaneTarget', 'image, rect, keypoints, descrs, data')\n", (2284, 2339), False, 'from collections import namedtuple\n'), ((2588, 2642), 'collections.namedtuple', 'namedtuple', (['"""TrackedTarget"""', '"""target, p0, p1, H, quad"""'], {}), "('TrackedTarget', 'target, p0, p1, H, quad')\n", (2598, 2642), False, 'from collections import namedtuple\n'), ((563, 613), 'numpy.array', 'np.array', (['[[x1, y1], [x2, y1], [x2, y2], [x1, y2]]'], {}), '([[x1, y1], [x2, y1], [x2, y2], [x1, y2]])\n', (571, 613), True, 'import numpy as np\n'), ((669, 681), 'numpy.array', 'np.array', (['s2'], {}), '(s2)\n', (677, 681), True, 'import numpy as np\n'), ((2712, 2745), 'cv2.AKAZE_create', 'cv2.AKAZE_create', ([], {'threshold': '(0.003)'}), '(threshold=0.003)\n', (2728, 2745), False, 'import cv2\n'), ((2771, 2810), 'cv2.FlannBasedMatcher', 'cv2.FlannBasedMatcher', (['flann_params', '{}'], {}), '(flann_params, {})\n', (2792, 2810), False, 'import cv2\n'), ((3334, 3349), 'numpy.uint8', 'np.uint8', (['descs'], {}), '(descs)\n', (3342, 3349), True, 'import numpy as np\n'), ((706, 725), 'cv2.contourArea', 'cv2.contourArea', (['s1'], {}), '(s1)\n', (721, 725), False, 'import cv2\n'), ((4578, 4598), 'numpy.float32', 'np.float32', (['(p0, p1)'], {}), '((p0, p1))\n', (4588, 4598), True, 'import numpy as np\n'), ((4623, 4666), 'cv2.findHomography', 'cv2.findHomography', (['p0', 'p1', 'cv2.RANSAC', '(3.0)'], {}), '(p0, p1, cv2.RANSAC, 3.0)\n', (4641, 4666), False, 'import cv2\n'), ((4885, 4937), 'numpy.float32', 'np.float32', (['[[x0, y0], [x1, y0], [x1, y1], [x0, y1]]'], {}), '([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])\n', (4895, 4937), True, 'import numpy as np\n'), ((744, 756), 'numpy.array', 'np.array', (['s2'], {}), '(s2)\n', (752, 756), True, 'import numpy as np\n'), ((1597, 1619), 'numpy.int32', 'np.int32', (['tracked.quad'], {}), '(tracked.quad)\n', (1605, 1619), True, 'import numpy as np\n')]
|
import re
from string import ascii_letters
import numpy as np
import pandas as pd
import pytest
import anndata as ad
ADATA_ATTRS = ("obs", "var", "varm", "obsm", "layers", "obsp", "varp", "uns")
@pytest.fixture
def adata():
return ad.AnnData(
np.zeros((20, 10)),
obs=pd.DataFrame(
dict(obs_key=list(ascii_letters[:20])),
index=[f"cell{i}" for i in range(20)],
),
var=pd.DataFrame(
dict(var_key=np.arange(10)), index=[f"gene{i}" for i in range(10)]
),
varm=dict(varm_key=np.zeros((10, 20))),
obsm=dict(obsm_key=np.zeros((20, 20))),
layers=dict(layers_key=np.zeros((20, 10))),
obsp=dict(obsp_key=np.zeros((20, 20))),
varp=dict(varp_key=np.zeros((10, 10))),
uns=dict(uns_key=dict(zip("abc", range(3)))),
)
@pytest.fixture(params=ADATA_ATTRS)
def adata_attr(request):
return request.param
def test_anndata_repr(adata):
assert f"{adata.n_obs} × {adata.n_vars}" in repr(adata)
for idxr in [
(slice(10, 20), 9),
(12, 9),
(["cell1", "cell2"], slice(10, 15)),
]:
v = adata[idxr]
v_repr = repr(v)
assert f"{v.n_obs} × {v.n_vars}" in v_repr
assert "View of" in v_repr
for attr in ADATA_ATTRS:
assert re.search(
rf"^\s+{attr}:[^$]*{attr}_key.*$", v_repr, flags=re.MULTILINE
)
def test_removal(adata, adata_attr):
attr = adata_attr
assert re.search(rf"^\s+{attr}:.*$", repr(adata), flags=re.MULTILINE)
delattr(adata, attr)
assert re.search(rf"^\s+{attr}:.*$", repr(adata), flags=re.MULTILINE) is None
|
[
"numpy.zeros",
"pytest.fixture",
"numpy.arange",
"re.search"
] |
[((843, 877), 'pytest.fixture', 'pytest.fixture', ([], {'params': 'ADATA_ATTRS'}), '(params=ADATA_ATTRS)\n', (857, 877), False, 'import pytest\n'), ((260, 278), 'numpy.zeros', 'np.zeros', (['(20, 10)'], {}), '((20, 10))\n', (268, 278), True, 'import numpy as np\n'), ((1323, 1395), 're.search', 're.search', (['f"""^\\\\s+{attr}:[^$]*{attr}_key.*$"""', 'v_repr'], {'flags': 're.MULTILINE'}), "(f'^\\\\s+{attr}:[^$]*{attr}_key.*$', v_repr, flags=re.MULTILINE)\n", (1332, 1395), False, 'import re\n'), ((563, 581), 'numpy.zeros', 'np.zeros', (['(10, 20)'], {}), '((10, 20))\n', (571, 581), True, 'import numpy as np\n'), ((611, 629), 'numpy.zeros', 'np.zeros', (['(20, 20)'], {}), '((20, 20))\n', (619, 629), True, 'import numpy as np\n'), ((663, 681), 'numpy.zeros', 'np.zeros', (['(20, 10)'], {}), '((20, 10))\n', (671, 681), True, 'import numpy as np\n'), ((711, 729), 'numpy.zeros', 'np.zeros', (['(20, 20)'], {}), '((20, 20))\n', (719, 729), True, 'import numpy as np\n'), ((759, 777), 'numpy.zeros', 'np.zeros', (['(10, 10)'], {}), '((10, 10))\n', (767, 777), True, 'import numpy as np\n'), ((471, 484), 'numpy.arange', 'np.arange', (['(10)'], {}), '(10)\n', (480, 484), True, 'import numpy as np\n')]
|
# Copyright 2019 Graphcore Ltd.
"""Networks for VAE implementation in VCD paper"""
import numpy as np
import tensorflow as tf
def encoder(X_input, Z_dim, dtype, n_hidden=200):
"""As in paper"""
with tf.variable_scope('encoder', reuse=tf.AUTO_REUSE, use_resource=True):
# Calculate sqrt(n_hidden) - for initialisers
sqrt_n_hid_inv = 1. / np.sqrt(float(n_hidden))
# Separate networks for approx posterior mean and log std
with tf.variable_scope('mean', use_resource=True, reuse=tf.AUTO_REUSE):
relu0_mean = tf.layers.dense(
X_input,
units=n_hidden,
activation=tf.nn.relu,
kernel_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
bias_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
name='relu0_mu')
relu1_mean = tf.layers.dense(
relu0_mean,
units=n_hidden,
activation=tf.nn.relu,
kernel_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
bias_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
name='relu1_mu')
Z_cond_X_mean = tf.layers.dense(
relu1_mean,
units=Z_dim,
activation=None,
kernel_initializer=tf.random_normal_initializer(dtype=dtype),
bias_initializer=tf.random_normal_initializer(dtype=dtype),
name='posterior_mean')
with tf.variable_scope('std', use_resource=True, reuse=tf.AUTO_REUSE):
relu0_std = tf.layers.dense(
X_input,
units=n_hidden,
activation=tf.nn.relu,
kernel_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
bias_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
name='relu0_std')
relu1_std = tf.layers.dense(
relu0_std,
units=n_hidden,
activation=tf.nn.relu,
kernel_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
bias_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
name='relu1_std')
Z_cond_X_log_std = tf.layers.dense(
relu1_std,
units=Z_dim,
activation=None,
kernel_initializer=tf.random_normal_initializer(dtype=dtype),
bias_initializer=tf.random_normal_initializer(dtype=dtype),
name='posterior_log_std')
# More numerically-stable exponential function
def _pos_softplus(x):
return x + tf.log(1. + tf.exp(1e-4 - x))
def _neg_softplus(x):
return 1e-4 + tf.log(1. + tf.exp(x - 1e-4))
Z_cond_X_std = tf.where(Z_cond_X_log_std >= 0,
_pos_softplus(Z_cond_X_log_std),
_neg_softplus(Z_cond_X_log_std))
return Z_cond_X_mean, Z_cond_X_std
def decoder(Z_cond_X_samples, output_dims, dtype, n_hidden=200):
"""As in paper"""
# Calculate sqrt(n_hidden) - for initialisers
sqrt_n_hid_inv = 1. / np.sqrt(float(n_hidden))
with tf.variable_scope('decoder', reuse=tf.AUTO_REUSE, use_resource=True):
relu0_dec = tf.layers.dense(
Z_cond_X_samples,
units=n_hidden,
activation=tf.nn.relu,
kernel_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
bias_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
name='relu0_dec')
relu1_dec = tf.layers.dense(
relu0_dec,
units=n_hidden,
activation=tf.nn.relu,
kernel_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
bias_initializer=tf.random_normal_initializer(stddev=sqrt_n_hid_inv, dtype=dtype),
name='relu1_dec')
lin_out = tf.layers.dense(
relu1_dec,
units=np.prod(output_dims),
activation=None,
kernel_initializer=tf.random_normal_initializer(dtype=dtype),
bias_initializer=tf.random_normal_initializer(dtype=dtype),
name='dec_lin_out')
return {'logits': lin_out}
|
[
"tensorflow.exp",
"tensorflow.random_normal_initializer",
"tensorflow.variable_scope",
"numpy.prod"
] |
[((209, 277), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""encoder"""'], {'reuse': 'tf.AUTO_REUSE', 'use_resource': '(True)'}), "('encoder', reuse=tf.AUTO_REUSE, use_resource=True)\n", (226, 277), True, 'import tensorflow as tf\n'), ((3424, 3492), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""decoder"""'], {'reuse': 'tf.AUTO_REUSE', 'use_resource': '(True)'}), "('decoder', reuse=tf.AUTO_REUSE, use_resource=True)\n", (3441, 3492), True, 'import tensorflow as tf\n'), ((469, 534), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""mean"""'], {'use_resource': '(True)', 'reuse': 'tf.AUTO_REUSE'}), "('mean', use_resource=True, reuse=tf.AUTO_REUSE)\n", (486, 534), True, 'import tensorflow as tf\n'), ((1624, 1688), 'tensorflow.variable_scope', 'tf.variable_scope', (['"""std"""'], {'use_resource': '(True)', 'reuse': 'tf.AUTO_REUSE'}), "('std', use_resource=True, reuse=tf.AUTO_REUSE)\n", (1641, 1688), True, 'import tensorflow as tf\n'), ((3655, 3719), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (3683, 3719), True, 'import tensorflow as tf\n'), ((3750, 3814), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (3778, 3814), True, 'import tensorflow as tf\n'), ((4001, 4065), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (4029, 4065), True, 'import tensorflow as tf\n'), ((4096, 4160), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (4124, 4160), True, 'import tensorflow as tf\n'), ((4269, 4289), 'numpy.prod', 'np.prod', (['output_dims'], {}), '(output_dims)\n', (4276, 4289), True, 'import numpy as np\n'), ((4351, 4392), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'dtype': 'dtype'}), '(dtype=dtype)\n', (4379, 4392), True, 'import tensorflow as tf\n'), ((4423, 4464), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'dtype': 'dtype'}), '(dtype=dtype)\n', (4451, 4464), True, 'import tensorflow as tf\n'), ((709, 773), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (737, 773), True, 'import tensorflow as tf\n'), ((808, 872), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (836, 872), True, 'import tensorflow as tf\n'), ((1084, 1148), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (1112, 1148), True, 'import tensorflow as tf\n'), ((1183, 1247), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (1211, 1247), True, 'import tensorflow as tf\n'), ((1452, 1493), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'dtype': 'dtype'}), '(dtype=dtype)\n', (1480, 1493), True, 'import tensorflow as tf\n'), ((1528, 1569), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'dtype': 'dtype'}), '(dtype=dtype)\n', (1556, 1569), True, 'import tensorflow as tf\n'), ((1862, 1926), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (1890, 1926), True, 'import tensorflow as tf\n'), ((1961, 2025), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (1989, 2025), True, 'import tensorflow as tf\n'), ((2236, 2300), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (2264, 2300), True, 'import tensorflow as tf\n'), ((2335, 2399), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'stddev': 'sqrt_n_hid_inv', 'dtype': 'dtype'}), '(stddev=sqrt_n_hid_inv, dtype=dtype)\n', (2363, 2399), True, 'import tensorflow as tf\n'), ((2608, 2649), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'dtype': 'dtype'}), '(dtype=dtype)\n', (2636, 2649), True, 'import tensorflow as tf\n'), ((2684, 2725), 'tensorflow.random_normal_initializer', 'tf.random_normal_initializer', ([], {'dtype': 'dtype'}), '(dtype=dtype)\n', (2712, 2725), True, 'import tensorflow as tf\n'), ((2890, 2908), 'tensorflow.exp', 'tf.exp', (['(0.0001 - x)'], {}), '(0.0001 - x)\n', (2896, 2908), True, 'import tensorflow as tf\n'), ((2977, 2995), 'tensorflow.exp', 'tf.exp', (['(x - 0.0001)'], {}), '(x - 0.0001)\n', (2983, 2995), True, 'import tensorflow as tf\n')]
|
from functools import reduce
from itertools import product
from typing import Any, Callable, Dict, Iterable, List, Optional, Tuple, Union
import numpy as np
class _Domain:
__slots__ = ['_dimensions_discrete',
'_avg_distance',
'_dimensions_continuous',
'_dimension_length',
'_dimensions',
'_domain',
'_total_size']
def __init__(self,
discrete_domain: Optional[List[Iterable]] = None,
continuous_bounds: Optional[List[Tuple]] = None,
default_resolution: int = 30):
domain_discrete: Dict[str, Any] = {
f'd{i}': list(d) for i, d in enumerate(discrete_domain or [])}
self._dimensions_discrete = list(domain_discrete.keys())
continuous_bounds = [c if len(c) == 2 else (*c, default_resolution)
for c in continuous_bounds]
self._dimension_length = {
f'c{i}': (c[1] - c[0])
for i, c in enumerate(continuous_bounds)}
self._avg_distance = {f'c{i}': (c[1] - c[0]) / c[2]
for i, c in enumerate(continuous_bounds)}
domain_continuous = {f'c{i}': np.linspace(*c)
for i, c in enumerate(continuous_bounds or [])}
self._dimensions_continuous = list(domain_continuous.keys())
self._dimensions = (self._dimensions_discrete +
self._dimensions_continuous)
self._domain = domain_discrete
self._domain.update(domain_continuous)
self._total_size = reduce(lambda x, y: x * y,
[len(v) for v in self._domain.values()])
assert self._total_size > 0, 'Please define domain components!'
assert default_resolution > 0, 'default_resolution must be > 0!'
def __iter__(self) -> Iterable[str]:
return self._domain.keys().__iter__()
def __getitem__(self, item: str) -> Union[List[Any], np.ndarray]:
return self._domain[item]
@property
def dimensions(self):
return self._dimensions
@property
def dimensions_discrete(self):
return self._dimensions_discrete
@property
def dimensions_continuous(self):
return self._dimensions_continuous
@property
def dimension_length(self):
return self._dimension_length
@property
def avg_distance(self):
return self._avg_distance
@property
def total_size(self):
return self._total_size
def keys(self) -> List[str]:
return list(self._domain.keys())
def values(self) -> List[Any]:
return list(self._domain.values())
def items(self) -> List[Tuple[str, Any]]:
return list(zip(self.keys(), self.values()))
class _Individual:
__slots__ = ['_values',
'_scores',
'_payload']
def __init__(self,
values: Dict[str, Any]):
self._values = values
self._scores: Optional[np.ndarray] = None
self._payload: Dict[str, Any] = {}
def __eq__(self,
other: '_Individual') -> bool:
return self._values == other._values
@property
def values(self) -> Dict[str, Any]:
return self._values
@property
def scores(self) -> Union[np.ndarray, None]:
return self._scores
@scores.setter
def scores(self, scores: np.ndarray):
self._scores = scores
@property
def payload(self) -> Dict[str, Any]:
return self._payload
def __getitem__(self, item: str) -> Any:
return self._payload[item]
def __setitem__(self, key: str, value: Any):
self._payload[key] = value
class _Population:
__slots__ = ['_individuals']
def __init__(self,
individuals: Optional[List[_Individual]] = None):
unique_individuals = []
if individuals is not None:
for individual in individuals:
for ind in unique_individuals:
if ind == individual:
continue
unique_individuals.append(individual)
self._individuals: List[_Individual] = unique_individuals
def __len__(self) -> int:
return len(self._individuals)
def __iter__(self) -> Iterable[_Individual]:
return self._individuals.__iter__()
def __add__(self,
other: '_Population'):
return _Population(self.individuals + other.individuals)
def __getitem__(self,
n: Union[int, slice]
) -> Union[_Individual, '_Population']:
if isinstance(n, int):
return self._individuals[n]
return _Population(self._individuals[n])
@property
def individuals(self) -> List[_Individual]:
return self._individuals
class _DistanceCalculator:
__slots__ = ['_domain']
def __init__(self,
domain: _Domain):
self._domain = domain
def distance_values(self,
individual1: _Individual,
individual2: _Individual) -> float:
s1 = individual1.values
s2 = individual2.values
# Hamming-distance:
distance_discrete = float(np.sum([
s1[k] != s2[k] for k in self._domain.dimensions_discrete]))
# L1-distance:
distance_continuous = float(np.sum([
abs(s1[k] - s2[k]) for k in self._domain.dimensions_continuous]))
return distance_discrete + distance_continuous
class _Scorer:
__slots__ = ['_domain',
'_objectives']
def __init__(self,
domain: _Domain,
objectives: List[Callable]):
self._domain = domain
self._objectives = objectives
def score_individual(self,
individual: _Individual):
if individual.scores is None:
individual.scores = np.array([
obj(individual, self._domain) for obj in self._objectives
])
def score_population(self,
population: _Population):
for ind in population.individuals:
self.score_individual(ind)
class _SimpleSorter:
__slots__ = []
@staticmethod
def sort_population(population: _Population,
score_index: int = 0
) -> _Population:
individuals_sorted = sorted(population,
key=lambda i: i.scores[score_index])
return _Population(individuals_sorted)
class _GridSampler:
__slots__ = ['_domain']
def __init__(self,
domain: _Domain):
self._domain = domain
def get_grid_positions(self) -> List[Dict[str, Any]]:
keys = self._domain.keys()
combinations = product(*self._domain.values())
return [dict(zip(keys, values)) for values in combinations]
def get_grid_population(self) -> _Population:
individuals = [_Individual(values)
for values in self.get_grid_positions()]
return _Population(individuals=individuals)
class _RandomSampler:
__slots__ = ['_domain',
'_rng']
def __init__(self,
domain: _Domain,
seed: int = 111):
self._rng = np.random.default_rng(seed=seed)
self._domain = domain
def get_random_position(self) -> Dict[str, Any]:
return {k: self._rng.choice(self._domain[k]) for k in self._domain}
def get_random_individual(self) -> _Individual:
values = self.get_random_position()
return _Individual(values)
def get_random_population(self,
n_individuals: int) -> _Population:
"""
Get a random population with (unique) samples. If less than the
desired number of individuals are available in the grid, the full
grid is returned.
"""
if n_individuals >= self._domain.total_size:
# If n_individuals exhausts the space, just return the full grid:
return _GridSampler(self._domain).get_grid_population()
individuals = []
while len(individuals) < n_individuals:
new_individual = self.get_random_individual()
if not any([new_individual == ind for ind in individuals]):
individuals.append(new_individual)
return _Population(individuals=individuals)
class _Mutator:
__slots__ = ['_domain',
'_mutation_probability',
'_crossover_probability',
'_selection_probability',
'_seed',
'_rng']
def __init__(self,
domain: _Domain,
mutation_probability: float = 0.2,
crossover_probability: float = 0.2,
selection_probability: float = 0.3,
seed: int = 112):
self._domain = domain
self._mutation_probability = mutation_probability
self._crossover_probability = crossover_probability
self._selection_probability = selection_probability
self._seed = seed
self._rng = np.random.default_rng(seed=seed)
def crossover_individuals(self,
individual1: _Individual,
individual2: _Individual
) -> Tuple[_Individual, _Individual]:
values1 = individual1.values.copy()
values2 = individual2.values.copy()
for d in self._domain.dimensions_discrete:
if self._rng.random() < self._crossover_probability:
values1[d], values2[d] = values2[d], values1[d]
for d in self._domain.dimensions_continuous:
if self._rng.random() < self._crossover_probability:
v1 = values1[d]
v2 = values2[d]
dist = v2 - v1
rand = self._rng.random()
v1 += dist * rand
v2 += dist * rand
# Match new values to grid:
arg_min1 = np.argmin(np.abs(self._domain[d] - v1))
values1[d] = self._domain[d][arg_min1]
arg_min2 = np.argmin(np.abs(self._domain[d] - v2))
values2[d] = self._domain[d][arg_min2]
return _Individual(values1), _Individual(values2)
def mutate_individual(self,
individual: _Individual) -> _Individual:
values = individual.values.copy()
for d in self._domain.dimensions_discrete:
if self._rng.random() < self._mutation_probability:
# Update discrete variables uniform by random:
values[d] = np.random.choice(self._domain[d])
for d in self._domain.dimensions_continuous:
if self._rng.random() < self._mutation_probability:
# Normally distributed mutation with std equal to
# 2x the typical distance between points:
new_value = (values[d] + self._rng.normal() *
2 * self._domain.avg_distance[d])
# Match new value to grid:
arg_min = np.argmin(np.abs(self._domain[d] - new_value))
values[d] = self._domain[d][arg_min]
return _Individual(values=values)
def mutate_population(self, population: _Population) -> _Population:
p = 1.0 - self._selection_probability
weights = np.array([p ** i for i in range(len(population))])
weights = np.cumsum(weights)
weights /= weights[-1]
counter = 0
new_individuals = population.individuals.copy()
while len(new_individuals) < 2 * len(population):
idx1 = int(np.where(self._rng.random() < weights)[0][0])
idx2 = int(np.where(self._rng.random() < weights)[0][0])
individual1 = population[idx1]
individual2 = population[idx2]
if idx1 != idx2:
individual1, individual2 = self.crossover_individuals(
individual1=individual1,
individual2=individual2)
individual1 = self.mutate_individual(individual1)
individual2 = self.mutate_individual(individual2)
if not np.any([individual1 == ind for ind in new_individuals]):
new_individuals.append(individual1)
if not np.any([individual2 == ind for ind in new_individuals]):
new_individuals.append(individual2)
counter += 1
if counter > 10 * len(population):
break
return _Population(new_individuals)
|
[
"numpy.sum",
"numpy.abs",
"numpy.random.default_rng",
"numpy.cumsum",
"numpy.any",
"numpy.linspace",
"numpy.random.choice"
] |
[((7364, 7396), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': 'seed'}), '(seed=seed)\n', (7385, 7396), True, 'import numpy as np\n'), ((9225, 9257), 'numpy.random.default_rng', 'np.random.default_rng', ([], {'seed': 'seed'}), '(seed=seed)\n', (9246, 9257), True, 'import numpy as np\n'), ((11582, 11600), 'numpy.cumsum', 'np.cumsum', (['weights'], {}), '(weights)\n', (11591, 11600), True, 'import numpy as np\n'), ((1240, 1255), 'numpy.linspace', 'np.linspace', (['*c'], {}), '(*c)\n', (1251, 1255), True, 'import numpy as np\n'), ((5292, 5360), 'numpy.sum', 'np.sum', (['[(s1[k] != s2[k]) for k in self._domain.dimensions_discrete]'], {}), '([(s1[k] != s2[k]) for k in self._domain.dimensions_discrete])\n', (5298, 5360), True, 'import numpy as np\n'), ((10763, 10796), 'numpy.random.choice', 'np.random.choice', (['self._domain[d]'], {}), '(self._domain[d])\n', (10779, 10796), True, 'import numpy as np\n'), ((12327, 12384), 'numpy.any', 'np.any', (['[(individual1 == ind) for ind in new_individuals]'], {}), '([(individual1 == ind) for ind in new_individuals])\n', (12333, 12384), True, 'import numpy as np\n'), ((12455, 12512), 'numpy.any', 'np.any', (['[(individual2 == ind) for ind in new_individuals]'], {}), '([(individual2 == ind) for ind in new_individuals])\n', (12461, 12512), True, 'import numpy as np\n'), ((10148, 10176), 'numpy.abs', 'np.abs', (['(self._domain[d] - v1)'], {}), '(self._domain[d] - v1)\n', (10154, 10176), True, 'import numpy as np\n'), ((10270, 10298), 'numpy.abs', 'np.abs', (['(self._domain[d] - v2)'], {}), '(self._domain[d] - v2)\n', (10276, 10298), True, 'import numpy as np\n'), ((11242, 11277), 'numpy.abs', 'np.abs', (['(self._domain[d] - new_value)'], {}), '(self._domain[d] - new_value)\n', (11248, 11277), True, 'import numpy as np\n')]
|
#!/usr/bin/env python
import numpy as np
import chainer
from chainer import cuda, serializers, Variable # , optimizers, training
import cv2
import os.path
#import chainer.functions as F
#import chainer.links as L
#import six
#import os
#from chainer.training import extensions
#from train import Image2ImageDataset
from img2imgDataset import ImageAndRefDataset
import unet
import lnet
class Painter:
def __init__(self, gpu=0):
print("start")
self.root = "./images/"
self.batchsize = 1
self.outdir = self.root + "out/"
self.outdir_min = self.root + "out_min/"
self.gpu = gpu
self._dtype = np.float32
if not os.path.isfile("./models/unet_128_standard"):
print("./models/unet_128_standard not found. Please download them from http://paintschainer.preferred.tech/downloads/")
if not os.path.isfile("./models/unet_512_standard"):
print("./models/unet_512_standard not found. Please download them from http://paintschainer.preferred.tech/downloads/")
print("load model")
if self.gpu >= 0:
cuda.get_device(self.gpu).use()
cuda.set_max_workspace_size(64 * 1024 * 1024) # 64MB
chainer.Function.type_check_enable = False
self.cnn_128 = unet.UNET()
self.cnn_512 = unet.UNET()
if self.gpu >= 0:
self.cnn_128.to_gpu()
self.cnn_512.to_gpu()
#lnn = lnet.LNET()
#serializers.load_npz("./cgi-bin/wnet/models/model_cnn_128_df_4", cnn_128)
#serializers.load_npz("./cgi-bin/paint_x2_unet/models/model_cnn_128_f3_2", cnn_128)
serializers.load_npz(
"./models/unet_128_standard", self.cnn_128)
#serializers.load_npz("./cgi-bin/paint_x2_unet/models/model_cnn_128_ua_1", self.cnn_128)
#serializers.load_npz("./cgi-bin/paint_x2_unet/models/model_m_1.6", self.cnn)
serializers.load_npz(
"./models/unet_512_standard", self.cnn_512)
#serializers.load_npz("./cgi-bin/paint_x2_unet/models/model_p2_1", self.cnn)
#serializers.load_npz("./cgi-bin/paint_x2_unet/models/model_10000", self.cnn)
#serializers.load_npz("./cgi-bin/paint_x2_unet/models/liner_f", lnn)
def save_as_img(self, array, name):
array = array.transpose(1, 2, 0)
array = array.clip(0, 255).astype(np.uint8)
array = cuda.to_cpu(array)
(major, minor, _) = cv2.__version__.split(".")
if major == '3':
img = cv2.cvtColor(array, cv2.COLOR_YUV2RGB)
else:
img = cv2.cvtColor(array, cv2.COLOR_YUV2BGR)
cv2.imwrite(name, img)
def liner(self, id_str):
if self.gpu >= 0:
cuda.get_device(self.gpu).use()
image1 = cv2.imread(path1, cv2.IMREAD_GRAYSCALE)
image1 = np.asarray(image1, self._dtype)
if image1.ndim == 2:
image1 = image1[:, :, np.newaxis]
img = image1.transpose(2, 0, 1)
x = np.zeros((1, 3, img.shape[1], img.shape[2]), dtype='f')
if self.gpu >= 0:
x = cuda.to_gpu(x)
lnn = lnet.LNET()
with chainer.no_backprop_mode():
with chainer.using_config('train', False):
y = lnn.calc(Variable(x))
self.save_as_img(y.data[0], self.root + "line/" + id_str + ".jpg")
def colorize(self, id_str, step='C', blur=0, s_size=128,colorize_format="jpg"):
if self.gpu >= 0:
cuda.get_device(self.gpu).use()
_ = {'S': "ref/", 'L': "out_min/", 'C': "ref/"}
dataset = ImageAndRefDataset(
[id_str + ".png"], self.root + "line/", self.root + _[step])
_ = {'S': True, 'L': False, 'C': True}
sample = dataset.get_example(0, minimize=_[step], blur=blur, s_size=s_size)
_ = {'S': 0, 'L': 1, 'C': 0}[step]
sample_container = np.zeros(
(1, 4, sample[_].shape[1], sample[_].shape[2]), dtype='f')
sample_container[0, :] = sample[_]
if self.gpu >= 0:
sample_container = cuda.to_gpu(sample_container)
cnn = {'S': self.cnn_128, 'L': self.cnn_512, 'C': self.cnn_128}
with chainer.no_backprop_mode():
with chainer.using_config('train', False):
image_conv2d_layer = cnn[step].calc(Variable(sample_container))
del sample_container
if step == 'C':
input_bat = np.zeros((1, 4, sample[1].shape[1], sample[1].shape[2]), dtype='f')
print(input_bat.shape)
input_bat[0, 0, :] = sample[1]
output = cuda.to_cpu(image_conv2d_layer.data[0])
del image_conv2d_layer # release memory
for channel in range(3):
input_bat[0, 1 + channel, :] = cv2.resize(
output[channel, :],
(sample[1].shape[2], sample[1].shape[1]),
interpolation=cv2.INTER_CUBIC)
if self.gpu >= 0:
link = cuda.to_gpu(input_bat, None)
else:
link = input_bat
with chainer.no_backprop_mode():
with chainer.using_config('train', False):
image_conv2d_layer = self.cnn_512.calc(Variable(link))
del link # release memory
image_out_path = {
'S': self.outdir_min + id_str + ".png",
'L': self.outdir + id_str + ".jpg",
'C': self.outdir + id_str + "_0." + colorize_format}
self.save_as_img(image_conv2d_layer.data[0], image_out_path[step])
del image_conv2d_layer
if __name__ == '__main__':
for n in range(1):
p = Painter()
print(n)
p.colorize(n * p.batchsize)
|
[
"lnet.LNET",
"chainer.cuda.set_max_workspace_size",
"cv2.resize",
"chainer.Variable",
"chainer.cuda.get_device",
"chainer.serializers.load_npz",
"cv2.cvtColor",
"cv2.imwrite",
"numpy.asarray",
"numpy.zeros",
"chainer.cuda.to_cpu",
"cv2.imread",
"unet.UNET",
"cv2.__version__.split",
"chainer.cuda.to_gpu",
"chainer.no_backprop_mode",
"chainer.using_config",
"img2imgDataset.ImageAndRefDataset"
] |
[((1298, 1309), 'unet.UNET', 'unet.UNET', ([], {}), '()\n', (1307, 1309), False, 'import unet\n'), ((1333, 1344), 'unet.UNET', 'unet.UNET', ([], {}), '()\n', (1342, 1344), False, 'import unet\n'), ((1649, 1713), 'chainer.serializers.load_npz', 'serializers.load_npz', (['"""./models/unet_128_standard"""', 'self.cnn_128'], {}), "('./models/unet_128_standard', self.cnn_128)\n", (1669, 1713), False, 'from chainer import cuda, serializers, Variable\n'), ((1918, 1982), 'chainer.serializers.load_npz', 'serializers.load_npz', (['"""./models/unet_512_standard"""', 'self.cnn_512'], {}), "('./models/unet_512_standard', self.cnn_512)\n", (1938, 1982), False, 'from chainer import cuda, serializers, Variable\n'), ((2394, 2412), 'chainer.cuda.to_cpu', 'cuda.to_cpu', (['array'], {}), '(array)\n', (2405, 2412), False, 'from chainer import cuda, serializers, Variable\n'), ((2441, 2467), 'cv2.__version__.split', 'cv2.__version__.split', (['"""."""'], {}), "('.')\n", (2462, 2467), False, 'import cv2\n'), ((2629, 2651), 'cv2.imwrite', 'cv2.imwrite', (['name', 'img'], {}), '(name, img)\n', (2640, 2651), False, 'import cv2\n'), ((2770, 2809), 'cv2.imread', 'cv2.imread', (['path1', 'cv2.IMREAD_GRAYSCALE'], {}), '(path1, cv2.IMREAD_GRAYSCALE)\n', (2780, 2809), False, 'import cv2\n'), ((2827, 2858), 'numpy.asarray', 'np.asarray', (['image1', 'self._dtype'], {}), '(image1, self._dtype)\n', (2837, 2858), True, 'import numpy as np\n'), ((2986, 3041), 'numpy.zeros', 'np.zeros', (['(1, 3, img.shape[1], img.shape[2])'], {'dtype': '"""f"""'}), "((1, 3, img.shape[1], img.shape[2]), dtype='f')\n", (2994, 3041), True, 'import numpy as np\n'), ((3114, 3125), 'lnet.LNET', 'lnet.LNET', ([], {}), '()\n', (3123, 3125), False, 'import lnet\n'), ((3570, 3649), 'img2imgDataset.ImageAndRefDataset', 'ImageAndRefDataset', (["[id_str + '.png']", "(self.root + 'line/')", '(self.root + _[step])'], {}), "([id_str + '.png'], self.root + 'line/', self.root + _[step])\n", (3588, 3649), False, 'from img2imgDataset import ImageAndRefDataset\n'), ((3866, 3933), 'numpy.zeros', 'np.zeros', (['(1, 4, sample[_].shape[1], sample[_].shape[2])'], {'dtype': '"""f"""'}), "((1, 4, sample[_].shape[1], sample[_].shape[2]), dtype='f')\n", (3874, 3933), True, 'import numpy as np\n'), ((1166, 1211), 'chainer.cuda.set_max_workspace_size', 'cuda.set_max_workspace_size', (['(64 * 1024 * 1024)'], {}), '(64 * 1024 * 1024)\n', (1193, 1211), False, 'from chainer import cuda, serializers, Variable\n'), ((2511, 2549), 'cv2.cvtColor', 'cv2.cvtColor', (['array', 'cv2.COLOR_YUV2RGB'], {}), '(array, cv2.COLOR_YUV2RGB)\n', (2523, 2549), False, 'import cv2\n'), ((2582, 2620), 'cv2.cvtColor', 'cv2.cvtColor', (['array', 'cv2.COLOR_YUV2BGR'], {}), '(array, cv2.COLOR_YUV2BGR)\n', (2594, 2620), False, 'import cv2\n'), ((3084, 3098), 'chainer.cuda.to_gpu', 'cuda.to_gpu', (['x'], {}), '(x)\n', (3095, 3098), False, 'from chainer import cuda, serializers, Variable\n'), ((3139, 3165), 'chainer.no_backprop_mode', 'chainer.no_backprop_mode', ([], {}), '()\n', (3163, 3165), False, 'import chainer\n'), ((4048, 4077), 'chainer.cuda.to_gpu', 'cuda.to_gpu', (['sample_container'], {}), '(sample_container)\n', (4059, 4077), False, 'from chainer import cuda, serializers, Variable\n'), ((4164, 4190), 'chainer.no_backprop_mode', 'chainer.no_backprop_mode', ([], {}), '()\n', (4188, 4190), False, 'import chainer\n'), ((4405, 4472), 'numpy.zeros', 'np.zeros', (['(1, 4, sample[1].shape[1], sample[1].shape[2])'], {'dtype': '"""f"""'}), "((1, 4, sample[1].shape[1], sample[1].shape[2]), dtype='f')\n", (4413, 4472), True, 'import numpy as np\n'), ((4573, 4612), 'chainer.cuda.to_cpu', 'cuda.to_cpu', (['image_conv2d_layer.data[0]'], {}), '(image_conv2d_layer.data[0])\n', (4584, 4612), False, 'from chainer import cuda, serializers, Variable\n'), ((3184, 3220), 'chainer.using_config', 'chainer.using_config', (['"""train"""', '(False)'], {}), "('train', False)\n", (3204, 3220), False, 'import chainer\n'), ((4209, 4245), 'chainer.using_config', 'chainer.using_config', (['"""train"""', '(False)'], {}), "('train', False)\n", (4229, 4245), False, 'import chainer\n'), ((4751, 4858), 'cv2.resize', 'cv2.resize', (['output[channel, :]', '(sample[1].shape[2], sample[1].shape[1])'], {'interpolation': 'cv2.INTER_CUBIC'}), '(output[channel, :], (sample[1].shape[2], sample[1].shape[1]),\n interpolation=cv2.INTER_CUBIC)\n', (4761, 4858), False, 'import cv2\n'), ((4972, 5000), 'chainer.cuda.to_gpu', 'cuda.to_gpu', (['input_bat', 'None'], {}), '(input_bat, None)\n', (4983, 5000), False, 'from chainer import cuda, serializers, Variable\n'), ((5069, 5095), 'chainer.no_backprop_mode', 'chainer.no_backprop_mode', ([], {}), '()\n', (5093, 5095), False, 'import chainer\n'), ((1122, 1147), 'chainer.cuda.get_device', 'cuda.get_device', (['self.gpu'], {}), '(self.gpu)\n', (1137, 1147), False, 'from chainer import cuda, serializers, Variable\n'), ((2720, 2745), 'chainer.cuda.get_device', 'cuda.get_device', (['self.gpu'], {}), '(self.gpu)\n', (2735, 2745), False, 'from chainer import cuda, serializers, Variable\n'), ((3251, 3262), 'chainer.Variable', 'Variable', (['x'], {}), '(x)\n', (3259, 3262), False, 'from chainer import cuda, serializers, Variable\n'), ((3463, 3488), 'chainer.cuda.get_device', 'cuda.get_device', (['self.gpu'], {}), '(self.gpu)\n', (3478, 3488), False, 'from chainer import cuda, serializers, Variable\n'), ((4299, 4325), 'chainer.Variable', 'Variable', (['sample_container'], {}), '(sample_container)\n', (4307, 4325), False, 'from chainer import cuda, serializers, Variable\n'), ((5118, 5154), 'chainer.using_config', 'chainer.using_config', (['"""train"""', '(False)'], {}), "('train', False)\n", (5138, 5154), False, 'import chainer\n'), ((5215, 5229), 'chainer.Variable', 'Variable', (['link'], {}), '(link)\n', (5223, 5229), False, 'from chainer import cuda, serializers, Variable\n')]
|
from flee import flee, SimulationSettings
from datamanager import handle_refugee_data
from datamanager import DataTable #DataTable.subtract_dates()
from flee import InputGeography
import numpy as np
import outputanalysis.analysis as a
import sys
import visualization.vis
from datetime import datetime
from datetime import timedelta
def AddInitialRefugees(e, d, loc):
""" Add the initial refugees to a location, using the location name"""
num_refugees = int(d.get_field(loc.name, 0, FullInterpolation=True))
for i in range(0, num_refugees):
e.addAgent(location=loc)
def date_to_sim_days(date):
return DataTable.subtract_dates(date,"2013-12-01")
if __name__ == "__main__":
end_time = 820
last_physical_day = 820
if len(sys.argv)>1:
if (sys.argv[1]).isnumeric():
end_time = int(sys.argv[1])
last_physical_day = int(sys.argv[1])
else:
end_time = 820
last_physical_day = 820
duration = flee.SimulationSettings.SimulationSettings.ReadFromCSV(sys.argv[1])
if duration>0:
end_time = duration
last_physical_day = end_time
e = flee.Ecosystem()
ig = InputGeography.InputGeography()
ig.ReadLocationsFromCSV("examples/car_input_csv/locations.csv")
ig.ReadLinksFromCSV("examples/car_input_csv/routes.csv")
ig.ReadClosuresFromCSV("examples/car_input_csv/closures.csv")
e,lm = ig.StoreInputGeographyInEcosystem(e)
#print("Network data loaded")
d = handle_refugee_data.RefugeeTable(csvformat="generic", data_directory="source_data/car2014/", start_date="2013-12-01", data_layout="data_layout.csv")
#Correcting for overestimations due to inaccurate level 1 registrations in five of the camps.
#These errors led to a perceived large drop in refugee population in all of these camps.
#We correct by linearly scaling the values down to make the last level 1 registration match the first level 2 registration value.
#To our knowledge, all level 2 registration procedures were put in place by the end of 2016.
d.correctLevel1Registrations("Amboko","2015-09-30")
d.correctLevel1Registrations("Belom","2015-08-31")
d.correctLevel1Registrations("Dosseye","2015-09-30")
d.correctLevel1Registrations("Gondje","2015-09-30")
lm["Moyo"].capacity *= d.correctLevel1Registrations("Moyo","2015-06-02") #also "2014-05-11" and "2015-06-02"
d.correctLevel1Registrations("East","2014-09-28")
d.correctLevel1Registrations("Adamaoua","2014-10-19")
d.correctLevel1Registrations("Bili","2016-06-30")
d.correctLevel1Registrations("Boyabu","2016-06-30")
d.correctLevel1Registrations("Inke","2014-06-30")
d.correctLevel1Registrations("Betou","2014-03-22")
lm["Amboko"].capacity = d.getMaxFromData("Amboko", last_physical_day)
lm["Belom"].capacity = d.getMaxFromData("Belom", last_physical_day) # set manually.
lm["Dosseye"].capacity = d.getMaxFromData("Dosseye", last_physical_day)
lm["Gondje"].capacity = d.getMaxFromData("Gondje", last_physical_day)
#lm["Moyo"].capacity = d.getMaxFromData("Moyo", last_physical_day ) # blip in the data set, set capacity manually.
lm["East"].capacity = d.getMaxFromData("East", last_physical_day)
lm["Adamaoua"].capacity = d.getMaxFromData("Adamaoua", last_physical_day)
lm["Mole"].capacity = d.getMaxFromData("Mole", last_physical_day)
lm["Bili"].capacity = d.getMaxFromData("Bili", last_physical_day)
#lm["Bossobolo"].capacity = d.getMaxFromData("Bossobolo", last_physical_day) #camp excluded
lm["Boyabu"].capacity = d.getMaxFromData("Boyabu", last_physical_day)
lm["Mboti"].capacity = d.getMaxFromData("Mboti", last_physical_day)
lm["Inke"].capacity = d.getMaxFromData("Inke", last_physical_day)
lm["Betou"].capacity = d.getMaxFromData("Betou", last_physical_day)
lm["Brazaville"].capacity = d.getMaxFromData("Brazaville", last_physical_day)
output_header_string = "Day,"
camp_locations = ["Amboko","Belom","Dosseye","Gondje","Moyo","East","Adamaoua","Mole","Bili","Boyabu","Mboti","Inke","Betou","Brazaville"]
#TODO: Add Camps from CSV based on their location type.
for l in camp_locations:
AddInitialRefugees(e,d,lm[l])
output_header_string += "%s sim,%s data,%s error," % (lm[l].name, lm[l].name, lm[l].name)
output_header_string += "Total error,refugees in camps (UNHCR),total refugees (simulation),raw UNHCR refugee count,refugees in camps (simulation),refugee_debt"
print(output_header_string)
# Set up a mechanism to incorporate temporary decreases in refugees
refugee_debt = 0
refugees_raw = 0 #raw (interpolated) data from TOTAL UNHCR refugee count only.
visoutput = visualization.vis.VisManager(SimulationSettings.SimulationSettings.DefaultVisPath / "car.json")
start_date = datetime(2013, 12, 1)
current_date = datetime(2013, 12, 1)
for t in range(0,end_time):
ig.AddNewConflictZones(e,t)
# Determine number of new refugees to insert into the system.
new_refs = d.get_daily_difference(t, FullInterpolation=True) - refugee_debt
refugees_raw += d.get_daily_difference(t, FullInterpolation=True)
if new_refs < 0:
refugee_debt = -new_refs
new_refs = 0
elif refugee_debt > 0:
refugee_debt = 0
#Insert refugee agents
for i in range(0, new_refs):
e.addAgent(e.pick_conflict_location())
e.refresh_conflict_weights()
t_data = t
e.enact_border_closures(t)
e.evolve()
#Calculation of error terms
errors = []
abs_errors = []
loc_data = []
camps = []
for i in camp_locations:
camps += [lm[i]]
loc_data += [d.get_field(i, t)]
refugees_in_camps_sim = 0
for c in camps:
refugees_in_camps_sim += c.numAgents
# calculate errors
j=0
for i in camp_locations:
errors += [a.rel_error(lm[i].numAgents, loc_data[j])]
abs_errors += [a.abs_error(lm[i].numAgents, loc_data[j])]
j += 1
output = "%s" % t
for i in range(0,len(errors)):
output += ",%s,%s,%s" % (lm[camp_locations[i]].numAgents, loc_data[i], errors[i])
if refugees_raw>0:
#output_string += ",%s,%s,%s,%s" % (float(np.sum(abs_errors))/float(refugees_raw), int(sum(loc_data)), e.numAgents(), refugees_raw)
output += ",%s,%s,%s,%s,%s,%s" % (float(np.sum(abs_errors))/float(refugees_raw), int(sum(loc_data)), e.numAgents(), refugees_raw, refugees_in_camps_sim, refugee_debt)
else:
output += ",0,0,0,0,0,0,0"
#output_string += ",0"
print(output)
assert t == visoutput.addTimeStep(current_date.strftime("%Y-%m-%d"))
visoutput.addLocationDataAtTime(t, e.locations)
current_date = current_date + timedelta(days=1)
visoutput.setMetaData([5.725311, 19.488373], start_date.strftime("%Y-%m-%d"), "CAR", "CAR visualization")
visoutput.saveVisData()
|
[
"outputanalysis.analysis.abs_error",
"flee.flee.Ecosystem",
"flee.InputGeography.InputGeography",
"numpy.sum",
"datamanager.handle_refugee_data.RefugeeTable",
"datamanager.DataTable.subtract_dates",
"datetime.datetime",
"datetime.timedelta",
"outputanalysis.analysis.rel_error",
"flee.flee.SimulationSettings.SimulationSettings.ReadFromCSV"
] |
[((614, 658), 'datamanager.DataTable.subtract_dates', 'DataTable.subtract_dates', (['date', '"""2013-12-01"""'], {}), "(date, '2013-12-01')\n", (638, 658), False, 'from datamanager import DataTable\n'), ((1104, 1120), 'flee.flee.Ecosystem', 'flee.Ecosystem', ([], {}), '()\n', (1118, 1120), False, 'from flee import flee, SimulationSettings\n'), ((1129, 1160), 'flee.InputGeography.InputGeography', 'InputGeography.InputGeography', ([], {}), '()\n', (1158, 1160), False, 'from flee import InputGeography\n'), ((1440, 1598), 'datamanager.handle_refugee_data.RefugeeTable', 'handle_refugee_data.RefugeeTable', ([], {'csvformat': '"""generic"""', 'data_directory': '"""source_data/car2014/"""', 'start_date': '"""2013-12-01"""', 'data_layout': '"""data_layout.csv"""'}), "(csvformat='generic', data_directory=\n 'source_data/car2014/', start_date='2013-12-01', data_layout=\n 'data_layout.csv')\n", (1472, 1598), False, 'from datamanager import handle_refugee_data\n'), ((4691, 4712), 'datetime.datetime', 'datetime', (['(2013)', '(12)', '(1)'], {}), '(2013, 12, 1)\n', (4699, 4712), False, 'from datetime import datetime\n'), ((4730, 4751), 'datetime.datetime', 'datetime', (['(2013)', '(12)', '(1)'], {}), '(2013, 12, 1)\n', (4738, 4751), False, 'from datetime import datetime\n'), ((943, 1010), 'flee.flee.SimulationSettings.SimulationSettings.ReadFromCSV', 'flee.SimulationSettings.SimulationSettings.ReadFromCSV', (['sys.argv[1]'], {}), '(sys.argv[1])\n', (997, 1010), False, 'from flee import flee, SimulationSettings\n'), ((6577, 6594), 'datetime.timedelta', 'timedelta', ([], {'days': '(1)'}), '(days=1)\n', (6586, 6594), False, 'from datetime import timedelta\n'), ((5722, 5763), 'outputanalysis.analysis.rel_error', 'a.rel_error', (['lm[i].numAgents', 'loc_data[j]'], {}), '(lm[i].numAgents, loc_data[j])\n', (5733, 5763), True, 'import outputanalysis.analysis as a\n'), ((5786, 5827), 'outputanalysis.analysis.abs_error', 'a.abs_error', (['lm[i].numAgents', 'loc_data[j]'], {}), '(lm[i].numAgents, loc_data[j])\n', (5797, 5827), True, 'import outputanalysis.analysis as a\n'), ((6199, 6217), 'numpy.sum', 'np.sum', (['abs_errors'], {}), '(abs_errors)\n', (6205, 6217), True, 'import numpy as np\n')]
|
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import matplotlib.patches as mpatches
#importing dataset and converting to datasframe
data = pd.read_csv('heart.csv', header=None)
df = pd.DataFrame(data) #data frame
y = df.iloc[:, 13]
y = y-1
def chol_age():
x = df.iloc[:, 0:5]
x = x.drop(x.columns[1:4], axis=1)
chol_avgs = x.groupby(0, sort=True).mean()
ages = (chol_avgs[4].index.values)
avgs = (chol_avgs[4].values)
plt.plot(ages,avgs,'g-')
plt.title('Variation of Cholestrol Levels with Age')
plt.xlabel('Age(years)')
plt.ylabel('Serum Cholestrol in mg/dl')
def heart_atrack_heart_rate_bp():
x = df.iloc[:, 0:14]
x[14] = np.round(df[3], -1)
x_dis = x[x[13] == 2]
bp_set_dis = x_dis.groupby(14, sort=True)
nums_dis = (bp_set_dis.count()[0]).index.values
bps_dis = (bp_set_dis.count()[0]).values
bar2 = plt.bar(nums_dis+2, bps_dis, color='r', width=2)
x_nor = x[x[13] == 1]
bp_set_nor = x_nor.groupby(14, sort=True)
nums_nor = (bp_set_nor.count()[0]).index.values
bps_nor = (bp_set_nor.count()[0]).values
bar1 = plt.bar(nums_nor, bps_nor, color='g', width=2)
plt.title('Resting blood pressure as heart risk indicator')
plt.xlabel('Resting Blood Pressure Bucket')
plt.ylabel('Number of Patients')
plt.legend((bar1[0], bar2[0]), ('Safe', 'At Risk'))
def pie_chart_chest_pain():
x = df.iloc[:, 0:3]
sets = x.groupby(2).count()
fin_lab = ['Typical Angina', 'Atypical Angina', 'Non-anginal Pain', 'Asymptotic']
values = (sets[0].values)
plt.pie(values, labels=fin_lab, colors=['yellowgreen', 'gold', 'lightskyblue', 'lightcoral'], explode = [0,0.2,0,0], shadow=True, autopct='%1.1f%%', startangle=90)
plt.title('Chest Pain Types')
def scatter_chart():
x = df.iloc[:, 0:13]
sc = plt.scatter(x[7],x[4], c=y, cmap='summer')
plt.title('Dataset Scatter')
classes = ['Safe', 'At Risk']
class_colours = ['g','y']
recs = []
for i in range(0,len(class_colours)):
recs.append(mpatches.Rectangle((0,0),1,1,fc=class_colours[i]))
plt.legend(recs, classes)
plt.show()
|
[
"matplotlib.pyplot.title",
"pandas.DataFrame",
"matplotlib.pyplot.show",
"matplotlib.pyplot.plot",
"matplotlib.patches.Rectangle",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.bar",
"matplotlib.pyplot.legend",
"matplotlib.pyplot.pie",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"numpy.round"
] |
[((165, 202), 'pandas.read_csv', 'pd.read_csv', (['"""heart.csv"""'], {'header': 'None'}), "('heart.csv', header=None)\n", (176, 202), True, 'import pandas as pd\n'), ((209, 227), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (221, 227), True, 'import pandas as pd\n'), ((2018, 2028), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2026, 2028), True, 'import matplotlib.pyplot as plt\n'), ((453, 479), 'matplotlib.pyplot.plot', 'plt.plot', (['ages', 'avgs', '"""g-"""'], {}), "(ages, avgs, 'g-')\n", (461, 479), True, 'import matplotlib.pyplot as plt\n'), ((479, 531), 'matplotlib.pyplot.title', 'plt.title', (['"""Variation of Cholestrol Levels with Age"""'], {}), "('Variation of Cholestrol Levels with Age')\n", (488, 531), True, 'import matplotlib.pyplot as plt\n'), ((533, 557), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Age(years)"""'], {}), "('Age(years)')\n", (543, 557), True, 'import matplotlib.pyplot as plt\n'), ((559, 598), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Serum Cholestrol in mg/dl"""'], {}), "('Serum Cholestrol in mg/dl')\n", (569, 598), True, 'import matplotlib.pyplot as plt\n'), ((665, 684), 'numpy.round', 'np.round', (['df[3]', '(-1)'], {}), '(df[3], -1)\n', (673, 684), True, 'import numpy as np\n'), ((851, 901), 'matplotlib.pyplot.bar', 'plt.bar', (['(nums_dis + 2)', 'bps_dis'], {'color': '"""r"""', 'width': '(2)'}), "(nums_dis + 2, bps_dis, color='r', width=2)\n", (858, 901), True, 'import matplotlib.pyplot as plt\n'), ((1066, 1112), 'matplotlib.pyplot.bar', 'plt.bar', (['nums_nor', 'bps_nor'], {'color': '"""g"""', 'width': '(2)'}), "(nums_nor, bps_nor, color='g', width=2)\n", (1073, 1112), True, 'import matplotlib.pyplot as plt\n'), ((1115, 1174), 'matplotlib.pyplot.title', 'plt.title', (['"""Resting blood pressure as heart risk indicator"""'], {}), "('Resting blood pressure as heart risk indicator')\n", (1124, 1174), True, 'import matplotlib.pyplot as plt\n'), ((1176, 1219), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Resting Blood Pressure Bucket"""'], {}), "('Resting Blood Pressure Bucket')\n", (1186, 1219), True, 'import matplotlib.pyplot as plt\n'), ((1221, 1253), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Number of Patients"""'], {}), "('Number of Patients')\n", (1231, 1253), True, 'import matplotlib.pyplot as plt\n'), ((1256, 1307), 'matplotlib.pyplot.legend', 'plt.legend', (['(bar1[0], bar2[0])', "('Safe', 'At Risk')"], {}), "((bar1[0], bar2[0]), ('Safe', 'At Risk'))\n", (1266, 1307), True, 'import matplotlib.pyplot as plt\n'), ((1498, 1670), 'matplotlib.pyplot.pie', 'plt.pie', (['values'], {'labels': 'fin_lab', 'colors': "['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']", 'explode': '[0, 0.2, 0, 0]', 'shadow': '(True)', 'autopct': '"""%1.1f%%"""', 'startangle': '(90)'}), "(values, labels=fin_lab, colors=['yellowgreen', 'gold',\n 'lightskyblue', 'lightcoral'], explode=[0, 0.2, 0, 0], shadow=True,\n autopct='%1.1f%%', startangle=90)\n", (1505, 1670), True, 'import matplotlib.pyplot as plt\n'), ((1663, 1692), 'matplotlib.pyplot.title', 'plt.title', (['"""Chest Pain Types"""'], {}), "('Chest Pain Types')\n", (1672, 1692), True, 'import matplotlib.pyplot as plt\n'), ((1743, 1786), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x[7]', 'x[4]'], {'c': 'y', 'cmap': '"""summer"""'}), "(x[7], x[4], c=y, cmap='summer')\n", (1754, 1786), True, 'import matplotlib.pyplot as plt\n'), ((1787, 1815), 'matplotlib.pyplot.title', 'plt.title', (['"""Dataset Scatter"""'], {}), "('Dataset Scatter')\n", (1796, 1815), True, 'import matplotlib.pyplot as plt\n'), ((1990, 2015), 'matplotlib.pyplot.legend', 'plt.legend', (['recs', 'classes'], {}), '(recs, classes)\n', (2000, 2015), True, 'import matplotlib.pyplot as plt\n'), ((1938, 1991), 'matplotlib.patches.Rectangle', 'mpatches.Rectangle', (['(0, 0)', '(1)', '(1)'], {'fc': 'class_colours[i]'}), '((0, 0), 1, 1, fc=class_colours[i])\n', (1956, 1991), True, 'import matplotlib.patches as mpatches\n')]
|
# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of NVIDIA CORPORATION nor the names of its
# contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY
# EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
# EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
# PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
# OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import sys
sys.path.append("../common")
import math
import unittest
import numpy as np
from tensorrtserver.api import *
import test_util as tu
class LargePayLoadTest(unittest.TestCase):
def setUp(self):
self.data_type_ = np.float32
# n GB divided by element size
self.input_size_ = math.trunc(6 * (1024 * 1024 * 1024) / np.dtype(self.data_type_).itemsize)
self.protocols_ = ((ProtocolType.HTTP, 'localhost:8000'),
(ProtocolType.GRPC, 'localhost:8001'))
def _test_helper(self, ctx, tensor_shape, small_tensor_shape,
input_name='INPUT0', output_name='OUTPUT0'):
try:
in0 = np.random.random(tensor_shape).astype(self.data_type_)
results = ctx.run({ input_name : (in0,)},
{ output_name : InferContext.ResultFormat.RAW},
1)
# if the inference is completed, examine results to ensure that
# the framework and protocol do support large payload
self.assertTrue(np.array_equal(in0, results[output_name][0]), "output is different from input")
except InferenceServerException as ex:
# if the inference failed, inference server should return error
# gracefully. In addition to this, send a small payload to
# verify if the server is still functional
sin0 = np.random.random(small_tensor_shape).astype(self.data_type_)
results = ctx.run({ input_name : (sin0,)},
{ output_name : InferContext.ResultFormat.RAW},
1)
self.assertTrue(np.array_equal(sin0, results[output_name][0]), "output is different from input")
def test_graphdef(self):
tensor_shape = (self.input_size_,)
small_tensor_shape = (1,)
# graphdef_nobatch_zero_1_float32 is identity model with input shape [-1]
for protocol, url in self.protocols_:
model_name = tu.get_zero_model_name("graphdef_nobatch", 1, self.data_type_)
ctx = InferContext(url, protocol, model_name, None, True)
self._test_helper(ctx, tensor_shape, small_tensor_shape)
def test_savedmodel(self):
tensor_shape = (self.input_size_,)
small_tensor_shape = (1,)
# savedmodel_nobatch_zero_1_float32 is identity model with input shape [-1]
for protocol, url in self.protocols_:
model_name = tu.get_zero_model_name("savedmodel_nobatch", 1, self.data_type_)
ctx = InferContext(url, protocol, model_name, None, True)
self._test_helper(ctx, tensor_shape, small_tensor_shape)
def test_netdef(self):
tensor_shape = (self.input_size_,)
small_tensor_shape = (1,)
# netdef_nobatch_zero_1_float32 is identity model with input shape [-1]
for protocol, url in self.protocols_:
model_name = tu.get_zero_model_name("netdef_nobatch", 1, self.data_type_)
ctx = InferContext(url, protocol, model_name, None, True)
self._test_helper(ctx, tensor_shape, small_tensor_shape)
def test_onnx(self):
tensor_shape = (self.input_size_,)
small_tensor_shape = (1,)
# onnx_nobatch_zero_1_float32 is identity model with input shape [-1]
for protocol, url in self.protocols_:
model_name = tu.get_zero_model_name("onnx_nobatch", 1, self.data_type_)
ctx = InferContext(url, protocol, model_name, None, True)
self._test_helper(ctx, tensor_shape, small_tensor_shape)
def test_plan(self):
tensor_shape = (self.input_size_,)
small_tensor_shape = (1,)
# plan_nobatch_zero_1_float32 is identity model with input shape [-1]
for protocol, url in self.protocols_:
model_name = tu.get_zero_model_name("plan_nobatch", 1, self.data_type_)
ctx = InferContext(url, protocol, model_name, None, True)
self._test_helper(ctx, tensor_shape, small_tensor_shape)
def test_libtorch(self):
tensor_shape = (self.input_size_,)
small_tensor_shape = (1,)
# libtorch_nobatch_zero_1_float32 is identity model with input shape [-1]
for protocol, url in self.protocols_:
model_name = tu.get_zero_model_name("libtorch_nobatch", 1, self.data_type_)
ctx = InferContext(url, protocol, model_name, None, True)
self._test_helper(ctx, tensor_shape, small_tensor_shape,
'INPUT__0', 'OUTPUT__0')
def test_custom(self):
tensor_shape = (self.input_size_,)
small_tensor_shape = (1,)
# custom_zero_1_float32 is identity model with input shape [-1]
for protocol, url in self.protocols_:
model_name = tu.get_zero_model_name("custom", 1, self.data_type_)
ctx = InferContext(url, protocol, model_name, None, True)
self._test_helper(ctx, tensor_shape, small_tensor_shape)
if __name__ == '__main__':
unittest.main()
|
[
"sys.path.append",
"unittest.main",
"numpy.dtype",
"test_util.get_zero_model_name",
"numpy.random.random",
"numpy.array_equal"
] |
[((1545, 1573), 'sys.path.append', 'sys.path.append', (['"""../common"""'], {}), "('../common')\n", (1560, 1573), False, 'import sys\n'), ((6563, 6578), 'unittest.main', 'unittest.main', ([], {}), '()\n', (6576, 6578), False, 'import unittest\n'), ((3541, 3603), 'test_util.get_zero_model_name', 'tu.get_zero_model_name', (['"""graphdef_nobatch"""', '(1)', 'self.data_type_'], {}), "('graphdef_nobatch', 1, self.data_type_)\n", (3563, 3603), True, 'import test_util as tu\n'), ((4008, 4072), 'test_util.get_zero_model_name', 'tu.get_zero_model_name', (['"""savedmodel_nobatch"""', '(1)', 'self.data_type_'], {}), "('savedmodel_nobatch', 1, self.data_type_)\n", (4030, 4072), True, 'import test_util as tu\n'), ((4469, 4529), 'test_util.get_zero_model_name', 'tu.get_zero_model_name', (['"""netdef_nobatch"""', '(1)', 'self.data_type_'], {}), "('netdef_nobatch', 1, self.data_type_)\n", (4491, 4529), True, 'import test_util as tu\n'), ((4922, 4980), 'test_util.get_zero_model_name', 'tu.get_zero_model_name', (['"""onnx_nobatch"""', '(1)', 'self.data_type_'], {}), "('onnx_nobatch', 1, self.data_type_)\n", (4944, 4980), True, 'import test_util as tu\n'), ((5373, 5431), 'test_util.get_zero_model_name', 'tu.get_zero_model_name', (['"""plan_nobatch"""', '(1)', 'self.data_type_'], {}), "('plan_nobatch', 1, self.data_type_)\n", (5395, 5431), True, 'import test_util as tu\n'), ((5832, 5894), 'test_util.get_zero_model_name', 'tu.get_zero_model_name', (['"""libtorch_nobatch"""', '(1)', 'self.data_type_'], {}), "('libtorch_nobatch', 1, self.data_type_)\n", (5854, 5894), True, 'import test_util as tu\n'), ((6338, 6390), 'test_util.get_zero_model_name', 'tu.get_zero_model_name', (['"""custom"""', '(1)', 'self.data_type_'], {}), "('custom', 1, self.data_type_)\n", (6360, 6390), True, 'import test_util as tu\n'), ((2599, 2643), 'numpy.array_equal', 'np.array_equal', (['in0', 'results[output_name][0]'], {}), '(in0, results[output_name][0])\n', (2613, 2643), True, 'import numpy as np\n'), ((1884, 1909), 'numpy.dtype', 'np.dtype', (['self.data_type_'], {}), '(self.data_type_)\n', (1892, 1909), True, 'import numpy as np\n'), ((2213, 2243), 'numpy.random.random', 'np.random.random', (['tensor_shape'], {}), '(tensor_shape)\n', (2229, 2243), True, 'import numpy as np\n'), ((3199, 3244), 'numpy.array_equal', 'np.array_equal', (['sin0', 'results[output_name][0]'], {}), '(sin0, results[output_name][0])\n', (3213, 3244), True, 'import numpy as np\n'), ((2948, 2984), 'numpy.random.random', 'np.random.random', (['small_tensor_shape'], {}), '(small_tensor_shape)\n', (2964, 2984), True, 'import numpy as np\n')]
|
# This code is part of Qiskit.
#
# (C) Copyright IBM 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
""" PrimitiveOp Class """
from typing import Dict, List, Optional, Set, Union, cast
import numpy as np
import scipy.linalg
from scipy.sparse import spmatrix
from qiskit import QuantumCircuit
from qiskit.circuit import Instruction, ParameterExpression
from qiskit.opflow.operator_base import OperatorBase
from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector
class PrimitiveOp(OperatorBase):
r"""
A class for representing basic Operators, backed by Operator primitives from
Terra. This class (and inheritors) primarily serves to allow the underlying
primitives to "flow" - i.e. interoperability and adherence to the Operator formalism
- while the core computational logic mostly remains in the underlying primitives.
For example, we would not produce an interface in Terra in which
``QuantumCircuit1 + QuantumCircuit2`` equaled the Operator sum of the circuit
unitaries, rather than simply appending the circuits. However, within the Operator
flow summing the unitaries is the expected behavior.
Note that all mathematical methods are not in-place, meaning that they return a
new object, but the underlying primitives are not copied.
"""
def __init_subclass__(cls):
cls.__new__ = lambda cls, *args, **kwargs: super().__new__(cls)
@staticmethod
# pylint: disable=unused-argument
def __new__(cls,
primitive: Union[Instruction, QuantumCircuit, List,
np.ndarray, spmatrix, Operator, Pauli, SparsePauliOp],
coeff: Union[complex, ParameterExpression] = 1.0) -> 'PrimitiveOp':
""" A factory method to produce the correct type of PrimitiveOp subclass
based on the primitive passed in. Primitive and coeff arguments are passed into
subclass's init() as-is automatically by new().
Args:
primitive: The operator primitive being wrapped.
coeff: A coefficient multiplying the primitive.
Returns:
The appropriate PrimitiveOp subclass for ``primitive``.
Raises:
TypeError: Unsupported primitive type passed.
"""
# pylint: disable=cyclic-import
if isinstance(primitive, (Instruction, QuantumCircuit)):
from .circuit_op import CircuitOp
return super().__new__(CircuitOp)
if isinstance(primitive, (list, np.ndarray, spmatrix, Operator)):
from .matrix_op import MatrixOp
return super().__new__(MatrixOp)
if isinstance(primitive, Pauli):
from .pauli_op import PauliOp
return super().__new__(PauliOp)
if isinstance(primitive, SparsePauliOp):
from .pauli_sum_op import PauliSumOp
return super().__new__(PauliSumOp)
raise TypeError('Unsupported primitive type {} passed into PrimitiveOp '
'factory constructor'.format(type(primitive)))
def __init__(self,
primitive: Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase],
coeff: Union[complex, ParameterExpression] = 1.0) -> None:
"""
Args:
primitive: The operator primitive being wrapped.
coeff: A coefficient multiplying the primitive.
"""
super().__init__()
self._primitive = primitive
self._coeff = coeff
@property
def primitive(self) -> Union[QuantumCircuit, Operator, Pauli, SparsePauliOp, OperatorBase]:
""" The primitive defining the underlying function of the Operator.
Returns:
The primitive object.
"""
return self._primitive
@property
def coeff(self) -> Union[complex, ParameterExpression]:
"""
The scalar coefficient multiplying the Operator.
Returns:
The coefficient.
"""
return self._coeff
@property
def num_qubits(self) -> int:
raise NotImplementedError
def primitive_strings(self) -> Set[str]:
raise NotImplementedError
def add(self, other: OperatorBase) -> OperatorBase:
raise NotImplementedError
def adjoint(self) -> OperatorBase:
raise NotImplementedError
def equals(self, other: OperatorBase) -> bool:
raise NotImplementedError
def mul(self, scalar: Union[complex, ParameterExpression]) -> OperatorBase:
if not isinstance(scalar, (int, float, complex, ParameterExpression)):
raise ValueError('Operators can only be scalar multiplied by float or complex, not '
'{} of type {}.'.format(scalar, type(scalar)))
# Need to return self.__class__ in case the object is one of the inherited OpPrimitives
return self.__class__(self.primitive, coeff=self.coeff * scalar)
def tensor(self, other: OperatorBase) -> OperatorBase:
raise NotImplementedError
def tensorpower(self, other: int) -> Union[OperatorBase, int]:
# Hack to make Z^(I^0) work as intended.
if other == 0:
return 1
if not isinstance(other, int) or other < 0:
raise TypeError('Tensorpower can only take positive int arguments')
temp = PrimitiveOp(self.primitive, coeff=self.coeff) # type: OperatorBase
for _ in range(other - 1):
temp = temp.tensor(self)
return temp
def compose(self, other: OperatorBase,
permutation: Optional[List[int]] = None, front: bool = False) -> \
OperatorBase:
# pylint: disable=cyclic-import
from ..list_ops.composed_op import ComposedOp
new_self, other = self._expand_shorter_operator_and_permute(other, permutation)
if isinstance(other, ComposedOp):
comp_with_first = new_self.compose(other.oplist[0])
if not isinstance(comp_with_first, ComposedOp):
new_oplist = [comp_with_first] + other.oplist[1:]
return ComposedOp(new_oplist, coeff=other.coeff)
return ComposedOp([new_self] + other.oplist, coeff=other.coeff)
return ComposedOp([new_self, other])
def power(self, exponent: int) -> OperatorBase:
if not isinstance(exponent, int) or exponent <= 0:
raise TypeError('power can only take positive int arguments')
temp = PrimitiveOp(self.primitive, coeff=self.coeff) # type: OperatorBase
for _ in range(exponent - 1):
temp = temp.compose(self)
return temp
def _expand_dim(self, num_qubits: int) -> OperatorBase:
raise NotImplementedError
def permute(self, permutation: List[int]) -> OperatorBase:
raise NotImplementedError
def exp_i(self) -> OperatorBase:
""" Return Operator exponentiation, equaling e^(-i * op)"""
# pylint: disable=cyclic-import
from ..evolutions.evolved_op import EvolvedOp
return EvolvedOp(self)
def log_i(self, massive: bool = False) -> OperatorBase:
"""Return a ``MatrixOp`` equivalent to log(H)/-i for this operator H. This
function is the effective inverse of exp_i, equivalent to finding the Hermitian
Operator which produces self when exponentiated."""
# pylint: disable=cyclic-import
from ..operator_globals import EVAL_SIG_DIGITS
from .matrix_op import MatrixOp
return MatrixOp(np.around(scipy.linalg.logm(self.to_matrix(massive=massive)) / -1j,
decimals=EVAL_SIG_DIGITS))
def __str__(self) -> str:
raise NotImplementedError
def __repr__(self) -> str:
return "{}({}, coeff={})".format(type(self).__name__, repr(self.primitive), self.coeff)
def eval(
self,
front: Optional[
Union[str, Dict[str, complex], np.ndarray, OperatorBase, Statevector]
] = None,
) -> Union[OperatorBase, complex]:
raise NotImplementedError
@property
def parameters(self):
params = set()
if isinstance(self.primitive, (OperatorBase, QuantumCircuit)):
params.update(self.primitive.parameters)
if isinstance(self.coeff, ParameterExpression):
params.update(self.coeff.parameters)
return params
def assign_parameters(self, param_dict: dict) -> OperatorBase:
param_value = self.coeff
if isinstance(self.coeff, ParameterExpression):
unrolled_dict = self._unroll_param_dict(param_dict)
if isinstance(unrolled_dict, list):
# pylint: disable=cyclic-import
from ..list_ops.list_op import ListOp
return ListOp([self.assign_parameters(param_dict) for param_dict in unrolled_dict])
if self.coeff.parameters <= set(unrolled_dict.keys()):
binds = {param: unrolled_dict[param] for param in self.coeff.parameters}
param_value = float(self.coeff.bind(binds))
return self.__class__(self.primitive, coeff=param_value)
# Nothing to collapse here.
def reduce(self) -> OperatorBase:
return self
def to_matrix(self, massive: bool = False) -> np.ndarray:
raise NotImplementedError
def to_matrix_op(self, massive: bool = False) -> OperatorBase:
""" Returns a ``MatrixOp`` equivalent to this Operator. """
coeff = self.coeff
op = self.copy()
op._coeff = 1
prim_mat = op.to_matrix(massive=massive)
from .matrix_op import MatrixOp
return MatrixOp(prim_mat, coeff=coeff)
def to_instruction(self) -> Instruction:
""" Returns an ``Instruction`` equivalent to this Operator. """
raise NotImplementedError
def to_circuit(self) -> QuantumCircuit:
""" Returns a ``QuantumCircuit`` equivalent to this Operator. """
qc = QuantumCircuit(self.num_qubits)
qc.append(self.to_instruction(), qargs=range(self.primitive.num_qubits))
return qc.decompose()
def to_circuit_op(self) -> OperatorBase:
""" Returns a ``CircuitOp`` equivalent to this Operator. """
from .circuit_op import CircuitOp
if self.coeff == 0:
return CircuitOp(QuantumCircuit(self.num_qubits), coeff=0)
return CircuitOp(self.to_circuit(), coeff=self.coeff)
def to_pauli_op(self, massive: bool = False) -> OperatorBase:
""" Returns a sum of ``PauliOp`` s equivalent to this Operator. """
# pylint: disable=cyclic-import
from .matrix_op import MatrixOp
mat_op = cast(MatrixOp, self.to_matrix_op(massive=massive))
sparse_pauli = SparsePauliOp.from_operator(mat_op.primitive)
if not sparse_pauli.to_list():
from ..operator_globals import I
return (I ^ self.num_qubits) * 0.0
from .pauli_op import PauliOp
if len(sparse_pauli) == 1:
label, coeff = sparse_pauli.to_list()[0]
coeff = coeff.real if np.isreal(coeff) else coeff
return PauliOp(Pauli(label), coeff * self.coeff)
from ..list_ops.summed_op import SummedOp
return SummedOp(
[
PrimitiveOp(
Pauli(label),
coeff.real if coeff == coeff.real else coeff,
)
for (label, coeff) in sparse_pauli.to_list()
],
self.coeff,
)
|
[
"numpy.isreal",
"qiskit.quantum_info.Pauli",
"qiskit.quantum_info.SparsePauliOp.from_operator",
"qiskit.QuantumCircuit"
] |
[((10316, 10347), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['self.num_qubits'], {}), '(self.num_qubits)\n', (10330, 10347), False, 'from qiskit import QuantumCircuit\n'), ((11091, 11136), 'qiskit.quantum_info.SparsePauliOp.from_operator', 'SparsePauliOp.from_operator', (['mat_op.primitive'], {}), '(mat_op.primitive)\n', (11118, 11136), False, 'from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector\n'), ((10673, 10704), 'qiskit.QuantumCircuit', 'QuantumCircuit', (['self.num_qubits'], {}), '(self.num_qubits)\n', (10687, 10704), False, 'from qiskit import QuantumCircuit\n'), ((11428, 11444), 'numpy.isreal', 'np.isreal', (['coeff'], {}), '(coeff)\n', (11437, 11444), True, 'import numpy as np\n'), ((11483, 11495), 'qiskit.quantum_info.Pauli', 'Pauli', (['label'], {}), '(label)\n', (11488, 11495), False, 'from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector\n'), ((11656, 11668), 'qiskit.quantum_info.Pauli', 'Pauli', (['label'], {}), '(label)\n', (11661, 11668), False, 'from qiskit.quantum_info import Operator, Pauli, SparsePauliOp, Statevector\n')]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: Apache-2.0
# SPDX-FileCopyrightText: © 2021 Massachusetts Institute of Technology.
# SPDX-FileCopyrightText: © 2021 <NAME> <<EMAIL>>
# NOTICE: authors should document their contributions in concisely in NOTICE
# with details inline in source files, comments, and docstrings.
"""
Some utilities to help with dataset creation and annotation
"""
from wavestate.bunch import Bunch
import numpy as np
from .. import annotate
from .. import TFmath
from .. import representations
from .. import fitters_ZPK
from . import plots
def make_description(
generator, sets=1, instances=1, description=None, annotation=None, **kwargs
):
doc = generator.__doc__
if description is None:
if doc is not None:
description = annotate.padding_remove(doc)
else:
description = "<no description>"
else:
description = annotate.padding_remove(description)
if annotation is None and doc is not None:
annotation = annotate.padding_remove(doc)
return Bunch(
generator=generator,
instances=instances,
description=description,
annotation=annotation,
**kwargs
)
def generator_autofill(
F_Hz,
SNR,
F_nyquist_Hz,
data=None,
bestfit_ZPK_z=None,
bestfit_ZPK_s=None,
delay_s=0,
residuals_log_best=None,
sN=0,
iN=0,
**kwargs
):
if bestfit_ZPK_s:
# replace with the ZPKs filled out fully
bestfit_ZPK_s = TFmath.ZPK_fill(bestfit_ZPK_s)
if bestfit_ZPK_z:
# replace with the ZPKs filled out fully
bestfit_ZPK_z = TFmath.ZPK_fill(bestfit_ZPK_z)
if not bestfit_ZPK_z and F_nyquist_Hz is not None:
if bestfit_ZPK_s:
bestfit_ZPK_z = TFmath.StoZ(
bestfit_ZPK_s,
F_nyquist_Hz=F_nyquist_Hz,
)
if not bestfit_ZPK_s and F_nyquist_Hz is not None:
if bestfit_ZPK_z:
bestfit_ZPK_s = TFmath.ZtoS(
bestfit_ZPK_z,
F_nyquist_Hz=F_nyquist_Hz,
)
if data is None:
if SNR is not None:
rand = np.random.RandomState()
rand.seed(iN)
N = len(F_Hz)
rel_noise = rand.normal(1, 1 / SNR, N) + 1j * rand.normal(0, 1 / SNR, N)
else:
rel_noise = 1
if bestfit_ZPK_s:
data = rel_noise * TFmath.TF_ZPK(
F_Hz,
ZPK=bestfit_ZPK_s,
)
elif bestfit_ZPK_z:
data = rel_noise * TFmath.TF_ZPK(
F_Hz,
ZPK=bestfit_ZPK_s,
F_nyquist_Hz=F_nyquist_Hz,
)
if delay_s is not None:
data = data * np.exp(-2j * np.pi * delay_s * F_Hz)
if bestfit_ZPK_z is not None:
rep_z = representations.ZPKwData(
data=data,
F_Hz=F_Hz,
W=SNR,
F_nyquist_Hz=F_nyquist_Hz,
ZPK=bestfit_ZPK_z,
delay_s=delay_s,
)
else:
rep_z = None
if bestfit_ZPK_s is not None:
rep_s = representations.ZPKwData(
data=data,
F_Hz=F_Hz,
W=SNR,
F_nyquist_Hz=None,
ZPK=bestfit_ZPK_s,
delay_s=delay_s,
)
else:
rep_s = None
return Bunch(
F_Hz=F_Hz,
data=data,
SNR=SNR,
F_nyquist_Hz=F_nyquist_Hz,
residuals_log_best=residuals_log_best,
bestfit_ZPK_z=bestfit_ZPK_z,
bestfit_ZPK_s=bestfit_ZPK_s,
rep_z=rep_z,
rep_s=rep_s,
iN=iN,
sN=sN,
**kwargs
)
def assert_almost_equal(arr1, arr2, decimals):
np.testing.assert_allclose(arr1, arr2, decimals)
# np.testing.assert_allclose(arr1.real, arr2.real, decimals)
# np.testing.assert_allclose(arr1.imag, arr2.imag, decimals)
def sign_validate(aid, fitter):
"""
To be added as a hint to data2filter
"""
rep = fitter.ZPKrep
xfer = rep.xfer_fit
data = rep.data
rat = data / xfer
rat_ang = np.exp(1j * np.angle(rat))
ang_avg_rep = np.sum(rat_ang * rep.W ** 2) / np.sum(rep.W ** 2)
xfer = fitter.xfer_fit
data = fitter.data
rat = data / xfer
rat_ang = np.exp(1j * np.angle(rat))
ang_avg_fit = np.sum(rat_ang * fitter.W ** 2) / np.sum(fitter.W ** 2)
# print("SGN: ", ang_avg_rep, ang_avg_fit)
# axB = plots.plots.plot_fit(
# fitter,
# fname = 'test1.png',
# )
# axB = plots.plots.plot_fitter_flag(
# fitter,
# fname = 'test3.png',
# )
# axB = plots.plots.plot_fit(
# fitter.ZPKrep,
# fname = 'test2.png',
# )
if isinstance(fitter, fitters_ZPK.MultiReprFilterBase):
for coding in list(fitter.num_codings) + list(fitter.den_codings):
rB = representations.RootBunch(
u=coding.roots(),
constraint=representations.root_constraints.no_constraint,
)
h1 = coding.transfer()
h, lnG = rB.val_lnG(fitter.Xex_grid)
h = h * np.exp(lnG)
assert_almost_equal(h / h1, 1, 4)
assert ang_avg_fit.real > 0 and ang_avg_rep.real > 0
sign_validate_hint = {
"fitter_update_validate": sign_validate,
"fitter_check_validate": sign_validate,
}
def rational_fitter_validate(rat_fitter, fitter):
"""
To be added as a hint to data2filter
"""
rep1 = rat_fitter.ZPKrep.xfer_fit
rep2 = fitter.ZPKrep.xfer_fit
rat = rat_fitter.xfer_fit
mrf = fitter.xfer_fit
assert_almost_equal(rep1 / rep2, 1, 5)
assert_almost_equal(rat / rep2, 1, 5)
assert_almost_equal(mrf / rep2, 1, 5)
print("Checking Rational Fitter")
def sign_validate_and_plot_hint(pyfile, request):
def sign_validate_plot(aid, fitter):
with plots.plot_on_assert(pyfile, request, fitter, plot_anyway=False):
try:
sign_validate(aid, fitter)
except AssertionError:
print(fitter)
print(fitter.F_nyquist_Hz)
print(fitter.zeros)
print(fitter.zeros_overlay)
print(fitter.ZPKrep)
# assert(False)
raise
hint = {
"fitter_update_validate": sign_validate_plot,
"fitter_check_validate": sign_validate_plot,
"rational_fitter_validate": rational_fitter_validate,
}
return hint
def stability_validate_and_plot_hint(pyfile, request):
def sign_validate_plot(aid, fitter):
with plots.plot_on_assert(pyfile, request, fitter, plot_anyway=False):
assert np.all(fitter.ZPKrep.poles.c.real <= 0)
assert np.all(fitter.ZPKrep.poles.r.real <= 0)
try:
sign_validate(aid, fitter)
except AssertionError:
print(fitter)
print(fitter.F_nyquist_Hz)
print(fitter.zeros)
print(fitter.zeros_overlay)
print(fitter.ZPKrep)
# assert(False)
raise
hint = {
"fitter_update_validate": sign_validate_plot,
"fitter_check_validate": sign_validate_plot,
"rational_fitter_validate": rational_fitter_validate,
}
return hint
def sign_validate_and_digest_hint(pyfile, request):
def sign_validate_plot(aid, fitter):
with plots.digest_on_assert(pyfile, request, aid, plot_anyway=False):
try:
sign_validate(aid, fitter)
except AssertionError:
print(fitter)
print(fitter.F_nyquist_Hz)
print(fitter.zeros)
print(fitter.zeros_overlay)
print(fitter.ZPKrep)
# assert(False)
raise
hint = {
"fitter_update_validate": sign_validate_plot,
"fitter_check_validate": sign_validate_plot,
"rational_fitter_validate": rational_fitter_validate,
}
return hint
|
[
"numpy.sum",
"numpy.angle",
"numpy.random.RandomState",
"numpy.exp",
"wavestate.bunch.Bunch",
"numpy.testing.assert_allclose",
"numpy.all"
] |
[((1086, 1195), 'wavestate.bunch.Bunch', 'Bunch', ([], {'generator': 'generator', 'instances': 'instances', 'description': 'description', 'annotation': 'annotation'}), '(generator=generator, instances=instances, description=description,\n annotation=annotation, **kwargs)\n', (1091, 1195), False, 'from wavestate.bunch import Bunch\n'), ((3385, 3608), 'wavestate.bunch.Bunch', 'Bunch', ([], {'F_Hz': 'F_Hz', 'data': 'data', 'SNR': 'SNR', 'F_nyquist_Hz': 'F_nyquist_Hz', 'residuals_log_best': 'residuals_log_best', 'bestfit_ZPK_z': 'bestfit_ZPK_z', 'bestfit_ZPK_s': 'bestfit_ZPK_s', 'rep_z': 'rep_z', 'rep_s': 'rep_s', 'iN': 'iN', 'sN': 'sN'}), '(F_Hz=F_Hz, data=data, SNR=SNR, F_nyquist_Hz=F_nyquist_Hz,\n residuals_log_best=residuals_log_best, bestfit_ZPK_z=bestfit_ZPK_z,\n bestfit_ZPK_s=bestfit_ZPK_s, rep_z=rep_z, rep_s=rep_s, iN=iN, sN=sN, **\n kwargs)\n', (3390, 3608), False, 'from wavestate.bunch import Bunch\n'), ((3751, 3799), 'numpy.testing.assert_allclose', 'np.testing.assert_allclose', (['arr1', 'arr2', 'decimals'], {}), '(arr1, arr2, decimals)\n', (3777, 3799), True, 'import numpy as np\n'), ((4170, 4198), 'numpy.sum', 'np.sum', (['(rat_ang * rep.W ** 2)'], {}), '(rat_ang * rep.W ** 2)\n', (4176, 4198), True, 'import numpy as np\n'), ((4201, 4219), 'numpy.sum', 'np.sum', (['(rep.W ** 2)'], {}), '(rep.W ** 2)\n', (4207, 4219), True, 'import numpy as np\n'), ((4352, 4383), 'numpy.sum', 'np.sum', (['(rat_ang * fitter.W ** 2)'], {}), '(rat_ang * fitter.W ** 2)\n', (4358, 4383), True, 'import numpy as np\n'), ((4386, 4407), 'numpy.sum', 'np.sum', (['(fitter.W ** 2)'], {}), '(fitter.W ** 2)\n', (4392, 4407), True, 'import numpy as np\n'), ((2188, 2211), 'numpy.random.RandomState', 'np.random.RandomState', ([], {}), '()\n', (2209, 2211), True, 'import numpy as np\n'), ((4137, 4150), 'numpy.angle', 'np.angle', (['rat'], {}), '(rat)\n', (4145, 4150), True, 'import numpy as np\n'), ((4319, 4332), 'numpy.angle', 'np.angle', (['rat'], {}), '(rat)\n', (4327, 4332), True, 'import numpy as np\n'), ((6691, 6730), 'numpy.all', 'np.all', (['(fitter.ZPKrep.poles.c.real <= 0)'], {}), '(fitter.ZPKrep.poles.c.real <= 0)\n', (6697, 6730), True, 'import numpy as np\n'), ((6750, 6789), 'numpy.all', 'np.all', (['(fitter.ZPKrep.poles.r.real <= 0)'], {}), '(fitter.ZPKrep.poles.r.real <= 0)\n', (6756, 6789), True, 'import numpy as np\n'), ((2780, 2818), 'numpy.exp', 'np.exp', (['(-2.0j * np.pi * delay_s * F_Hz)'], {}), '(-2.0j * np.pi * delay_s * F_Hz)\n', (2786, 2818), True, 'import numpy as np\n'), ((5144, 5155), 'numpy.exp', 'np.exp', (['lnG'], {}), '(lnG)\n', (5150, 5155), True, 'import numpy as np\n')]
|
import numpy as np
import matplotlib
matplotlib.use('pdf')
import matplotlib.pyplot as plt
import traceback
Fs = 30.72e6
x1 = []
x2=[]
x5=[]
x_comp_0 = []
y_comp_0 = []
x_comp_1 = []
y_comp_1 = []
x_comp_2 = []
y_comp_2 = []
try:
f1 = open("/root/.files/free5GRAN/execution_raw_files/studied_frame.txt", "r")
for x in f1:
x = x.split("(")[1]
x = x.split(")")[0]
re = float(x.split(',')[0])
im = float(x.split(',')[1])
x1.append(complex(re,im))
fig1 = plt.figure()
plt.specgram(x1, NFFT=1024, Fs=Fs)
plt.xticks(np.arange(0, 0.01, 0.001))
plt.title("Studied Frame")
plt.ylim(-Fs/2, Fs/2)
plt.savefig("/root/.files/free5GRAN/visualization_files/studied_frame.pdf", bbox_inches='tight', pad_inches=0.5)
plt.close(fig1)
except Exception:
traceback.print_exc()
try:
f2 = open("/root/.files/free5GRAN/execution_raw_files/moniroting_slots.txt", "r")
for x in f2:
x = x.split("(")[1]
x = x.split(")")[0]
re = float(x.split(',')[0])
im = float(x.split(',')[1])
x2.append(complex(re,im))
fig2 = plt.figure()
plt.specgram(x2, NFFT=1024, Fs=Fs)
plt.yticks(np.arange(-15e6, 15e6, 2e6))
plt.title("Monitoring slots")
plt.ylim(-Fs/2, Fs/2)
plt.savefig("/root/.files/free5GRAN/visualization_files/moniroting_slots.pdf", bbox_inches='tight', pad_inches=0.5)
plt.close(fig2)
except Exception:
traceback.print_exc()
try:
f5 = open("/root/.files/free5GRAN/execution_raw_files/global_signal.txt", "r")
for x in f5:
x = x.split("(")[1]
x = x.split(")")[0]
re = float(x.split(',')[0])
im = float(x.split(',')[1])
x5.append(complex(re,im))
fig2 = plt.figure()
plt.specgram(x5, NFFT=1024, Fs=Fs)
plt.yticks(np.arange(-15e6, 15e6, 2e6))
plt.title("Global signal")
plt.ylim(-Fs/2, Fs/2)
plt.savefig("/root/.files/free5GRAN/visualization_files/global_signal.pdf", bbox_inches='tight', pad_inches=0.5)
plt.close(fig2)
except Exception:
traceback.print_exc()
try:
f3 = open("/root/.files/free5GRAN/execution_raw_files/pdcch_constellation.txt", "r")
for x in f3:
x = x.split("(")[1]
x = x.split(")")[0]
x_comp_0.append(float(x.split(',')[0]))
y_comp_0.append(float(x.split(',')[1]))
fig3 = plt.figure()
plt.scatter(x_comp_0,y_comp_0, color='red')
plt.title("PDCCH constellation")
plt.savefig("/root/.files/free5GRAN/visualization_files/pdcch_constellation.pdf")
plt.close(fig3)
except Exception:
traceback.print_exc()
try:
f4 = open("/root/.files/free5GRAN/execution_raw_files/pdsch_constellation.txt", "r")
for x in f4:
x = x.split("(")[1]
x = x.split(")")[0]
x_comp_1.append(float(x.split(',')[0]))
y_comp_1.append(float(x.split(',')[1]))
fig4 = plt.figure()
plt.scatter(x_comp_1,y_comp_1, color='red')
plt.title("PDSCH constellation")
plt.savefig("/root/.files/free5GRAN/visualization_files/pdsch_constellation.pdf")
plt.close(fig4)
except Exception:
traceback.print_exc()
|
[
"matplotlib.pyplot.title",
"matplotlib.pyplot.specgram",
"traceback.print_exc",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.close",
"matplotlib.pyplot.scatter",
"matplotlib.pyplot.figure",
"matplotlib.use",
"numpy.arange",
"matplotlib.pyplot.savefig"
] |
[((37, 58), 'matplotlib.use', 'matplotlib.use', (['"""pdf"""'], {}), "('pdf')\n", (51, 58), False, 'import matplotlib\n'), ((509, 521), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (519, 521), True, 'import matplotlib.pyplot as plt\n'), ((526, 560), 'matplotlib.pyplot.specgram', 'plt.specgram', (['x1'], {'NFFT': '(1024)', 'Fs': 'Fs'}), '(x1, NFFT=1024, Fs=Fs)\n', (538, 560), True, 'import matplotlib.pyplot as plt\n'), ((607, 633), 'matplotlib.pyplot.title', 'plt.title', (['"""Studied Frame"""'], {}), "('Studied Frame')\n", (616, 633), True, 'import matplotlib.pyplot as plt\n'), ((638, 663), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-Fs / 2)', '(Fs / 2)'], {}), '(-Fs / 2, Fs / 2)\n', (646, 663), True, 'import matplotlib.pyplot as plt\n'), ((664, 780), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""/root/.files/free5GRAN/visualization_files/studied_frame.pdf"""'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.5)'}), "('/root/.files/free5GRAN/visualization_files/studied_frame.pdf',\n bbox_inches='tight', pad_inches=0.5)\n", (675, 780), True, 'import matplotlib.pyplot as plt\n'), ((781, 796), 'matplotlib.pyplot.close', 'plt.close', (['fig1'], {}), '(fig1)\n', (790, 796), True, 'import matplotlib.pyplot as plt\n'), ((1127, 1139), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1137, 1139), True, 'import matplotlib.pyplot as plt\n'), ((1144, 1178), 'matplotlib.pyplot.specgram', 'plt.specgram', (['x2'], {'NFFT': '(1024)', 'Fs': 'Fs'}), '(x2, NFFT=1024, Fs=Fs)\n', (1156, 1178), True, 'import matplotlib.pyplot as plt\n'), ((1227, 1256), 'matplotlib.pyplot.title', 'plt.title', (['"""Monitoring slots"""'], {}), "('Monitoring slots')\n", (1236, 1256), True, 'import matplotlib.pyplot as plt\n'), ((1261, 1286), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-Fs / 2)', '(Fs / 2)'], {}), '(-Fs / 2, Fs / 2)\n', (1269, 1286), True, 'import matplotlib.pyplot as plt\n'), ((1287, 1406), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""/root/.files/free5GRAN/visualization_files/moniroting_slots.pdf"""'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.5)'}), "('/root/.files/free5GRAN/visualization_files/moniroting_slots.pdf',\n bbox_inches='tight', pad_inches=0.5)\n", (1298, 1406), True, 'import matplotlib.pyplot as plt\n'), ((1407, 1422), 'matplotlib.pyplot.close', 'plt.close', (['fig2'], {}), '(fig2)\n', (1416, 1422), True, 'import matplotlib.pyplot as plt\n'), ((1749, 1761), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1759, 1761), True, 'import matplotlib.pyplot as plt\n'), ((1766, 1800), 'matplotlib.pyplot.specgram', 'plt.specgram', (['x5'], {'NFFT': '(1024)', 'Fs': 'Fs'}), '(x5, NFFT=1024, Fs=Fs)\n', (1778, 1800), True, 'import matplotlib.pyplot as plt\n'), ((1849, 1875), 'matplotlib.pyplot.title', 'plt.title', (['"""Global signal"""'], {}), "('Global signal')\n", (1858, 1875), True, 'import matplotlib.pyplot as plt\n'), ((1880, 1905), 'matplotlib.pyplot.ylim', 'plt.ylim', (['(-Fs / 2)', '(Fs / 2)'], {}), '(-Fs / 2, Fs / 2)\n', (1888, 1905), True, 'import matplotlib.pyplot as plt\n'), ((1906, 2022), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""/root/.files/free5GRAN/visualization_files/global_signal.pdf"""'], {'bbox_inches': '"""tight"""', 'pad_inches': '(0.5)'}), "('/root/.files/free5GRAN/visualization_files/global_signal.pdf',\n bbox_inches='tight', pad_inches=0.5)\n", (1917, 2022), True, 'import matplotlib.pyplot as plt\n'), ((2023, 2038), 'matplotlib.pyplot.close', 'plt.close', (['fig2'], {}), '(fig2)\n', (2032, 2038), True, 'import matplotlib.pyplot as plt\n'), ((2361, 2373), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2371, 2373), True, 'import matplotlib.pyplot as plt\n'), ((2378, 2422), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_comp_0', 'y_comp_0'], {'color': '"""red"""'}), "(x_comp_0, y_comp_0, color='red')\n", (2389, 2422), True, 'import matplotlib.pyplot as plt\n'), ((2426, 2458), 'matplotlib.pyplot.title', 'plt.title', (['"""PDCCH constellation"""'], {}), "('PDCCH constellation')\n", (2435, 2458), True, 'import matplotlib.pyplot as plt\n'), ((2463, 2549), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""/root/.files/free5GRAN/visualization_files/pdcch_constellation.pdf"""'], {}), "(\n '/root/.files/free5GRAN/visualization_files/pdcch_constellation.pdf')\n", (2474, 2549), True, 'import matplotlib.pyplot as plt\n'), ((2549, 2564), 'matplotlib.pyplot.close', 'plt.close', (['fig3'], {}), '(fig3)\n', (2558, 2564), True, 'import matplotlib.pyplot as plt\n'), ((2888, 2900), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (2898, 2900), True, 'import matplotlib.pyplot as plt\n'), ((2905, 2949), 'matplotlib.pyplot.scatter', 'plt.scatter', (['x_comp_1', 'y_comp_1'], {'color': '"""red"""'}), "(x_comp_1, y_comp_1, color='red')\n", (2916, 2949), True, 'import matplotlib.pyplot as plt\n'), ((2953, 2985), 'matplotlib.pyplot.title', 'plt.title', (['"""PDSCH constellation"""'], {}), "('PDSCH constellation')\n", (2962, 2985), True, 'import matplotlib.pyplot as plt\n'), ((2990, 3076), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""/root/.files/free5GRAN/visualization_files/pdsch_constellation.pdf"""'], {}), "(\n '/root/.files/free5GRAN/visualization_files/pdsch_constellation.pdf')\n", (3001, 3076), True, 'import matplotlib.pyplot as plt\n'), ((3076, 3091), 'matplotlib.pyplot.close', 'plt.close', (['fig4'], {}), '(fig4)\n', (3085, 3091), True, 'import matplotlib.pyplot as plt\n'), ((576, 601), 'numpy.arange', 'np.arange', (['(0)', '(0.01)', '(0.001)'], {}), '(0, 0.01, 0.001)\n', (585, 601), True, 'import numpy as np\n'), ((820, 841), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (839, 841), False, 'import traceback\n'), ((1194, 1239), 'numpy.arange', 'np.arange', (['(-15000000.0)', '(15000000.0)', '(2000000.0)'], {}), '(-15000000.0, 15000000.0, 2000000.0)\n', (1203, 1239), True, 'import numpy as np\n'), ((1446, 1467), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (1465, 1467), False, 'import traceback\n'), ((1816, 1861), 'numpy.arange', 'np.arange', (['(-15000000.0)', '(15000000.0)', '(2000000.0)'], {}), '(-15000000.0, 15000000.0, 2000000.0)\n', (1825, 1861), True, 'import numpy as np\n'), ((2062, 2083), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (2081, 2083), False, 'import traceback\n'), ((2588, 2609), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (2607, 2609), False, 'import traceback\n'), ((3114, 3135), 'traceback.print_exc', 'traceback.print_exc', ([], {}), '()\n', (3133, 3135), False, 'import traceback\n')]
|
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
from functions_scenario import derivatives, sat_conc
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas import DataFrame
# Start hour h2 is for test only - in live version will be current time
h2 = 1095
h1 = h2-240 # select previous 10 days
ndp = int((h2-h1)/12) # number of data points used for calibration
# Input calibrated parameters output from calibration model
# Stored in database? Currently output to csv file
ACHinp = np.genfromtxt('ACH_out.csv', delimiter=',')
IASinp = np.genfromtxt('IAS_out.csv', delimiter=',')
# Calculate mean calibrated ACH, IAS and 5%, 95% quantiles
ACHcal = ACHinp[1:,-1*ndp:]*9+1 # selects ACH values corresponding to the last ndp data points
ACHmean = np.mean(ACHcal,0)
ACHuq = np.quantile(ACHcal,0.95,0)
ACHlq = np.quantile(ACHcal,0.05,0)
IAScal = IASinp[1:,-1*ndp:]*0.75+0.1
IASmean = np.mean(IAScal,0)
IASuq = np.quantile(IAScal,0.95,0)
IASlq = np.quantile(IAScal,0.05,0)
# Set up parameters for runs: 1) BAU mean, 2) Scenario, 3) BAU UQ, 4) BAU LQ
# Scenario values N, ndh and lshift will come from sliders on dashboard
test = np.zeros((ndp,4,4))
#for i in range(np.size(test,2)):
test[:,0,0] = ACHmean
test[:,1,0] = IASmean
test[:,2,0] = 1
test[:,3,0] = 0
test[:,0,1] = ACHmean
test[:,1,1] = IASmean
test[:,2,1] = 1
test[:,3,1] = 0
test[:,0,2] = ACHuq
test[:,1,2] = IASlq
test[:,2,2] = 1
test[:,3,2] = 0
test[:,0,3] = ACHlq
test[:,1,3] = IASuq
test[:,2,3] = 1
test[:,3,3] = 0
# Scenario 1 - vary ACH
N = 1 # ventilation rate inout from slider
ScenEval = np.zeros((8,4,4))
ScenEval[:,0,0] = ACHmean[-1]
ScenEval[:,0,1] = N # input from slider
ScenEval[:,0,2] = ACHuq[-1]
ScenEval[:,0,3] = ACHlq[-1]
ScenEval[:,1,0] = IASmean[-1]
ScenEval[:,1,1] = IASmean[-1]
ScenEval[:,1,2] = IASlq[-1]
ScenEval[:,1,3] = IASuq[-1]
# Scenario 2 - vary number of dehumidifiers
ndh = 2 # number of dehumidifiers
ScenEval[:,2,0] = 1
ScenEval[:,2,1] = ndh/2 # ndh input from slider (integer) (/2 as half farm modelled)
ScenEval[:,2,2] = 1
ScenEval[:,2,3] = 1
# Scenario 3 - shift lighting schedule (+/-hours)
lshift = -3
ScenEval[:,3,0] = 1
ScenEval[:,3,1] = lshift # lshift input from slider
ScenEval[:,3,2] = 1
ScenEval[:,3,3] = 1
params = np.concatenate((test, ScenEval)) # put scenario on the end of the calibrated parameters
## Run model, using time varying ACH, IAS corresponding to outputs from calibration for
# first 10 days, then scenario evaluation values for last 3 days
results = derivatives(h1, h2, params, ndp)
T_air = results[1,:,:]
Cw_air = results[11,:,:]
RH_air = Cw_air/sat_conc(T_air)
## Plot Results
p1 = h1 # start hour
delta_h = 12 # hours between data points
p2 = ndp*delta_h+p1 # end data point
seq = np.linspace(p1,p2,ndp+1,endpoint='true')
date_cols = ["DateTimex"]
Data = pd.read_csv("TRHE2018.csv", parse_dates=date_cols)
RHData =Data['MidFarmRH2']
TData =Data['MidFarmT']
#t = np.linspace(h1,h2+3*24,1+240+3*24)
t = np.linspace(h1-h2,3*24,1+240+3*24)
t1 = np.linspace(0,3*24,1+3*24)
td = np.linspace(h1-h2,0,21)
dpRH = RHData[seq]
dpT = TData[seq]+273.15
dpCw = dpRH/100 * sat_conc(dpT)
fig = plt.figure()
ax1 = fig.add_subplot(1,2,1)
plt.plot(t,T_air[:,0]-273.15,'r')
#p1 = plt.plot(t,T_air[:,2]-273.15,'r:')
#p2 = plt.plot(t,T_air[:,3]-273.15,'r:')
ax1.fill_between(t[:-73], T_air[:-73,2]-273.15, T_air[:-73,3]-273.15, color='red', alpha = 0.2)
#plt.plot(t,T_air[:,1],'b--')
plt.plot(t1,T_air[-73:,1]-273.15,'b--')
plt.scatter(td,dpT-273.15, marker='.', color='k')
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
ax1.set_xlabel('Hour', fontsize=8)
ax1.set_ylabel('Temperature ($\mathregular{^{o}}$C)', fontsize=8)
ax1.set_title('Temperature', fontsize=10)
ax1.axvline(x=0, color='k')
ax1.set_xlim(-120, 72)
ax3 = fig.add_subplot(1,2,2)
lbl1 = str(int(N)) + ' ACH'
lbl2 = ', ' + str(int(ndh)) + ' DH'
lbl3 = ', ' + str(int(lshift)) + ' hours'
plt.plot(t,100*RH_air[:,0],'r', label='BAU')
ax3.fill_between(t[:-73], 100*RH_air[:-73,2], 100*RH_air[:-73,3], color='red', alpha = 0.2)
#plt.plot(t,100*RH_air[:,1],'b--', label='Max N')
plt.plot(t1,100*RH_air[-73:,1],'b--', label= lbl1 + lbl2 + lbl3)
plt.scatter(td,dpRH, marker='.', color='k', label='Data')
ax3.set_title('Relative Humidity', fontsize=10)
plt.xticks(fontsize=8)
plt.yticks(fontsize=8)
ax3.set_xlabel('Hour', fontsize=8)
ax3.set_ylabel('Relative Humidity (%)', fontsize=8)
ax3.legend(loc='best', fontsize='small')
ax3.axvline(x=0, color='k')
ax3.set_xlim(-120, 72)
plt.subplots_adjust(wspace=0.5)
# Calculate statistics and produce pie charts. Note need too cold as well? Check
# setpoints with Mel
setTmax = 25 + 273.15
setTmin = 20 + 273.15
setRHmax = 0.85
setRHmin = 0.5
TBAUstat = T_air[-73:,0]
TSEstat = T_air[-73:,1]
RHBAUstat = RH_air[-73:,0]
RHSEstat = RH_air[-73:,1]
testTBAU = TBAUstat>setTmax
testTBAU_low = TBAUstat<setTmin
testTSE = TSEstat>setTmax
testTSE_low = TSEstat<setTmin
testRHBAU = RHBAUstat>setRHmax
testRHBAU_low = RHBAUstat<setRHmin
testRHSE = RHSEstat>setRHmax
testRHSE_low = RHSEstat<setRHmin
#y1 = ([np.sum(testTBAU), 72])
y1 = {'T<Tmin': np.sum(testTBAU_low), 'T OK': 72-np.sum(testTBAU)-np.sum(testTBAU_low), 'T>Tset': np.sum(testTBAU)}
names1 = [key for key,value in y1.items() if value!=0]
values1 = [value for value in y1.values() if value!=0]
#y2 = ([np.sum(testTSE), 72])
#y2 = {'T<Tset': 72-np.sum(testTSE), 'T>Tset': np.sum(testTSE)}
y2 = {'T<Tmin': np.sum(testTSE_low), 'T OK': 72-np.sum(testTSE)-np.sum(testTSE_low), 'T>Tset': np.sum(testTSE)}
names2 = [key for key,value in y2.items() if value!=0]
values2 = [value for value in y2.values() if value!=0]
#y3 = ([np.sum(testRHBAU), 72])
#y3 = {'RH<RHset': 72-np.sum(testRHBAU), 'RH>RHset': np.sum(testRHBAU)}
y3 = {'RH<RHmin': np.sum(testRHBAU_low), 'RH OK': 72-np.sum(testRHBAU)-np.sum(testRHBAU_low), 'RH>RHset': np.sum(testRHBAU)}
names3 = [key for key,value in y3.items()]
values3 = [value for value in y3.values()]
#y4 = ([np.sum(testRHSE), 72])
#y4 = {'RH<RHset': 72-np.sum(testRHSE), 'RH>RHset': np.sum(testRHSE)}
y4 = {'RH<RHmin': np.sum(testRHSE_low), 'RH OK': 72-np.sum(testRHSE)-np.sum(testRHSE_low), 'RH>RHset': np.sum(testRHSE)}
names4 = [key for key,value in y4.items()]
values4 = [value for value in y4.values()]
fig2 = plt.figure()
#Tlabels = ['T>Tset', 'T<Tset']
#RHlabels = ['RH>RHset', 'RH<RHset']
ax11 = fig2.add_subplot(2,2,1)
plt.pie(values1, colors = ['blue','green','red'], startangle = 90, labels = names1, textprops={'fontsize': 8})
ax11.set_title('Temperature - BAU', fontsize = 8)
ax12 = fig2.add_subplot(2,2,3)
plt.pie(values2, colors = ['blue','green','red'], startangle = 90, labels = names2, textprops={'fontsize': 8})
ax12.set_title('Temperature - Scenario', fontsize = 8)
ax31 = fig2.add_subplot(2,2,2)
plt.pie(values3, colors = ['blue','green','red'], startangle = 90, labels = names3, textprops={'fontsize': 8})
ax31.set_title('RH - BAU', fontsize = 8)
ax32 = fig2.add_subplot(2,2,4)
plt.pie(values4, colors = ['blue','green','red'], startangle = 90, labels = names4, textprops={'fontsize': 8})
ax32.set_title('RH - Scenario', fontsize = 8)
|
[
"numpy.quantile",
"numpy.sum",
"matplotlib.pyplot.plot",
"pandas.read_csv",
"matplotlib.pyplot.scatter",
"functions_scenario.derivatives",
"matplotlib.pyplot.yticks",
"numpy.zeros",
"numpy.genfromtxt",
"matplotlib.pyplot.figure",
"numpy.mean",
"numpy.linspace",
"matplotlib.pyplot.subplots_adjust",
"functions_scenario.sat_conc",
"matplotlib.pyplot.xticks",
"numpy.concatenate",
"matplotlib.pyplot.pie"
] |
[((544, 587), 'numpy.genfromtxt', 'np.genfromtxt', (['"""ACH_out.csv"""'], {'delimiter': '""","""'}), "('ACH_out.csv', delimiter=',')\n", (557, 587), True, 'import numpy as np\n'), ((597, 640), 'numpy.genfromtxt', 'np.genfromtxt', (['"""IAS_out.csv"""'], {'delimiter': '""","""'}), "('IAS_out.csv', delimiter=',')\n", (610, 640), True, 'import numpy as np\n'), ((807, 825), 'numpy.mean', 'np.mean', (['ACHcal', '(0)'], {}), '(ACHcal, 0)\n', (814, 825), True, 'import numpy as np\n'), ((833, 861), 'numpy.quantile', 'np.quantile', (['ACHcal', '(0.95)', '(0)'], {}), '(ACHcal, 0.95, 0)\n', (844, 861), True, 'import numpy as np\n'), ((868, 896), 'numpy.quantile', 'np.quantile', (['ACHcal', '(0.05)', '(0)'], {}), '(ACHcal, 0.05, 0)\n', (879, 896), True, 'import numpy as np\n'), ((943, 961), 'numpy.mean', 'np.mean', (['IAScal', '(0)'], {}), '(IAScal, 0)\n', (950, 961), True, 'import numpy as np\n'), ((969, 997), 'numpy.quantile', 'np.quantile', (['IAScal', '(0.95)', '(0)'], {}), '(IAScal, 0.95, 0)\n', (980, 997), True, 'import numpy as np\n'), ((1004, 1032), 'numpy.quantile', 'np.quantile', (['IAScal', '(0.05)', '(0)'], {}), '(IAScal, 0.05, 0)\n', (1015, 1032), True, 'import numpy as np\n'), ((1189, 1210), 'numpy.zeros', 'np.zeros', (['(ndp, 4, 4)'], {}), '((ndp, 4, 4))\n', (1197, 1210), True, 'import numpy as np\n'), ((1622, 1641), 'numpy.zeros', 'np.zeros', (['(8, 4, 4)'], {}), '((8, 4, 4))\n', (1630, 1641), True, 'import numpy as np\n'), ((2296, 2328), 'numpy.concatenate', 'np.concatenate', (['(test, ScenEval)'], {}), '((test, ScenEval))\n', (2310, 2328), True, 'import numpy as np\n'), ((2551, 2583), 'functions_scenario.derivatives', 'derivatives', (['h1', 'h2', 'params', 'ndp'], {}), '(h1, h2, params, ndp)\n', (2562, 2583), False, 'from functions_scenario import derivatives, sat_conc\n'), ((2796, 2841), 'numpy.linspace', 'np.linspace', (['p1', 'p2', '(ndp + 1)'], {'endpoint': '"""true"""'}), "(p1, p2, ndp + 1, endpoint='true')\n", (2807, 2841), True, 'import numpy as np\n'), ((2871, 2921), 'pandas.read_csv', 'pd.read_csv', (['"""TRHE2018.csv"""'], {'parse_dates': 'date_cols'}), "('TRHE2018.csv', parse_dates=date_cols)\n", (2882, 2921), True, 'import pandas as pd\n'), ((3022, 3068), 'numpy.linspace', 'np.linspace', (['(h1 - h2)', '(3 * 24)', '(1 + 240 + 3 * 24)'], {}), '(h1 - h2, 3 * 24, 1 + 240 + 3 * 24)\n', (3033, 3068), True, 'import numpy as np\n'), ((3062, 3096), 'numpy.linspace', 'np.linspace', (['(0)', '(3 * 24)', '(1 + 3 * 24)'], {}), '(0, 3 * 24, 1 + 3 * 24)\n', (3073, 3096), True, 'import numpy as np\n'), ((3094, 3121), 'numpy.linspace', 'np.linspace', (['(h1 - h2)', '(0)', '(21)'], {}), '(h1 - h2, 0, 21)\n', (3105, 3121), True, 'import numpy as np\n'), ((3201, 3213), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (3211, 3213), True, 'import matplotlib.pyplot as plt\n'), ((3244, 3282), 'matplotlib.pyplot.plot', 'plt.plot', (['t', '(T_air[:, 0] - 273.15)', '"""r"""'], {}), "(t, T_air[:, 0] - 273.15, 'r')\n", (3252, 3282), True, 'import matplotlib.pyplot as plt\n'), ((3486, 3530), 'matplotlib.pyplot.plot', 'plt.plot', (['t1', '(T_air[-73:, 1] - 273.15)', '"""b--"""'], {}), "(t1, T_air[-73:, 1] - 273.15, 'b--')\n", (3494, 3530), True, 'import matplotlib.pyplot as plt\n'), ((3526, 3578), 'matplotlib.pyplot.scatter', 'plt.scatter', (['td', '(dpT - 273.15)'], {'marker': '"""."""', 'color': '"""k"""'}), "(td, dpT - 273.15, marker='.', color='k')\n", (3537, 3578), True, 'import matplotlib.pyplot as plt\n'), ((3576, 3598), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(8)'}), '(fontsize=8)\n', (3586, 3598), True, 'import matplotlib.pyplot as plt\n'), ((3599, 3621), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(8)'}), '(fontsize=8)\n', (3609, 3621), True, 'import matplotlib.pyplot as plt\n'), ((3952, 4001), 'matplotlib.pyplot.plot', 'plt.plot', (['t', '(100 * RH_air[:, 0])', '"""r"""'], {'label': '"""BAU"""'}), "(t, 100 * RH_air[:, 0], 'r', label='BAU')\n", (3960, 4001), True, 'import matplotlib.pyplot as plt\n'), ((4140, 4208), 'matplotlib.pyplot.plot', 'plt.plot', (['t1', '(100 * RH_air[-73:, 1])', '"""b--"""'], {'label': '(lbl1 + lbl2 + lbl3)'}), "(t1, 100 * RH_air[-73:, 1], 'b--', label=lbl1 + lbl2 + lbl3)\n", (4148, 4208), True, 'import matplotlib.pyplot as plt\n'), ((4205, 4263), 'matplotlib.pyplot.scatter', 'plt.scatter', (['td', 'dpRH'], {'marker': '"""."""', 'color': '"""k"""', 'label': '"""Data"""'}), "(td, dpRH, marker='.', color='k', label='Data')\n", (4216, 4263), True, 'import matplotlib.pyplot as plt\n'), ((4311, 4333), 'matplotlib.pyplot.xticks', 'plt.xticks', ([], {'fontsize': '(8)'}), '(fontsize=8)\n', (4321, 4333), True, 'import matplotlib.pyplot as plt\n'), ((4334, 4356), 'matplotlib.pyplot.yticks', 'plt.yticks', ([], {'fontsize': '(8)'}), '(fontsize=8)\n', (4344, 4356), True, 'import matplotlib.pyplot as plt\n'), ((4538, 4569), 'matplotlib.pyplot.subplots_adjust', 'plt.subplots_adjust', ([], {'wspace': '(0.5)'}), '(wspace=0.5)\n', (4557, 4569), True, 'import matplotlib.pyplot as plt\n'), ((6307, 6319), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (6317, 6319), True, 'import matplotlib.pyplot as plt\n'), ((6423, 6534), 'matplotlib.pyplot.pie', 'plt.pie', (['values1'], {'colors': "['blue', 'green', 'red']", 'startangle': '(90)', 'labels': 'names1', 'textprops': "{'fontsize': 8}"}), "(values1, colors=['blue', 'green', 'red'], startangle=90, labels=\n names1, textprops={'fontsize': 8})\n", (6430, 6534), True, 'import matplotlib.pyplot as plt\n'), ((6624, 6735), 'matplotlib.pyplot.pie', 'plt.pie', (['values2'], {'colors': "['blue', 'green', 'red']", 'startangle': '(90)', 'labels': 'names2', 'textprops': "{'fontsize': 8}"}), "(values2, colors=['blue', 'green', 'red'], startangle=90, labels=\n names2, textprops={'fontsize': 8})\n", (6631, 6735), True, 'import matplotlib.pyplot as plt\n'), ((6824, 6935), 'matplotlib.pyplot.pie', 'plt.pie', (['values3'], {'colors': "['blue', 'green', 'red']", 'startangle': '(90)', 'labels': 'names3', 'textprops': "{'fontsize': 8}"}), "(values3, colors=['blue', 'green', 'red'], startangle=90, labels=\n names3, textprops={'fontsize': 8})\n", (6831, 6935), True, 'import matplotlib.pyplot as plt\n'), ((7017, 7128), 'matplotlib.pyplot.pie', 'plt.pie', (['values4'], {'colors': "['blue', 'green', 'red']", 'startangle': '(90)', 'labels': 'names4', 'textprops': "{'fontsize': 8}"}), "(values4, colors=['blue', 'green', 'red'], startangle=90, labels=\n names4, textprops={'fontsize': 8})\n", (7024, 7128), True, 'import matplotlib.pyplot as plt\n'), ((2654, 2669), 'functions_scenario.sat_conc', 'sat_conc', (['T_air'], {}), '(T_air)\n', (2662, 2669), False, 'from functions_scenario import derivatives, sat_conc\n'), ((3180, 3193), 'functions_scenario.sat_conc', 'sat_conc', (['dpT'], {}), '(dpT)\n', (3188, 3193), False, 'from functions_scenario import derivatives, sat_conc\n'), ((5147, 5167), 'numpy.sum', 'np.sum', (['testTBAU_low'], {}), '(testTBAU_low)\n', (5153, 5167), True, 'import numpy as np\n'), ((5229, 5245), 'numpy.sum', 'np.sum', (['testTBAU'], {}), '(testTBAU)\n', (5235, 5245), True, 'import numpy as np\n'), ((5468, 5487), 'numpy.sum', 'np.sum', (['testTSE_low'], {}), '(testTSE_low)\n', (5474, 5487), True, 'import numpy as np\n'), ((5547, 5562), 'numpy.sum', 'np.sum', (['testTSE'], {}), '(testTSE)\n', (5553, 5562), True, 'import numpy as np\n'), ((5797, 5818), 'numpy.sum', 'np.sum', (['testRHBAU_low'], {}), '(testRHBAU_low)\n', (5803, 5818), True, 'import numpy as np\n'), ((5885, 5902), 'numpy.sum', 'np.sum', (['testRHBAU'], {}), '(testRHBAU)\n', (5891, 5902), True, 'import numpy as np\n'), ((6110, 6130), 'numpy.sum', 'np.sum', (['testRHSE_low'], {}), '(testRHSE_low)\n', (6116, 6130), True, 'import numpy as np\n'), ((6195, 6211), 'numpy.sum', 'np.sum', (['testRHSE'], {}), '(testRHSE)\n', (6201, 6211), True, 'import numpy as np\n'), ((5197, 5217), 'numpy.sum', 'np.sum', (['testTBAU_low'], {}), '(testTBAU_low)\n', (5203, 5217), True, 'import numpy as np\n'), ((5516, 5535), 'numpy.sum', 'np.sum', (['testTSE_low'], {}), '(testTSE_low)\n', (5522, 5535), True, 'import numpy as np\n'), ((5850, 5871), 'numpy.sum', 'np.sum', (['testRHBAU_low'], {}), '(testRHBAU_low)\n', (5856, 5871), True, 'import numpy as np\n'), ((6161, 6181), 'numpy.sum', 'np.sum', (['testRHSE_low'], {}), '(testRHSE_low)\n', (6167, 6181), True, 'import numpy as np\n'), ((5180, 5196), 'numpy.sum', 'np.sum', (['testTBAU'], {}), '(testTBAU)\n', (5186, 5196), True, 'import numpy as np\n'), ((5500, 5515), 'numpy.sum', 'np.sum', (['testTSE'], {}), '(testTSE)\n', (5506, 5515), True, 'import numpy as np\n'), ((5832, 5849), 'numpy.sum', 'np.sum', (['testRHBAU'], {}), '(testRHBAU)\n', (5838, 5849), True, 'import numpy as np\n'), ((6144, 6160), 'numpy.sum', 'np.sum', (['testRHSE'], {}), '(testRHSE)\n', (6150, 6160), True, 'import numpy as np\n')]
|
"""Print summary statistics of DRIAMS spectra.
The purpose of this script is to print some summary statistics about DRIAMS
data sets, stratified by site. This is just a debug script with no usage in
real-world analysis scenarios.
"""
import argparse
import dotenv
import os
import numpy as np
from maldi_learn.driams import DRIAMSDatasetExplorer
from maldi_learn.driams import load_driams_dataset
from tqdm import tqdm
dotenv.load_dotenv()
DRIAMS_ROOT = os.getenv('DRIAMS_ROOT')
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
'-s', '--site',
default='DRIAMS-A',
type=str,
help='Site to pre-process')
parser.add_argument(
'-y', '--years',
default=['2015', '2016', '2017', '2018'],
type=str,
nargs='+',
help='Years to pre-process'
)
args = parser.parse_args()
# Get all available antibiotics for the selected site. We will
# pre-process *all* the spectra.
explorer = DRIAMSDatasetExplorer(DRIAMS_ROOT)
antibiotics = explorer.available_antibiotics(args.site)
# Process each year separately, because that simplifies assigning
# the output files.
for year in tqdm(args.years, desc='Year'):
driams_dataset = load_driams_dataset(
explorer.root,
args.site,
year,
'*', # Load all species; we do *not* want to filter anything
antibiotics[year],
handle_missing_resistance_measurements='keep', # Keep all
spectra_type='binned_6000',
)
codes = driams_dataset.y['code'].values
for spectrum, code in tqdm(zip(driams_dataset.X, codes),
total=len(codes),
desc='Spectrum'):
# Use intensity values only
if len(spectrum.shape) == 2:
spectrum = spectrum[:, 1]
min_value, max_value = np.min(spectrum), np.max(spectrum)
tic = np.sum(spectrum)
print(f'*** {code} ***')
print(f'Min: {min_value:.08f}')
print(f'Max: {max_value:.08f}')
print(f'TIC: {tic:.2f}')
|
[
"tqdm.tqdm",
"numpy.sum",
"argparse.ArgumentParser",
"maldi_learn.driams.DRIAMSDatasetExplorer",
"maldi_learn.driams.load_driams_dataset",
"dotenv.load_dotenv",
"numpy.min",
"numpy.max",
"os.getenv"
] |
[((425, 445), 'dotenv.load_dotenv', 'dotenv.load_dotenv', ([], {}), '()\n', (443, 445), False, 'import dotenv\n'), ((460, 484), 'os.getenv', 'os.getenv', (['"""DRIAMS_ROOT"""'], {}), "('DRIAMS_ROOT')\n", (469, 484), False, 'import os\n'), ((528, 553), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (551, 553), False, 'import argparse\n'), ((1018, 1052), 'maldi_learn.driams.DRIAMSDatasetExplorer', 'DRIAMSDatasetExplorer', (['DRIAMS_ROOT'], {}), '(DRIAMS_ROOT)\n', (1039, 1052), False, 'from maldi_learn.driams import DRIAMSDatasetExplorer\n'), ((1224, 1253), 'tqdm.tqdm', 'tqdm', (['args.years'], {'desc': '"""Year"""'}), "(args.years, desc='Year')\n", (1228, 1253), False, 'from tqdm import tqdm\n'), ((1280, 1434), 'maldi_learn.driams.load_driams_dataset', 'load_driams_dataset', (['explorer.root', 'args.site', 'year', '"""*"""', 'antibiotics[year]'], {'handle_missing_resistance_measurements': '"""keep"""', 'spectra_type': '"""binned_6000"""'}), "(explorer.root, args.site, year, '*', antibiotics[year],\n handle_missing_resistance_measurements='keep', spectra_type='binned_6000')\n", (1299, 1434), False, 'from maldi_learn.driams import load_driams_dataset\n'), ((2057, 2073), 'numpy.sum', 'np.sum', (['spectrum'], {}), '(spectrum)\n', (2063, 2073), True, 'import numpy as np\n'), ((2004, 2020), 'numpy.min', 'np.min', (['spectrum'], {}), '(spectrum)\n', (2010, 2020), True, 'import numpy as np\n'), ((2022, 2038), 'numpy.max', 'np.max', (['spectrum'], {}), '(spectrum)\n', (2028, 2038), True, 'import numpy as np\n')]
|
from functools import partial
import numpy as np
from keras.preprocessing.image import img_to_array
from keras.preprocessing.image import load_img
from toolbox.image import bicubic_rescale
from toolbox.image import modcrop
from toolbox.paths import data_dir
def load_set(name, lr_sub_size=11, lr_sub_stride=5, scale=3):
hr_sub_size = lr_sub_size * scale
hr_sub_stride = lr_sub_stride * scale
lr_gen_sub = partial(generate_sub_images, size=lr_sub_size,
stride=lr_sub_stride)
hr_gen_sub = partial(generate_sub_images, size=hr_sub_size,
stride=hr_sub_stride)
lr_sub_arrays = []
hr_sub_arrays = []
for path in (data_dir / name).glob('*'):
lr_image, hr_image = load_image_pair(str(path), scale=scale)
lr_sub_arrays += [img_to_array(img) for img in lr_gen_sub(lr_image)]
hr_sub_arrays += [img_to_array(img) for img in hr_gen_sub(hr_image)]
x = np.stack(lr_sub_arrays)
y = np.stack(hr_sub_arrays)
return x, y
def load_image_pair(path, scale=3):
image = load_img(path)
image = image.convert('YCbCr')
hr_image = modcrop(image, scale)
lr_image = bicubic_rescale(hr_image, 1 / scale)
return lr_image, hr_image
def generate_sub_images(image, size, stride):
for i in range(0, image.size[0] - size + 1, stride):
for j in range(0, image.size[1] - size + 1, stride):
yield image.crop([i, j, i + size, j + size])
|
[
"numpy.stack",
"functools.partial",
"toolbox.image.bicubic_rescale",
"keras.preprocessing.image.img_to_array",
"keras.preprocessing.image.load_img",
"toolbox.image.modcrop"
] |
[((421, 489), 'functools.partial', 'partial', (['generate_sub_images'], {'size': 'lr_sub_size', 'stride': 'lr_sub_stride'}), '(generate_sub_images, size=lr_sub_size, stride=lr_sub_stride)\n', (428, 489), False, 'from functools import partial\n'), ((532, 600), 'functools.partial', 'partial', (['generate_sub_images'], {'size': 'hr_sub_size', 'stride': 'hr_sub_stride'}), '(generate_sub_images, size=hr_sub_size, stride=hr_sub_stride)\n', (539, 600), False, 'from functools import partial\n'), ((949, 972), 'numpy.stack', 'np.stack', (['lr_sub_arrays'], {}), '(lr_sub_arrays)\n', (957, 972), True, 'import numpy as np\n'), ((981, 1004), 'numpy.stack', 'np.stack', (['hr_sub_arrays'], {}), '(hr_sub_arrays)\n', (989, 1004), True, 'import numpy as np\n'), ((1071, 1085), 'keras.preprocessing.image.load_img', 'load_img', (['path'], {}), '(path)\n', (1079, 1085), False, 'from keras.preprocessing.image import load_img\n'), ((1136, 1157), 'toolbox.image.modcrop', 'modcrop', (['image', 'scale'], {}), '(image, scale)\n', (1143, 1157), False, 'from toolbox.image import modcrop\n'), ((1173, 1209), 'toolbox.image.bicubic_rescale', 'bicubic_rescale', (['hr_image', '(1 / scale)'], {}), '(hr_image, 1 / scale)\n', (1188, 1209), False, 'from toolbox.image import bicubic_rescale\n'), ((813, 830), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['img'], {}), '(img)\n', (825, 830), False, 'from keras.preprocessing.image import img_to_array\n'), ((890, 907), 'keras.preprocessing.image.img_to_array', 'img_to_array', (['img'], {}), '(img)\n', (902, 907), False, 'from keras.preprocessing.image import img_to_array\n')]
|
from datetime import datetime
import numpy as NP
import scipy.optimize
import sympy as SYM
import pylab as PL
def chapman(z, Nm, Hm, H_O, exp=NP.exp):
"""
Return Chapman function electron density at height *z*, maximum
electron density at the F-peak *Nm*, height at the maximum *Hm*,
and the scale height of atomic oxygen *H_O*. The exponential
function can be overridden with *exp*.
"""
return Nm * exp((1 - ((z - Hm) / H_O) - exp(-(z - Hm) / H_O)) / 2)
def chapman_sym(z, Nm, Hm, H_O):
"""
Return symbolic (i.e., :module:`sympy`) Chapman electron density
profile function.
"""
return chapman(z, Nm, Hm, H_O, exp=SYM.exp)
def chapman_vec(z_vec, Nm_vec, Hm_vec, H_O_vec):
"""
Vectorized implementation of the Chapman function evaluation
routine :func:`chapman`. The input arguments must be sequences
with the same length and the output is an :class:`NP.ndarray` with
that length.
"""
try:
chapman_vec._chapman_sym_f
except AttributeError:
sym_vars = SYM.symbols('z Nm Hm H_O')
chapman_vec._chapman_sym_f = SYM.lambdify(sym_vars,
chapman_sym(*sym_vars),
modules='numexpr')
return chapman_vec._chapman_sym_f(z_vec,
Nm_vec,
Hm_vec,
H_O_vec)
def chapman_fit(alt,
ne,
x0=[1e6, 300, 50],
bounds=[(1, None),
(150, 500),
(30, 80)],
verbose=False,
**kwds):
"""
"""
# optimization setup
z, Nm, Hm, H_O = SYM.symbols('z Nm Hm H_O')
chapman = chapman_sym(z, Nm, Hm, H_O)
dNm = SYM.diff(chapman, Nm)
dHm = SYM.diff(chapman, Hm)
dH_O = SYM.diff(chapman, H_O)
chapman_f = SYM.lambdify((z, Nm, Hm, H_O),
chapman,
modules='numexpr')
dNm_f = SYM.lambdify((z, Nm, Hm, H_O),
dNm,
modules='numexpr')
dHm_f = SYM.lambdify((z, Nm, Hm, H_O),
dHm,
modules='numexpr')
dH_O_f = SYM.lambdify((z, Nm, Hm, H_O),
dH_O,
modules='numexpr')
# define cost function
y = NP.asarray(ne)
def J(x):
Nm, Hm, H_O = x
if verbose:
print('-' * 80)
print(x)
y_hat = NP.array([chapman_f(z, Nm, Hm, H_O) for z in alt])
diff = y - y_hat
J1 = NP.array([dNm_f(z, Nm, Hm, H_O) for z in alt])
J2 = NP.array([dHm_f(z, Nm, Hm, H_O) for z in alt])
J3 = NP.array([dH_O_f(z, Nm, Hm, H_O) for z in alt])
return (NP.dot(diff, diff),
NP.array([-2 * NP.sum(diff * J1),
-2 * NP.sum(diff * J2),
-2 * NP.sum(diff * J3)]))
# minimize cost function
x_star, f, d = scipy.optimize.fmin_l_bfgs_b(J,
x0,
bounds=bounds,
**kwds)
assert d['warnflag'] == 0
return x_star
if __name__ == '__main__':
from pyglow.pyglow import Point
N = 200
alt = NP.linspace(100, 1500, N)
dt = datetime(2000, 1, 1)
lat = 0
lon = 0
iri_ne = []
for alt_i in alt:
point = Point(dt, lat, lon, alt_i)
point.run_iri()
iri_ne.append(point.ne)
Nm_star, Hm_star, H_O_star = chapman_fit(alt, iri_ne, verbose=True)
chapman_ne = [chapman(z, Nm_star, Hm_star, H_O_star) for z in alt]
fig = PL.figure(figsize=(6,10))
PL.plot(iri_ne,
alt,
color='b',
label='IRI')
PL.plot(chapman_ne,
alt,
color='g',
label='Chapman fit')
PL.legend()
PL.xlabel('Electron density [cm$^{-3}$]')
PL.ylabel('Height [km]')
PL.ticklabel_format(style='sci', axis='x', scilimits=(0,0))
PL.axis('tight')
PL.show()
|
[
"sympy.symbols",
"pylab.show",
"numpy.sum",
"pylab.axis",
"numpy.asarray",
"sympy.diff",
"pylab.ylabel",
"sympy.lambdify",
"datetime.datetime",
"pylab.figure",
"numpy.linspace",
"pylab.xlabel",
"numpy.dot",
"pyglow.pyglow.Point",
"pylab.ticklabel_format",
"pylab.legend",
"pylab.plot"
] |
[((1769, 1795), 'sympy.symbols', 'SYM.symbols', (['"""z Nm Hm H_O"""'], {}), "('z Nm Hm H_O')\n", (1780, 1795), True, 'import sympy as SYM\n'), ((1848, 1869), 'sympy.diff', 'SYM.diff', (['chapman', 'Nm'], {}), '(chapman, Nm)\n', (1856, 1869), True, 'import sympy as SYM\n'), ((1880, 1901), 'sympy.diff', 'SYM.diff', (['chapman', 'Hm'], {}), '(chapman, Hm)\n', (1888, 1901), True, 'import sympy as SYM\n'), ((1913, 1935), 'sympy.diff', 'SYM.diff', (['chapman', 'H_O'], {}), '(chapman, H_O)\n', (1921, 1935), True, 'import sympy as SYM\n'), ((1952, 2010), 'sympy.lambdify', 'SYM.lambdify', (['(z, Nm, Hm, H_O)', 'chapman'], {'modules': '"""numexpr"""'}), "((z, Nm, Hm, H_O), chapman, modules='numexpr')\n", (1964, 2010), True, 'import sympy as SYM\n'), ((2081, 2135), 'sympy.lambdify', 'SYM.lambdify', (['(z, Nm, Hm, H_O)', 'dNm'], {'modules': '"""numexpr"""'}), "((z, Nm, Hm, H_O), dNm, modules='numexpr')\n", (2093, 2135), True, 'import sympy as SYM\n'), ((2198, 2252), 'sympy.lambdify', 'SYM.lambdify', (['(z, Nm, Hm, H_O)', 'dHm'], {'modules': '"""numexpr"""'}), "((z, Nm, Hm, H_O), dHm, modules='numexpr')\n", (2210, 2252), True, 'import sympy as SYM\n'), ((2316, 2371), 'sympy.lambdify', 'SYM.lambdify', (['(z, Nm, Hm, H_O)', 'dH_O'], {'modules': '"""numexpr"""'}), "((z, Nm, Hm, H_O), dH_O, modules='numexpr')\n", (2328, 2371), True, 'import sympy as SYM\n'), ((2459, 2473), 'numpy.asarray', 'NP.asarray', (['ne'], {}), '(ne)\n', (2469, 2473), True, 'import numpy as NP\n'), ((3429, 3454), 'numpy.linspace', 'NP.linspace', (['(100)', '(1500)', 'N'], {}), '(100, 1500, N)\n', (3440, 3454), True, 'import numpy as NP\n'), ((3465, 3485), 'datetime.datetime', 'datetime', (['(2000)', '(1)', '(1)'], {}), '(2000, 1, 1)\n', (3473, 3485), False, 'from datetime import datetime\n'), ((3804, 3830), 'pylab.figure', 'PL.figure', ([], {'figsize': '(6, 10)'}), '(figsize=(6, 10))\n', (3813, 3830), True, 'import pylab as PL\n'), ((3834, 3878), 'pylab.plot', 'PL.plot', (['iri_ne', 'alt'], {'color': '"""b"""', 'label': '"""IRI"""'}), "(iri_ne, alt, color='b', label='IRI')\n", (3841, 3878), True, 'import pylab as PL\n'), ((3919, 3975), 'pylab.plot', 'PL.plot', (['chapman_ne', 'alt'], {'color': '"""g"""', 'label': '"""Chapman fit"""'}), "(chapman_ne, alt, color='g', label='Chapman fit')\n", (3926, 3975), True, 'import pylab as PL\n'), ((4016, 4027), 'pylab.legend', 'PL.legend', ([], {}), '()\n', (4025, 4027), True, 'import pylab as PL\n'), ((4032, 4073), 'pylab.xlabel', 'PL.xlabel', (['"""Electron density [cm$^{-3}$]"""'], {}), "('Electron density [cm$^{-3}$]')\n", (4041, 4073), True, 'import pylab as PL\n'), ((4078, 4102), 'pylab.ylabel', 'PL.ylabel', (['"""Height [km]"""'], {}), "('Height [km]')\n", (4087, 4102), True, 'import pylab as PL\n'), ((4107, 4167), 'pylab.ticklabel_format', 'PL.ticklabel_format', ([], {'style': '"""sci"""', 'axis': '"""x"""', 'scilimits': '(0, 0)'}), "(style='sci', axis='x', scilimits=(0, 0))\n", (4126, 4167), True, 'import pylab as PL\n'), ((4171, 4187), 'pylab.axis', 'PL.axis', (['"""tight"""'], {}), "('tight')\n", (4178, 4187), True, 'import pylab as PL\n'), ((4193, 4202), 'pylab.show', 'PL.show', ([], {}), '()\n', (4200, 4202), True, 'import pylab as PL\n'), ((3565, 3591), 'pyglow.pyglow.Point', 'Point', (['dt', 'lat', 'lon', 'alt_i'], {}), '(dt, lat, lon, alt_i)\n', (3570, 3591), False, 'from pyglow.pyglow import Point\n'), ((1053, 1079), 'sympy.symbols', 'SYM.symbols', (['"""z Nm Hm H_O"""'], {}), "('z Nm Hm H_O')\n", (1064, 1079), True, 'import sympy as SYM\n'), ((2870, 2888), 'numpy.dot', 'NP.dot', (['diff', 'diff'], {}), '(diff, diff)\n', (2876, 2888), True, 'import numpy as NP\n'), ((2921, 2938), 'numpy.sum', 'NP.sum', (['(diff * J1)'], {}), '(diff * J1)\n', (2927, 2938), True, 'import numpy as NP\n'), ((2971, 2988), 'numpy.sum', 'NP.sum', (['(diff * J2)'], {}), '(diff * J2)\n', (2977, 2988), True, 'import numpy as NP\n'), ((3021, 3038), 'numpy.sum', 'NP.sum', (['(diff * J3)'], {}), '(diff * J3)\n', (3027, 3038), True, 'import numpy as NP\n')]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.