repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
alkscr/talking-head-anime-2-demo
|
[
"8de34d3e9a681519b8fe04645f54643583ace2ca"
] |
[
"tha2/app/manual_poser.py"
] |
[
"import logging\r\nimport os\r\nimport sys\r\nfrom typing import List\r\n\r\nsys.path.append(os.getcwd())\r\n\r\nimport numpy\r\nimport torch\r\nimport wx\r\nimport PIL.Image\r\n\r\nfrom tha2.poser.poser import Poser, PoseParameterCategory, PoseParameterGroup\r\nfrom tha2.util import extract_PIL_image_from_filelike, resize_PIL_image, extract_pytorch_image_from_PIL_image, convert_output_image_from_torch_to_numpy\r\n\r\n\r\nclass MorphCategoryControlPanel(wx.Panel):\r\n def __init__(self,\r\n parent,\r\n title: str,\r\n pose_param_category: PoseParameterCategory,\r\n param_groups: List[PoseParameterGroup]):\r\n super().__init__(parent, style=wx.SIMPLE_BORDER)\r\n self.pose_param_category = pose_param_category\r\n self.sizer = wx.BoxSizer(wx.VERTICAL)\r\n self.SetSizer(self.sizer)\r\n self.SetAutoLayout(1)\r\n\r\n title_text = wx.StaticText(self, label=title, style=wx.ALIGN_CENTER)\r\n self.sizer.Add(title_text, 0, wx.EXPAND)\r\n\r\n self.param_groups = [group for group in param_groups if group.get_category() == pose_param_category]\r\n self.choice = wx.Choice(self, choices=[group.get_group_name() for group in self.param_groups])\r\n if len(self.param_groups) > 0:\r\n self.choice.SetSelection(0)\r\n self.choice.Bind(wx.EVT_CHOICE, self.on_choice_updated)\r\n self.sizer.Add(self.choice, 0, wx.EXPAND)\r\n\r\n self.left_slider = wx.Slider(self, minValue=-1000, maxValue=1000, value=-1000, style=wx.HORIZONTAL)\r\n self.sizer.Add(self.left_slider, 0, wx.EXPAND)\r\n\r\n self.right_slider = wx.Slider(self, minValue=-1000, maxValue=1000, value=-1000, style=wx.HORIZONTAL)\r\n self.sizer.Add(self.right_slider, 0, wx.EXPAND)\r\n\r\n self.checkbox = wx.CheckBox(self, label=\"Show\")\r\n self.checkbox.SetValue(True)\r\n self.sizer.Add(self.checkbox, 0, wx.SHAPED | wx.ALIGN_CENTER)\r\n\r\n self.update_ui()\r\n\r\n self.sizer.Fit(self)\r\n\r\n def update_ui(self):\r\n param_group = self.param_groups[self.choice.GetSelection()]\r\n if param_group.is_discrete():\r\n self.left_slider.Enable(False)\r\n self.right_slider.Enable(False)\r\n self.checkbox.Enable(True)\r\n elif param_group.get_arity() == 1:\r\n self.left_slider.Enable(True)\r\n self.right_slider.Enable(False)\r\n self.checkbox.Enable(False)\r\n else:\r\n self.left_slider.Enable(True)\r\n self.right_slider.Enable(True)\r\n self.checkbox.Enable(False)\r\n\r\n def on_choice_updated(self, event: wx.Event):\r\n param_group = self.param_groups[self.choice.GetSelection()]\r\n if param_group.is_discrete():\r\n self.checkbox.SetValue(True)\r\n self.update_ui()\r\n\r\n def set_param_value(self, pose: List[float]):\r\n if len(self.param_groups) == 0:\r\n return\r\n selected_morph_index = self.choice.GetSelection()\r\n param_group = self.param_groups[selected_morph_index]\r\n param_index = param_group.get_parameter_index()\r\n if param_group.is_discrete():\r\n if self.checkbox.GetValue():\r\n for i in range(param_group.get_arity()):\r\n pose[param_index + i] = 1.0\r\n else:\r\n param_range = param_group.get_range()\r\n alpha = (self.left_slider.GetValue() + 1000) / 2000.0\r\n pose[param_index] = param_range[0] + (param_range[1] - param_range[0]) * alpha\r\n if param_group.get_arity() == 2:\r\n alpha = (self.right_slider.GetValue() + 1000) / 2000.0\r\n pose[param_index + 1] = param_range[0] + (param_range[1] - param_range[0]) * alpha\r\n\r\n\r\nclass RotationControlPanel(wx.Panel):\r\n def __init__(self, parent,\r\n pose_param_category: PoseParameterCategory,\r\n param_groups: List[PoseParameterGroup]):\r\n super().__init__(parent, style=wx.SIMPLE_BORDER)\r\n self.sizer = wx.BoxSizer(wx.VERTICAL)\r\n self.SetSizer(self.sizer)\r\n self.SetAutoLayout(1)\r\n\r\n self.param_groups = [group for group in param_groups if group.get_category() == pose_param_category]\r\n for param_group in self.param_groups:\r\n assert not param_group.is_discrete()\r\n assert param_group.get_arity() == 1\r\n\r\n self.sliders = []\r\n for param_group in self.param_groups:\r\n static_text = wx.StaticText(self, label=\"--- %s ---\" % param_group.get_group_name(), style=wx.ALIGN_CENTER)\r\n self.sizer.Add(static_text, 0, wx.EXPAND)\r\n slider = wx.Slider(self, minValue=-1000, maxValue=1000, value=0, style=wx.HORIZONTAL)\r\n self.sizer.Add(slider, 0, wx.EXPAND)\r\n self.sliders.append(slider)\r\n\r\n self.sizer.Fit(self)\r\n\r\n def set_param_value(self, pose: List[float]):\r\n if len(self.param_groups) == 0:\r\n return\r\n for param_group_index in range(len(self.param_groups)):\r\n param_group = self.param_groups[param_group_index]\r\n slider = self.sliders[param_group_index]\r\n param_range = param_group.get_range()\r\n param_index = param_group.get_parameter_index()\r\n alpha = (slider.GetValue() + 1000) / 2000.0\r\n pose[param_index] = param_range[0] + (param_range[1] - param_range[0]) * alpha\r\n\r\n\r\nclass MainFrame(wx.Frame):\r\n def __init__(self, poser: Poser, device: torch.device):\r\n super().__init__(None, wx.ID_ANY, \"Poser\")\r\n self.poser = poser\r\n self.device = device\r\n\r\n self.wx_source_image = None\r\n self.torch_source_image = None\r\n self.source_image_string = \"Nothing yet!\"\r\n\r\n self.main_sizer = wx.BoxSizer(wx.HORIZONTAL)\r\n self.SetSizer(self.main_sizer)\r\n self.SetAutoLayout(1)\r\n self.init_left_panel()\r\n self.init_control_panel()\r\n self.init_right_panel()\r\n self.main_sizer.Fit(self)\r\n\r\n self.timer = wx.Timer(self, wx.ID_ANY)\r\n self.Bind(wx.EVT_TIMER, self.update_result_image_panel, self.timer)\r\n\r\n save_image_id = wx.NewIdRef()\r\n self.Bind(wx.EVT_MENU, self.on_save_image, id=save_image_id)\r\n accelerator_table = wx.AcceleratorTable([\r\n (wx.ACCEL_CTRL, ord('S'), save_image_id)\r\n ])\r\n self.SetAcceleratorTable(accelerator_table)\r\n\r\n self.last_pose = None\r\n self.last_output_index = self.output_index_choice.GetSelection()\r\n self.last_output_numpy_image = None\r\n\r\n def init_left_panel(self):\r\n self.control_panel = wx.Panel(self, style=wx.SIMPLE_BORDER, size=(256, -1))\r\n self.left_panel = wx.Panel(self, style=wx.SIMPLE_BORDER)\r\n left_panel_sizer = wx.BoxSizer(wx.VERTICAL)\r\n self.left_panel.SetSizer(left_panel_sizer)\r\n self.left_panel.SetAutoLayout(1)\r\n\r\n self.source_image_panel = wx.Panel(self.left_panel, size=(256, 256), style=wx.SIMPLE_BORDER)\r\n self.source_image_panel.Bind(wx.EVT_PAINT, self.paint_source_image_panel)\r\n left_panel_sizer.Add(self.source_image_panel, 0, wx.FIXED_MINSIZE)\r\n\r\n self.load_image_button = wx.Button(self.left_panel, wx.ID_ANY, \"\\nLoad Image\\n\\n\")\r\n left_panel_sizer.Add(self.load_image_button, 1, wx.EXPAND)\r\n self.load_image_button.Bind(wx.EVT_BUTTON, self.load_image)\r\n\r\n left_panel_sizer.Fit(self.left_panel)\r\n self.main_sizer.Add(self.left_panel, 0, wx.FIXED_MINSIZE)\r\n\r\n def init_control_panel(self):\r\n self.control_panel_sizer = wx.BoxSizer(wx.VERTICAL)\r\n self.control_panel.SetSizer(self.control_panel_sizer)\r\n\r\n morph_categories = [\r\n PoseParameterCategory.EYEBROW,\r\n PoseParameterCategory.EYE,\r\n PoseParameterCategory.MOUTH,\r\n PoseParameterCategory.IRIS_MORPH\r\n ]\r\n morph_category_titles = {\r\n PoseParameterCategory.EYEBROW: \"--- Eyebrow ---\",\r\n PoseParameterCategory.EYE: \"--- Eye ---\",\r\n PoseParameterCategory.MOUTH: \"--- Mouth ---\",\r\n PoseParameterCategory.IRIS_MORPH: \"--- Iris morphs ---\",\r\n }\r\n self.morph_control_panels = {}\r\n for category in morph_categories:\r\n param_groups = self.poser.get_pose_parameter_groups()\r\n filtered_param_groups = [group for group in param_groups if group.get_category() == category]\r\n if len(filtered_param_groups) == 0:\r\n continue\r\n control_panel = MorphCategoryControlPanel(\r\n self.control_panel,\r\n morph_category_titles[category],\r\n category,\r\n self.poser.get_pose_parameter_groups())\r\n self.morph_control_panels[category] = control_panel\r\n self.control_panel_sizer.Add(control_panel, 0, wx.EXPAND)\r\n\r\n self.rotation_control_panels = {}\r\n rotation_categories = [\r\n PoseParameterCategory.IRIS_ROTATION,\r\n PoseParameterCategory.FACE_ROTATION\r\n ]\r\n for category in rotation_categories:\r\n param_groups = self.poser.get_pose_parameter_groups()\r\n filtered_param_groups = [group for group in param_groups if group.get_category() == category]\r\n if len(filtered_param_groups) == 0:\r\n continue\r\n control_panel = RotationControlPanel(\r\n self.control_panel,\r\n category,\r\n self.poser.get_pose_parameter_groups())\r\n self.rotation_control_panels[category] = control_panel\r\n self.control_panel_sizer.Add(control_panel, 0, wx.EXPAND)\r\n\r\n self.control_panel_sizer.Fit(self.control_panel)\r\n self.main_sizer.Add(self.control_panel, 1, wx.EXPAND)\r\n\r\n def init_right_panel(self):\r\n self.right_panel = wx.Panel(self, style=wx.SIMPLE_BORDER)\r\n right_panel_sizer = wx.BoxSizer(wx.VERTICAL)\r\n self.right_panel.SetSizer(right_panel_sizer)\r\n self.right_panel.SetAutoLayout(1)\r\n\r\n self.result_image_panel = wx.Panel(self.right_panel, size=(256, 256), style=wx.SIMPLE_BORDER)\r\n self.result_image_panel.Bind(wx.EVT_PAINT, self.paint_result_image_panel)\r\n self.output_index_choice = wx.Choice(\r\n self.right_panel,\r\n choices=[str(i) for i in range(self.poser.get_output_length())])\r\n self.output_index_choice.SetSelection(0)\r\n right_panel_sizer.Add(self.result_image_panel, 0, wx.FIXED_MINSIZE)\r\n right_panel_sizer.Add(self.output_index_choice, 0, wx.EXPAND)\r\n\r\n self.save_image_button = wx.Button(self.right_panel, wx.ID_ANY, \"\\nSave Image\\n\\n\")\r\n right_panel_sizer.Add(self.save_image_button, 1, wx.EXPAND)\r\n self.save_image_button.Bind(wx.EVT_BUTTON, self.on_save_image)\r\n\r\n right_panel_sizer.Fit(self.right_panel)\r\n self.main_sizer.Add(self.right_panel, 0, wx.FIXED_MINSIZE)\r\n\r\n def create_param_category_choice(self, param_category: PoseParameterCategory):\r\n params = []\r\n for param_group in self.poser.get_pose_parameter_groups():\r\n if param_group.get_category() == param_category:\r\n params.append(param_group.get_group_name())\r\n choice = wx.Choice(self.control_panel, choices=params)\r\n if len(params) > 0:\r\n choice.SetSelection(0)\r\n return choice\r\n\r\n def load_image(self, event: wx.Event):\r\n dir_name = \"data/illust\"\r\n file_dialog = wx.FileDialog(self, \"Choose an image\", dir_name, \"\", \"*.png\", wx.FD_OPEN)\r\n if file_dialog.ShowModal() == wx.ID_OK:\r\n image_file_name = os.path.join(file_dialog.GetDirectory(), file_dialog.GetFilename())\r\n pil_image = resize_PIL_image(extract_PIL_image_from_filelike(image_file_name))\r\n w, h = pil_image.size\r\n if pil_image.mode != 'RGBA':\r\n self.source_image_string = \"Image must have alpha channel!\"\r\n self.wx_source_image = None\r\n self.torch_source_image = None\r\n else:\r\n self.wx_source_image = wx.Bitmap.FromBufferRGBA(w, h, pil_image.convert(\"RGBA\").tobytes())\r\n self.torch_source_image = extract_pytorch_image_from_PIL_image(pil_image).to(self.device)\r\n self.Refresh()\r\n file_dialog.Destroy()\r\n\r\n def paint_source_image_panel(self, event: wx.Event):\r\n if self.wx_source_image is None:\r\n self.draw_source_image_string(self.source_image_panel, use_paint_dc=True)\r\n else:\r\n dc = wx.PaintDC(self.source_image_panel)\r\n dc.Clear()\r\n dc.DrawBitmap(self.wx_source_image, 0, 0, True)\r\n\r\n def paint_result_image_panel(self, event: wx.Event):\r\n self.last_pose = None\r\n\r\n def draw_source_image_string(self, widget, use_paint_dc: bool = True):\r\n if use_paint_dc:\r\n dc = wx.PaintDC(widget)\r\n else:\r\n dc = wx.ClientDC(widget)\r\n dc.Clear()\r\n font = wx.Font(wx.FontInfo(14).Family(wx.FONTFAMILY_SWISS))\r\n dc.SetFont(font)\r\n w, h = dc.GetTextExtent(self.source_image_string)\r\n dc.DrawText(self.source_image_string, 128 - w // 2, 128 - h // 2)\r\n\r\n def get_current_pose(self):\r\n current_pose = [0.0 for i in range(self.poser.get_num_parameters())]\r\n for morph_control_panel in self.morph_control_panels.values():\r\n morph_control_panel.set_param_value(current_pose)\r\n for rotation_control_panel in self.rotation_control_panels.values():\r\n rotation_control_panel.set_param_value(current_pose)\r\n return current_pose\r\n\r\n def update_result_image_panel(self, event: wx.Event):\r\n current_pose = self.get_current_pose()\r\n if self.last_pose is not None \\\r\n and self.last_pose == current_pose \\\r\n and self.last_output_index == self.output_index_choice.GetSelection():\r\n return\r\n self.last_pose = current_pose\r\n self.last_output_index = self.output_index_choice.GetSelection()\r\n\r\n if self.torch_source_image is None:\r\n self.draw_source_image_string(self.result_image_panel, use_paint_dc=False)\r\n return\r\n\r\n pose = torch.tensor(current_pose, device=self.device)\r\n output_index = self.output_index_choice.GetSelection()\r\n output_image = self.poser.pose(self.torch_source_image, pose, output_index)[0].detach().cpu()\r\n numpy_image = numpy.uint8(numpy.rint(convert_output_image_from_torch_to_numpy(output_image) * 255.0))\r\n self.last_output_numpy_image = numpy_image\r\n wx_image = wx.ImageFromBuffer(\r\n numpy_image.shape[0],\r\n numpy_image.shape[1],\r\n numpy_image[:, :, 0:3].tobytes(),\r\n numpy_image[:, :, 3].tobytes())\r\n wx_bitmap = wx_image.ConvertToBitmap()\r\n\r\n dc = wx.ClientDC(self.result_image_panel)\r\n dc.Clear()\r\n dc.DrawBitmap(wx_bitmap, (256 - numpy_image.shape[0]) // 2, (256 - numpy_image.shape[1]) // 2, True)\r\n\r\n def on_save_image(self, event: wx.Event):\r\n if self.last_output_numpy_image is None:\r\n logging.info(\"There is no output image to save!!!\")\r\n return\r\n\r\n dir_name = \"data/illust\"\r\n file_dialog = wx.FileDialog(self, \"Save image\", dir_name, \"\", \"*.png\", wx.FD_SAVE)\r\n if file_dialog.ShowModal() == wx.ID_OK:\r\n image_file_name = os.path.join(file_dialog.GetDirectory(), file_dialog.GetFilename())\r\n try:\r\n if os.path.exists(image_file_name):\r\n message_dialog = wx.MessageDialog(self, f\"Override {image_file_name}\", \"Manual Poser\",\r\n wx.YES_NO | wx.ICON_QUESTION)\r\n result = message_dialog.ShowModal()\r\n if result == wx.ID_YES:\r\n self.save_last_numpy_image(image_file_name)\r\n message_dialog.Destroy()\r\n else:\r\n self.save_last_numpy_image(image_file_name)\r\n except:\r\n message_dialog = wx.MessageDialog(self, f\"Could not save {image_file_name}\", \"Manual Poser\", wx.OK)\r\n message_dialog.ShowModal()\r\n message_dialog.Destroy()\r\n file_dialog.Destroy()\r\n\r\n def save_last_numpy_image(self, image_file_name):\r\n numpy_image = self.last_output_numpy_image\r\n pil_image = PIL.Image.fromarray(numpy_image, mode='RGBA')\r\n os.makedirs(os.path.dirname(image_file_name), exist_ok=True)\r\n pil_image.save(image_file_name)\r\n\r\n\r\nif __name__ == \"__main__\":\r\n cuda = torch.device('cuda')\r\n import tha2.poser.modes.mode_20\r\n\r\n poser = tha2.poser.modes.mode_20.create_poser(cuda)\r\n\r\n app = wx.App()\r\n main_frame = MainFrame(poser, cuda)\r\n main_frame.Show(True)\r\n main_frame.timer.Start(30)\r\n app.MainLoop()\r\n"
] |
[
[
"torch.device",
"torch.tensor"
]
] |
Leooo-Shen/MaskDetector
|
[
"2b4d94ee71e7d10dce6baeb7d3aac01dea5a1e80"
] |
[
"nets/yolo4-aspp.py"
] |
[
"import torch\nimport torch.nn as nn\nfrom collections import OrderedDict\nfrom nets.CSPdarknet import darknet53,Mish\n\n\ndef conv2d(filter_in, filter_out, kernel_size, stride=1):\n pad = (kernel_size - 1) // 2 if kernel_size else 0\n return nn.Sequential(OrderedDict([\n (\"conv\", nn.Conv2d(filter_in, filter_out, kernel_size=kernel_size, stride=stride, padding=pad, bias=False)),\n (\"bn\", nn.BatchNorm2d(filter_out)),\n # (\"relu\", nn.LeakyReLU(0.1)),\n (\"mish\", Mish())\n ]))\n\n#---------------------------------------------------#\n# SPP结构,利用不同大小的池化核进行池化\n# 池化后堆叠\n#---------------------------------------------------#\nclass SpatialPyramidPooling(nn.Module):\n def __init__(self, pool_sizes=[5, 9, 13]):\n super(SpatialPyramidPooling, self).__init__()\n\n self.maxpools = nn.ModuleList([nn.MaxPool2d(pool_size, 1, pool_size//2) for pool_size in pool_sizes])\n\n def forward(self, x):\n features = [maxpool(x) for maxpool in self.maxpools[::-1]]\n features = torch.cat(features + [x], dim=1)\n\n return features\n\n#---------------------------------------------------#\n# ASPP结构,利用不同大小的池化核进行池化\n# 池化后堆叠\n#---------------------------------------------------#\nclass ASPP_Module(nn.Module):\n def __init__(self, in_channel=512, depth=2048):\n super(ASPP_Module, self).__init__()\n # global average pooling : init nn.AdaptiveAvgPool2d ;also forward torch.mean(,,keep_dim=True)\n self.mean = nn.AdaptiveAvgPool2d((1, 1))\n self.conv = nn.Conv2d(in_channel, depth, 1, 1)\n # k=1 s=1 no pad\n self.atrous_block1 = nn.Conv2d(in_channel, depth, 1, 1)\n self.atrous_block6 = nn.Conv2d(in_channel, depth, 3, 1, padding=6, dilation=6)\n self.atrous_block12 = nn.Conv2d(in_channel, depth, 3, 1, padding=12, dilation=12)\n self.atrous_block18 = nn.Conv2d(in_channel, depth, 3, 1, padding=18, dilation=18)\n\n self.conv_1x1_output = nn.Conv2d(depth * 5, depth, 1, 1)\n\n def forward(self, x):\n size = x.shape[2:]\n\n image_features = self.mean(x)\n image_features = self.conv(image_features)\n image_features = nn.functional.upsample(image_features, size=size, mode='bilinear')\n\n atrous_block1 = self.atrous_block1(x)\n\n atrous_block6 = self.atrous_block6(x)\n\n atrous_block12 = self.atrous_block12(x)\n\n atrous_block18 = self.atrous_block18(x)\n\n net = self.conv_1x1_output(torch.cat([image_features, atrous_block1, atrous_block6,\n atrous_block12, atrous_block18], dim=1))\n return net\n\n#---------------------------------------------------#\n# 卷积 + 上采样\n#---------------------------------------------------#\nclass Upsample(nn.Module):\n def __init__(self, in_channels, out_channels):\n super(Upsample, self).__init__()\n\n self.upsample = nn.Sequential(\n conv2d(in_channels, out_channels, 1),\n nn.Upsample(scale_factor=2, mode='nearest')\n )\n\n def forward(self, x,):\n x = self.upsample(x)\n return x\n\n#---------------------------------------------------#\n# 三次卷积块\n#---------------------------------------------------#\ndef make_three_conv(filters_list, in_filters):\n m = nn.Sequential(\n conv2d(in_filters, filters_list[0], 1),\n conv2d(filters_list[0], filters_list[1], 3),\n conv2d(filters_list[1], filters_list[0], 1),\n )\n return m\n\n#---------------------------------------------------#\n# 五次卷积块\n#---------------------------------------------------#\ndef make_five_conv(filters_list, in_filters):\n m = nn.Sequential(\n conv2d(in_filters, filters_list[0], 1),\n conv2d(filters_list[0], filters_list[1], 3),\n conv2d(filters_list[1], filters_list[0], 1),\n conv2d(filters_list[0], filters_list[1], 3),\n conv2d(filters_list[1], filters_list[0], 1),\n )\n return m\n\n#---------------------------------------------------#\n# 最后获得yolov4的输出\n#---------------------------------------------------#\ndef yolo_head(filters_list, in_filters):\n m = nn.Sequential(\n conv2d(in_filters, filters_list[0], 3),\n nn.Conv2d(filters_list[0], filters_list[1], 1),\n )\n return m\n\n#---------------------------------------------------#\n# yolo_body\n#---------------------------------------------------#\nclass YoloBody(nn.Module):\n def __init__(self, num_anchors, num_classes):\n super(YoloBody, self).__init__()\n # backbone\n self.backbone = darknet53(None)\n\n self.conv1 = make_three_conv([512,1024],1024)\n # self.SPP = SpatialPyramidPooling()\n self.ASPP = ASPP_Module() # !!!!\n self.conv2 = make_three_conv([512,1024],2048)\n\n self.upsample1 = Upsample(512,256)\n self.conv_for_P4 = conv2d(512,256,1)\n self.make_five_conv1 = make_five_conv([256, 512],512)\n\n self.upsample2 = Upsample(256,128)\n self.conv_for_P3 = conv2d(256,128,1)\n self.make_five_conv2 = make_five_conv([128, 256],256)\n # 3*(5+num_classes)=3*(5+20)=3*(4+1+20)=75\n # 4+1+num_classes\n final_out_filter2 = num_anchors * (5 + num_classes)\n self.yolo_head3 = yolo_head([256, final_out_filter2],128)\n\n self.down_sample1 = conv2d(128,256,3,stride=2)\n self.make_five_conv3 = make_five_conv([256, 512],512)\n # 3*(5+num_classes)=3*(5+20)=3*(4+1+20)=75\n final_out_filter1 = num_anchors * (5 + num_classes)\n self.yolo_head2 = yolo_head([512, final_out_filter1],256)\n\n self.down_sample2 = conv2d(256,512,3,stride=2)\n self.make_five_conv4 = make_five_conv([512, 1024],1024)\n # 3*(5+num_classes)=3*(5+20)=3*(4+1+20)=75\n final_out_filter0 = num_anchors * (5 + num_classes)\n self.yolo_head1 = yolo_head([1024, final_out_filter0],512)\n\n\n def forward(self, x):\n # backbone\n x2, x1, x0 = self.backbone(x)\n\n P5 = self.conv1(x0)\n # P5 = self.SPP(P5)\n P5 = self.ASPP(P5)\n P5 = self.conv2(P5)\n\n P5_upsample = self.upsample1(P5)\n P4 = self.conv_for_P4(x1)\n P4 = torch.cat([P4,P5_upsample],axis=1)\n P4 = self.make_five_conv1(P4)\n\n P4_upsample = self.upsample2(P4)\n P3 = self.conv_for_P3(x2)\n P3 = torch.cat([P3,P4_upsample],axis=1)\n P3 = self.make_five_conv2(P3)\n\n P3_downsample = self.down_sample1(P3)\n P4 = torch.cat([P3_downsample,P4],axis=1)\n P4 = self.make_five_conv3(P4)\n\n P4_downsample = self.down_sample2(P4)\n P5 = torch.cat([P4_downsample,P5],axis=1)\n P5 = self.make_five_conv4(P5)\n\n out2 = self.yolo_head3(P3)\n out1 = self.yolo_head2(P4)\n out0 = self.yolo_head1(P5)\n\n return out0, out1, out2\n\n"
] |
[
[
"torch.nn.functional.upsample",
"torch.cat",
"torch.nn.Conv2d",
"torch.nn.MaxPool2d",
"torch.nn.AdaptiveAvgPool2d",
"torch.nn.Upsample",
"torch.nn.BatchNorm2d"
]
] |
cioppaanthony/online-distillation
|
[
"581e0eff97d52b9214c724b20db78f2880e02d52"
] |
[
"utils/folder_read_benchmark.py"
] |
[
"\"\"\"\n----------------------------------------------------------------------------------------\nCopyright (c) 2020 - see AUTHORS file\n\nThis file is part of the ARTHuS software.\n\nThis program is free software: you can redistribute it and/or modify it under the terms \nof the GNU Affero General Public License as published by the Free Software Foundation, \neither version 3 of the License, or (at your option) any later version.\n\nThis program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; \nwithout even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. \nSee the GNU Affero General Public License for more details.\n\nYou should have received a copy of the GNU Affero General Public License along with this \nprogram. If not, see < [ https://www.gnu.org/licenses/ | https://www.gnu.org/licenses/ ] >.\n----------------------------------------------------------------------------------------\n\"\"\"\n\nimport os\nimport cv2\nimport glob\nimport torch\nimport natsort\nimport numpy as np\nfrom tqdm import tqdm\nimport utils.filterOperations as filterOperations\n\nfrom arguments_benchmark import args\n\ndef load_from_folder(directory, normalized=True, device=\"cpu\", append_original=None, append_mask=None, append_border=None):\n\n\t# Get all file names\n\tfilename_list_original = natsort.natsorted(glob.glob(directory + \"/original_*.png\"))\n\tfilename_list_masks = natsort.natsorted(glob.glob(directory + \"/mask_*.png\"))\n\n\tif append_mask == None or append_original == None:\n\t\tappend_original = list()\n\t\tappend_mask = list()\n\n\tpbar = tqdm(total = len(filename_list_original))\n\n\tfor file_original, file_mask in zip(filename_list_original, filename_list_masks):\n\n\t\ttmp_image = cv2.imread(file_original, cv2.IMREAD_COLOR)\n\t\ttmp_label = cv2.imread(file_mask, cv2.IMREAD_GRAYSCALE)\n\n\t\tif append_border is not None:\n\t\t\tappend_border.append(borderMask(tmp_label, int(args.border[0]), int(args.border[1])))\n\n\t\ttorch_image = torch.from_numpy(tmp_image).to(device).type(torch.float).transpose(0,2).transpose(1,2)\n\t\ttorch_label = torch.from_numpy(tmp_label).to(device).type(torch.float)\n\t\ttorch_label = 1-(torch_label/255)\n\t\ttorch_label = torch_label.type(torch.long).unsqueeze_(0)\n\n\t\tif normalized:\n\t\t\ttorch_image = ((torch_image*2)/255) -1\n\n\t\tappend_original.append(torch_image.unsqueeze_(0).to(\"cpu\"))\n\t\tappend_mask.append(torch_label.to(\"cpu\"))\n\n\t\tpbar.update(1)\n\tpbar.close()\n\n\treturn append_original, append_mask, append_border\n\ndef compute_weights(labels):\n\n\ttotal = 0\n\ttotal_foreground = 0\n\n\tfor label in labels:\n\n\t\ttotal_foreground += torch.sum(label == 0).to(\"cpu\").numpy()\n\t\ttotal += label.size()[1] * label.size()[2]\n\n\tpercentage = total_foreground/total\n\n\tweights = torch.Tensor(2)\n\tweights[0] = 1/percentage\n\tweights[1] = 1/(1-percentage)\n\n\treturn weights\n\nclass ConfusionMatrix:\n\n\tdef __init__(self, device):\n\n\t\tself.TP = 0\n\t\tself.FP = 0\n\t\tself.FN = 0\n\t\tself.TN = 0\n\n\t\tself.ones = None \n\t\tself.zeros = None\n\t\tself.device = device\n\n\tdef evaluate(self, mask, groundtruth):\n\n\t\tif self.ones is None or self.zeros is None:\n\t\t\tself.update(groundtruth.size()[0], groundtruth.size()[1])\n\n\t\tself.ones = self.ones.to(self.device)\n\t\tself.zeros = self.zeros.to(self.device)\n\n\t\tTP_mask = torch.where((mask == 1) & (groundtruth == 1), self.ones, self.zeros)\n\t\tFP_mask = torch.where((mask == 1) & (groundtruth == 0), self.ones, self.zeros)\n\t\tFN_mask = torch.where((mask == 0) & (groundtruth == 1), self.ones, self.zeros)\n\t\tTN_mask = torch.where((mask == 0) & (groundtruth == 0), self.ones, self.zeros)\n\t\t\n\t\tself.TP += torch.sum(TP_mask)\n\t\tself.FP += torch.sum(FP_mask)\n\t\tself.FN += torch.sum(FN_mask)\n\t\tself.TN += torch.sum(TN_mask)\n\n\t\tself.ones = self.ones.to(\"cpu\")\n\t\tself.zeros = self.zeros.to(\"cpu\")\n\n\tdef update(self, height, width):\n\n\t\tself.ones = torch.ones((height, width), dtype=torch.float32)\n\t\tself.zeros = torch.zeros((height, width), dtype=torch.float32)\n\t\n\tdef F1(self):\n\n\t\treturn ((2*self.TP)/(2*self.TP + self.FP + self.FN)).to(\"cpu\").numpy()\n\n\tdef Jaccard(self):\n\n\t\treturn ((self.TP)/(self.TP + self.FP + self.FN)).to(\"cpu\").numpy()\n\n\tdef Accuracy(self):\n\t\treturn ((self.TP + self.TN)/(self.TP + self.FP + self.FN + self.TN)).to(\"cpu\").numpy()\n\n\tdef Precision(self):\n\n\t\treturn ((self.TP)/(self.TP + self.FP)).to(\"cpu\").numpy()\n\n\tdef TPR(self):\n\n\t\treturn ((self.TP)/(self.TP + self.FN)).to(\"cpu\").numpy()\n\n\tdef FPR(self):\n\n\t\treturn (1-((self.TN)/(self.TN+self.FP))).to(\"cpu\").numpy()\n\n\tdef get_metrics(self):\n\t\treturn [self.F1(), self.Jaccard(), self.Precision(), self.TPR(), self.FPR(), self.Accuracy()]\n\n\tdef __str__(self):\n\n\t\tprint(\"Jaccard : \", self.Jaccard())\n\t\tprint(\"F1 : \", self.F1())\n\t\tprint(\"Precision :\", self.Precision())\n\t\tprint(\"TPR : \", self.TPR())\n\t\tprint(\"FPR : \", self.FPR())\n\t\tprint(\"Accuracy : \", self.Accuracy())\n\t\tprint(self.TP, \" - \", self.FP)\n\t\tprint(self.FN, \" - \", self.TN)\n\n\t\treturn \"-----\"\n\ndef borderMask(mask, inner_border_size, outer_border_size):\n\n\tmask_eroded = filterOperations.morphological_erosion(mask, 2*inner_border_size+1)\n\tmask_dilated = filterOperations.morphological_dilation(mask, 2*outer_border_size+1)\n\tborder = mask_dilated - mask_eroded\n\tout = np.abs(mask-0.5*border)\n\tout_tensor = torch.from_numpy(out).type(torch.float)/255\n\treturn out_tensor"
] |
[
[
"torch.ones",
"numpy.abs",
"torch.Tensor",
"torch.zeros",
"torch.sum",
"torch.from_numpy",
"torch.where"
]
] |
shauheen/triton
|
[
"12b6158c5cbc10c56f935985e6f466c9867d9238"
] |
[
"python/triton/testing.py"
] |
[
"import torch\nimport os\nfrom .code_gen import OutOfResources\nimport subprocess\nimport sys\n\n\ntry:\n import triton._C.libtriton.cutlass as _cutlass\n has_cutlass = True\nexcept ImportError:\n _cutlass = None\n has_cutlass = False\n\ndef catch_oor(kernel, pytest_handle=None):\n try:\n res = kernel()\n except OutOfResources as e:\n if pytest_handle:\n pytest_handle.skip(str(e))\n return None\n return res\n\n\ndef sparsify_tensor(x, mask, block):\n ret = torch.empty((x.size(0), mask.sum(), block, block), dtype=x.dtype, device=x.device)\n for idx, (h, i, j) in enumerate(zip(*mask.nonzero(as_tuple=True))):\n ret[:, idx, :, :] = x[:, h, i * block:(i + 1) * block, j * block:(j + 1) * block]\n return ret\n\n\ndef cutlass_matmul(a, b):\n if _cutlass is None:\n raise RuntimeError(\"Cannot find cutlass library\")\n M, N = a.shape[0], b.shape[1]\n Ka, Kb = a.shape[1], b.shape[0]\n assert Ka == Kb\n assert a.dtype == b.dtype\n assert a.device == b.device\n # allocate output\n c = torch.empty_strided((M, N), (1, M), dtype=a.dtype, device=a.device)\n # run function\n dtype = str(a.dtype).split('.')[-1]\n _cutlass.matmul(a.data_ptr(), b.data_ptr(), c.data_ptr(), \\\n M, N, Ka,\\\n a.stride(0), a.stride(1),\\\n b.stride(0), b.stride(1),\\\n c.stride(0), c.stride(1),\\\n dtype, dtype, dtype,\n a.device.index, torch.cuda.current_stream(a.device).cuda_stream)\n\n return c\n\n\ndef mask_tensor(x, mask, block, value=0):\n ret = x.clone()\n for h, i, j in zip(*(mask == 0).nonzero(as_tuple=True)):\n ret[:, h, i * block:(i + 1) * block, j * block:(j + 1) * block] = value\n return ret\n\ndef assert_almost_equal(x, y, decimal=2, err_msg=''):\n import numpy.testing as npt\n if isinstance(x, torch.Tensor):\n x = x.cpu().detach().numpy()\n if isinstance(y, torch.Tensor):\n y = y.cpu().detach().numpy()\n npt.assert_array_almost_equal(x, y, err_msg=err_msg, decimal=decimal)\n\n\ndef allclose(x, y, tol=1e-2):\n if x.dtype != y.dtype:\n raise RuntimeError(f'{x.dtype} did not match with {x.dtype}')\n if x.shape != y.shape:\n raise RuntimeError(f'{x.shape} did not match with {y.shape}')\n if x.dtype == torch.bool:\n return torch.sum(x ^ y) == 0\n if x.dtype in [torch.int8, torch.int16, torch.int32, torch.int64]:\n tol = 0\n diff = abs(x - y)\n x_max = torch.max(x)\n y_max = torch.max(y)\n tol = 1e-2\n err = torch.max(diff) / torch.max(x_max, y_max)\n return err <= tol\n\n\ndef assert_allclose(x, y, tol=1e-2):\n assert x.dtype == y.dtype\n assert allclose(x, y, tol)\n\n\ndef random(shape, dtype, device):\n torch.manual_seed(0)\n if isinstance(shape, int):\n shape = (shape, )\n if dtype == torch.bool:\n return torch.randint(0, 2, shape, dtype=dtype, device=device)\n if dtype in [torch.int8, torch.int16, torch.int32, torch.int64]:\n return torch.randint(1, 32, shape, dtype=dtype, device=device)\n if dtype in [torch.float16, torch.float32, torch.float64]:\n return torch.normal(0, 1, shape, dtype=dtype, device=device)\n raise RuntimeError(f'Unknown dtype {dtype}')\n\n\ndef nvsmi(attrs):\n attrs = ','.join(attrs)\n cmd = ['nvidia-smi', '-i', '0', '--query-gpu=' + attrs, '--format=csv,noheader,nounits']\n out = subprocess.check_output(cmd)\n ret = out.decode(sys.stdout.encoding).split(',')\n ret = [int(x) for x in ret]\n return ret\n\ndef do_bench(fn, warmup=25, rep=100, grad_to_none=None, percentiles=[0.5, 0.2, 0.8], record_clocks=False):\n \"\"\"\n Benchmark the runtime of the provided function. By default, return the median runtime of :code:`fn` along with\n the 20-th and 80-th performance percentile.\n\n :param fn: Function to benchmark\n :type fn: Callable\n :param warmup: Warmup time (in ms)\n :type warmup: int\n :param rep: Repetition time (in ms)\n :type rep: int\n :param grad_to_none: Reset the gradient of the provided tensor to None\n :type grad_to_none: torch.tensor, optional\n :param percentiles: Performance percentile to return in addition to the median.\n :type percentiles: list[float]\n \"\"\"\n\n # Estimate the runtime of the function\n fn()\n torch.cuda.synchronize()\n start_event = torch.cuda.Event(enable_timing=True)\n end_event = torch.cuda.Event(enable_timing=True)\n start_event.record()\n for _ in range(5):\n fn()\n end_event.record()\n torch.cuda.synchronize()\n estimate_ms = start_event.elapsed_time(end_event) / 5\n # compute number of warmup and repeat\n n_warmup = max(1, int(warmup/estimate_ms))\n n_repeat = max(1, int(rep/estimate_ms))\n # We maintain a buffer of 256 MB that we clear\n # before each kernel call to make sure that the L2\n # doesn't contain any input data before the run\n start_event = [torch.cuda.Event(enable_timing=True) for i in range(n_repeat)]\n end_event = [torch.cuda.Event(enable_timing=True) for i in range(n_repeat)]\n cache = torch.empty(int(256e6), dtype=torch.int8, device='cuda')\n # Warm-up\n for _ in range(n_warmup):\n fn()\n # Benchmark\n for i in range(n_repeat):\n # we don't want `fn` to accumulate gradient values\n # if it contains a backward pass. So we clear the\n # provided gradients\n if grad_to_none is not None:\n for x in grad_to_none:\n x.grad = None\n # we clear the L2 cache before each run\n cache.zero_()\n # record time of `fn`\n start_event[i].record()\n fn()\n end_event[i].record()\n # Record clocks\n torch.cuda.synchronize()\n times = torch.tensor([s.elapsed_time(e) for s, e in zip(start_event, end_event)])\n if percentiles:\n percentiles = torch.quantile(times, torch.tensor(percentiles)).tolist()\n return tuple(percentiles)\n else:\n return torch.mean(times).item()\n\n\nclass Benchmark:\n \"\"\"\n This class is used by the :code:`perf_report` function to generate line plots with a concise API.\n \"\"\"\n def __init__(\n self,\n x_names,\n x_vals,\n line_arg,\n line_vals,\n line_names,\n plot_name,\n args,\n xlabel='',\n ylabel='',\n x_log=False,\n y_log=False,\n color=None,\n styles=None,\n ):\n \"\"\"\n Constructor \n\n :param x_names: Name of the arguments that should appear on the x axis of the plot. If the list contains more than one element, all the arguments are assumed to have the same value.\n :type x_names: List[str]\n :param x_vals: List of values to use for the arguments in :code:`x_names`.\n :type x_vals: List[Any]\n :param line_arg: Argument name for which different values correspond to different lines in the plot.\n :type line_arg: str\n :param line_vals: List of values to use for the arguments in :code:`line_arg`.\n :type line_vals: List[str]\n :param line_names: Label names for the different lines.\n :type line_names: List[str]\n :param plot_name: Name of the plot.\n :type plot_name: str\n :param args: List of arguments to remain fixed throughout the benchmark.\n :type args: List[str]\n :param xlabel: Label for the x axis of the plot.\n :type xlabel: str, optional\n :param ylabel: Label for the y axis of the plot.\n :type ylabel: str, optional\n :param x_log: Whether the x axis should be log scale.\n :type x_log: bool, optional\n :param y_log: Whether the y axis should be log scale.\n :type y_log: bool, optional\n \"\"\"\n self.x_names = x_names\n self.x_vals = x_vals\n self.x_log = x_log\n self.line_arg = line_arg\n self.line_vals = line_vals\n self.line_names = line_names\n self.y_log = y_log\n self.styles = styles\n # plot info\n self.xlabel = xlabel\n self.ylabel = ylabel\n self.plot_name = plot_name\n self.args = args\n\n\nclass Mark:\n def __init__(self, fn, benchmarks):\n self.fn = fn\n self.benchmarks = benchmarks\n\n def _run(self, bench, save_path, show_plots, print_data):\n import matplotlib.pyplot as plt\n import pandas as pd\n import os\n y_mean = bench.line_names\n y_min = [f'{x}-min' for x in bench.line_names]\n y_max = [f'{x}-max' for x in bench.line_names]\n df = pd.DataFrame(columns=[bench.x_names[0]] + y_mean + y_min + y_max)\n for x in bench.x_vals:\n x_args = {x_name: x for x_name in bench.x_names}\n row_mean, row_min, row_max = [], [], []\n for y in bench.line_vals:\n ret = self.fn(**x_args, **{bench.line_arg: y}, **bench.args)\n try:\n y_mean, y_min, y_max = ret\n except TypeError:\n y_mean, y_min, y_max = ret, None, None\n row_mean += [y_mean]\n row_min += [y_min]\n row_max += [y_max]\n df.loc[len(df)] = [x] + row_mean + row_min + row_max\n if bench.plot_name:\n plt.figure()\n ax = plt.subplot()\n x = bench.x_names[0]\n for i, y in enumerate(bench.line_names):\n y_min, y_max = df[y + '-min'], df[y + '-max']\n col = bench.styles[i][0] if bench.styles else None\n sty = bench.styles[i][1] if bench.styles else None\n ax.plot(df[x], df[y], label=y, color=col, ls=sty)\n if y_min is not None and y_max is not None:\n ax.fill_between(df[x], y_min, y_max, alpha=0.15, color=col)\n ax.legend()\n xlabel = bench.xlabel if bench.xlabel else \" = \".join(bench.x_names)\n ax.set_xlabel(xlabel)\n ax.set_ylabel(bench.ylabel)\n #ax.set_title(bench.plot_name)\n ax.set_xscale(\"log\" if bench.x_log else \"linear\")\n ax.set_yscale(\"log\" if bench.y_log else \"linear\")\n if show_plots:\n plt.show()\n if save_path:\n plt.savefig(os.path.join(save_path, f\"{bench.plot_name}.png\"))\n df = df[[bench.x_names[0]] + bench.line_names]\n if print_data:\n print(bench.plot_name + ':')\n print(df)\n if save_path:\n df.to_csv(os.path.join(save_path, f\"{bench.plot_name}.csv\"), float_format='%.1f', index=False)\n\n def run(self, show_plots=False, print_data=False, save_path=''):\n has_single_bench = isinstance(self.benchmarks, Benchmark)\n benchmarks = [self.benchmarks] if has_single_bench else self.benchmarks\n if save_path:\n html = open(os.path.join(save_path, \"results.html\"), \"w\")\n html.write(\"<html><body>\\n\")\n for bench in benchmarks:\n self._run(bench, save_path, show_plots, print_data)\n if save_path:\n html.write(f\"<image src=\\\"{bench.plot_name}.png\\\"/>\\n\")\n if save_path:\n html.write(\"</body></html>\\n\")\n\n\ndef perf_report(benchmarks):\n \"\"\"\n Mark a function for benchmarking. The benchmark can then be executed by using the :code:`.run` method on the return value.\n\n :param benchmarks: Benchmarking configurations.\n :type benchmarks: List of :class:`Benchmark`\n \"\"\"\n wrapper = lambda fn: Mark(fn, benchmarks)\n return wrapper\n"
] |
[
[
"torch.normal",
"torch.mean",
"torch.cuda.synchronize",
"torch.randint",
"torch.max",
"torch.manual_seed",
"torch.cuda.current_stream",
"torch.cuda.Event",
"torch.sum",
"matplotlib.pyplot.figure",
"pandas.DataFrame",
"torch.tensor",
"matplotlib.pyplot.subplot",
"torch.empty_strided",
"matplotlib.pyplot.show",
"numpy.testing.assert_array_almost_equal"
]
] |
CxzPink/polyGAT
|
[
"95ee1414dd721567f321a7a6271ce518964688ac"
] |
[
"models.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom layers import GraphAttentionLayer, SpGraphAttentionLayer, my_SpGraphAttentionLayer1, my_SpGraphAttentionLayer2\n\n\nclass GAT(nn.Module):\n def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):\n \"\"\"Dense version of GAT.\"\"\"\n super(GAT, self).__init__()\n self.dropout = dropout\n\n self.attentions = [GraphAttentionLayer(nfeat, nhid, dropout=dropout, alpha=alpha, concat=True) for _ in range(nheads)]\n for i, attention in enumerate(self.attentions):\n self.add_module('attention_{}'.format(i), attention)\n\n self.out_att = GraphAttentionLayer(nhid * nheads, nclass, dropout=dropout, alpha=alpha, concat=False)\n\n def forward(self, x, adj):\n x = F.dropout(x, self.dropout, training=self.training)\n x = torch.cat([att(x, adj) for att in self.attentions], dim=1)\n x = F.dropout(x, self.dropout, training=self.training)\n x = F.elu(self.out_att(x, adj))\n return F.log_softmax(x, dim=1)\n\n\nclass SpGAT(nn.Module):\n def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):\n \"\"\"Sparse version of GAT.\"\"\"\n super(SpGAT, self).__init__()\n self.dropout = dropout\n\n self.attentions = [SpGraphAttentionLayer(nfeat, \n nhid, \n dropout=dropout, \n alpha=alpha, \n concat=True) for _ in range(nheads)]\n for i, attention in enumerate(self.attentions):\n self.add_module('attention_{}'.format(i), attention)\n\n self.out_att = SpGraphAttentionLayer(nhid * nheads, \n nclass, \n dropout=dropout, \n alpha=alpha, \n concat=False)\n\n def forward(self, x, adj):\n x = F.dropout(x, self.dropout, training=self.training)\n x = torch.cat([att(x, adj) for att in self.attentions], dim=1)\n x = F.dropout(x, self.dropout, training=self.training)\n x = F.elu(self.out_att(x, adj))\n return F.log_softmax(x, dim=1)\n\n\nclass my_SpGAT(nn.Module):\n def __init__(self, nfeat, nhid, nclass, dropout, alpha, nheads):\n super(my_SpGAT, self).__init__()\n self.dropout = dropout\n self.attentions = [my_SpGraphAttentionLayer2(nfeat, \n nhid, \n dropout=dropout, \n alpha=alpha, \n concat=True) for _ in range(nheads)]\n for i, attention in enumerate(self.attentions):\n self.add_module('attention_{}'.format(i), attention)\n\n self.out_att = my_SpGraphAttentionLayer1(nhid * nheads, \n nclass, \n dropout=dropout, \n alpha=alpha, \n concat=False)\n\n def forward(self, x, adj):\n x = F.dropout(x, self.dropout, training=self.training)\n x = torch.cat([att(x, adj) for att in self.attentions], dim=1)\n x = F.dropout(x, self.dropout, training=self.training)\n x = F.elu(self.out_att(x, adj))\n return F.log_softmax(x, dim=1)"
] |
[
[
"torch.nn.functional.log_softmax",
"torch.nn.functional.dropout"
]
] |
mosin26/selforacle
|
[
"c99478bf65fd137014f3b7947ed83d105b9f038a"
] |
[
"code-predictors/detectors/single_image_based_detectors/autoencoders/convolutional_autoencoder.py"
] |
[
"from tensorflow.keras import Input, Model\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, UpSampling2D, BatchNormalization, Activation\n\nimport numpy as np\n\nfrom detectors.single_image_based_detectors.abs_single_image_autoencoder import AbstractSingleImageAD\nfrom detectors.single_image_based_detectors.autoencoder_batch_generator import AutoencoderBatchGenerator\nfrom detectors.anomaly_detector import AnomalyDetector\nfrom utils import IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS\n\nINPUT_SHAPE = (IMAGE_HEIGHT, IMAGE_WIDTH, IMAGE_CHANNELS)\n\n\nclass ConvolutionalAutoencoder(AbstractSingleImageAD, AnomalyDetector):\n\n def __init__(self, name: str, args):\n super(ConvolutionalAutoencoder, self).__init__(name=name, is_keras_model=True, args=args)\n\n def get_input_shape(self):\n return INPUT_SHAPE\n\n def _create_keras_model(self, input_shape, args=None):\n input_img = Input(shape=input_shape)\n\n x = Conv2D(64, (3, 3), padding='same')(input_img)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(32, (3, 3), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = MaxPooling2D((2, 2), padding='same')(x)\n x = Conv2D(16, (3, 3), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n encoded = MaxPooling2D((2, 2), padding='same')(x)\n\n x = Conv2D(16, (3, 3), padding='same')(encoded)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = UpSampling2D((2, 2))(x)\n x = Conv2D(32, (3, 3), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = UpSampling2D((2, 2))(x)\n x = Conv2D(64, (3, 3), padding='same')(x)\n x = BatchNormalization()(x)\n x = Activation('relu')(x)\n x = UpSampling2D((2, 2))(x)\n x = Conv2D(3, (3, 3), padding='same')(x)\n x = BatchNormalization()(x)\n decoded = Activation('sigmoid')(x)\n\n autoencoder = Model(input_img, decoded)\n return autoencoder\n\n def normalize_and_reshape(self, x):\n x = x.astype('float32') / 255.\n x = np.reshape(x, newshape=INPUT_SHAPE) # CNN needs depth.\n return x\n"
] |
[
[
"tensorflow.keras.layers.Activation",
"tensorflow.keras.Input",
"numpy.reshape",
"tensorflow.keras.layers.Conv2D",
"tensorflow.keras.layers.UpSampling2D",
"tensorflow.keras.Model",
"tensorflow.keras.layers.BatchNormalization",
"tensorflow.keras.layers.MaxPooling2D"
]
] |
zjplab/nmt_soft_prototype
|
[
"38ccc0b3a118072560ddbfb2c3d95d81e95082c8"
] |
[
"fairseq/models/transformer_soft_proto.py"
] |
[
"# Copyright (c) 2017-present, Facebook, Inc.\n# All rights reserved.\n#\n# This source code is licensed under the license found in the LICENSE file in\n# the root directory of this source tree. An additional grant of patent rights\n# can be found in the PATENTS file in the same directory.\n\nimport math\nfrom copy import copy\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom fairseq import utils\n\nfrom fairseq.modules import (\n LearnedPositionalEmbedding, MultiheadAttention,\n SinusoidalPositionalEmbedding,\n)\n\nfrom . import (\n FairseqIncrementalDecoder, FairseqEncoder, FairseqDecoder, FairseqModel,\n register_model, register_model_architecture,\n)\n\nfrom fairseq.models.transformer import TransformerEncoderLayer, TransformerDecoderLayer\n\n\n@register_model('transformer_soft_proto')\nclass TransformerSoftProtoModel(FairseqModel):\n def __init__(self, encoder, decoder):\n super().__init__(encoder, decoder)\n\n assert isinstance(self.encoder, FairseqEncoder)\n assert isinstance(self.decoder, FairseqDecoder)\n\n def forward(self, src_tokens, src_lengths, prev_output_tokens,\n src_tokens_2=None, src_scores_2=None, src_lengths_2=None):\n encoder_out = self.encoder(src_tokens, src_lengths, src_tokens_2, src_scores_2, src_lengths_2)\n decoder_out = self.decoder(prev_output_tokens, encoder_out)\n return decoder_out\n\n @staticmethod\n def add_args(parser):\n \"\"\"Add model-specific arguments to the parser.\"\"\"\n parser.add_argument('--dropout', type=float, metavar='D',\n help='dropout probability')\n parser.add_argument('--attention-dropout', type=float, metavar='D',\n help='dropout probability for attention weights')\n parser.add_argument('--relu-dropout', type=float, metavar='D',\n help='dropout probability after ReLU in FFN')\n parser.add_argument('--encoder-embed-path', type=str, metavar='STR',\n help='path to pre-trained encoder embedding')\n parser.add_argument('--encoder-embed-dim', type=int, metavar='N',\n help='encoder embedding dimension')\n parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N',\n help='encoder embedding dimension for FFN')\n parser.add_argument('--encoder-layers', type=int, metavar='N',\n help='num encoder layers')\n parser.add_argument('--encoder2-layers', type=int, metavar='N',\n help='num encoder2 layers')\n parser.add_argument('--encoder-attention-heads', type=int, metavar='N',\n help='num encoder attention heads')\n parser.add_argument('--encoder-normalize-before', default=False, action='store_true',\n help='apply layernorm before each encoder block')\n parser.add_argument('--encoder-learned-pos', default=False, action='store_true',\n help='use learned positional embeddings in the encoder')\n parser.add_argument('--encoder1-pos-emb', default=\"timing\", type=str, metavar='STR',\n help='whether to use positional embeddings in encoder_1 (not used if none)')\n parser.add_argument('--encoder2-pos-emb', default=\"none\", type=str, metavar='STR',\n help='whether to use positional embeddings in encoder_2 (not used if none)')\n parser.add_argument('--share-encoder-params', default=False, action='store_true',\n help='share encoder and enc-dec attn parameters')\n parser.add_argument('--proto-emb-no-grad', default=False, action='store_true',\n help='no gradient from proto-emb')\n parser.add_argument('--decoder-embed-path', type=str, metavar='STR',\n help='path to pre-trained decoder embedding')\n parser.add_argument('--decoder-embed-dim', type=int, metavar='N',\n help='decoder embedding dimension')\n parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N',\n help='decoder embedding dimension for FFN')\n parser.add_argument('--decoder-layers', type=int, metavar='N',\n help='num decoder layers')\n parser.add_argument('--proto-layers', type=str, default='all', metavar='STR',\n help='all, or layer ids to add prototype, semicolon separated, e.g., 0;1;2;')\n parser.add_argument('--decoder-attention-heads', type=int, metavar='N',\n help='num decoder attention heads')\n parser.add_argument('--decoder-learned-pos', default=False, action='store_true',\n help='use learned positional embeddings in the decoder')\n parser.add_argument('--decoder-normalize-before', default=False, action='store_true',\n help='apply layernorm before each decoder block')\n parser.add_argument('--share-decoder-input-output-embed', default=False, action='store_true',\n help='share decoder input and output embeddings')\n parser.add_argument('--share-all-embeddings', default=False, action='store_true',\n help='share encoder, decoder and output embeddings'\n ' (requires shared dictionary and embed dim)')\n\n @classmethod\n def build_model(cls, args, task):\n \"\"\"Build a new model instance.\"\"\"\n # make sure that all args are properly defaulted (in case there are any new ones)\n base_architecture(args)\n\n src_dict, tgt_dict = task.source_dictionary, task.target_dictionary\n\n def build_embedding(dictionary, embed_dim, path=None):\n num_embeddings = len(dictionary)\n padding_idx = dictionary.pad()\n emb = Embedding(num_embeddings, embed_dim, padding_idx)\n # if provided, load from preloaded dictionaries\n if path:\n embed_dict = utils.parse_embedding(path)\n utils.load_embedding(embed_dict, dictionary, emb)\n return emb\n\n if args.share_all_embeddings:\n if src_dict != tgt_dict:\n raise RuntimeError('--share-all-embeddings requires a joined dictionary')\n if args.encoder_embed_dim != args.decoder_embed_dim:\n raise RuntimeError(\n '--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim')\n if args.decoder_embed_path and (\n args.decoder_embed_path != args.encoder_embed_path):\n raise RuntimeError('--share-all-embeddings not compatible with --decoder-embed-path')\n encoder_embed_tokens = build_embedding(\n src_dict, args.encoder_embed_dim, args.encoder_embed_path\n )\n decoder_embed_tokens = encoder_embed_tokens\n args.share_decoder_input_output_embed = True\n else:\n encoder_embed_tokens = build_embedding(\n src_dict, args.encoder_embed_dim, args.encoder_embed_path\n )\n decoder_embed_tokens = build_embedding(\n tgt_dict, args.decoder_embed_dim, args.decoder_embed_path\n )\n\n add_pos_emb_1 = args.encoder1_pos_emb != \"none\"\n add_pos_emb_2 = args.encoder2_pos_emb != \"none\"\n encoder = TransformerProtoEncoder(\n args, src_dict, encoder_embed_tokens,\n add_pos_emb_1=add_pos_emb_1,\n add_pos_emd_2=add_pos_emb_2)\n decoder = TransformerProtoDecoder(args, tgt_dict, decoder_embed_tokens)\n return TransformerSoftProtoModel(encoder, decoder)\n\n\nclass TransformerProtoEncoder(FairseqEncoder):\n def __init__(self, args, dictionary, embed_tokens,\n left_pad=True, add_pos_emb_1=True, add_pos_emd_2=False):\n super().__init__(dictionary)\n self.share_encoder_params = args.share_encoder_params\n\n print(\"| [model] building soft prototype encoder, shared = {}\".format(self.share_encoder_params))\n self.encoder_1 = TransformerProtoSingleEncoder(\n args, dictionary, embed_tokens, left_pad, add_pos_emb_1)\n args2 = copy(args)\n args2.encoder_layers = args.encoder2_layers\n self.encoder_2 = TransformerProtoSingleEncoder(\n args2, dictionary, embed_tokens, left_pad, add_pos_emd_2) \\\n if not self.share_encoder_params else None\n\n def forward(self, src_tokens, src_lengths,\n src_tokens_2=None, src_scores_2=None, src_lengths_2=None):\n encoder_out_1 = self.encoder_1(src_tokens, src_lengths, weighted_comb=False)\n encoder_out_2 = self.encoder_2(\n src_tokens_2, src_lengths_2, src_scores_2, True\n ) if not self.share_encoder_params else self.encoder_1(\n src_tokens_2, src_lengths_2, src_scores_2, True\n )\n return {\n 'encoder_out_1': encoder_out_1['encoder_out'],\n 'encoder_padding_mask_1': encoder_out_1['encoder_padding_mask'],\n 'encoder_out_2': encoder_out_2['encoder_out'],\n 'encoder_padding_mask_2': encoder_out_2['encoder_padding_mask'],\n }\n\n def reorder_encoder_out(self, encoder_out_dict, new_order):\n if encoder_out_dict['encoder_out_1'] is not None:\n encoder_out_dict['encoder_out_1'] = \\\n encoder_out_dict['encoder_out_1'].index_select(1, new_order)\n if encoder_out_dict['encoder_out_2'] is not None:\n encoder_out_dict['encoder_out_2'] = \\\n encoder_out_dict['encoder_out_2'].index_select(1, new_order)\n if encoder_out_dict['encoder_padding_mask_1'] is not None:\n encoder_out_dict['encoder_padding_mask_1'] = \\\n encoder_out_dict['encoder_padding_mask_1'].index_select(0, new_order)\n if encoder_out_dict['encoder_padding_mask_2'] is not None:\n encoder_out_dict['encoder_padding_mask_2'] = \\\n encoder_out_dict['encoder_padding_mask_2'].index_select(0, new_order)\n return encoder_out_dict\n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n return self.encoder_1.max_positions()\n\n def upgrade_state_dict(self, state_dict):\n if isinstance(self.encoder_1.embed_positions, SinusoidalPositionalEmbedding):\n if 'encoder.encoder_1.embed_positions.weights' in state_dict:\n del state_dict['encoder.encoder_1.embed_positions.weights']\n if 'encoder.encoder_1.embed_positions._float_tensor' not in state_dict:\n state_dict['encoder.encoder_1.embed_positions._float_tensor'] = torch.FloatTensor()\n if not self.share_encoder_params and isinstance(\n self.encoder_2.embed_positions, SinusoidalPositionalEmbedding):\n if 'encoder.encoder_2.embed_positions.weights' in state_dict:\n del state_dict['encoder.encoder_2.embed_positions.weights']\n if 'encoder.encoder_2.embed_positions._float_tensor' not in state_dict:\n state_dict['encoder.encoder_2.embed_positions._float_tensor'] = torch.FloatTensor()\n return state_dict\n\n\nclass TransformerProtoSingleEncoder(FairseqEncoder):\n \"\"\"Transformer encoder.\"\"\"\n\n def __init__(self, args, dictionary, embed_tokens, left_pad=True, add_pos_emb=True):\n super().__init__(dictionary)\n\n self.dropout = args.dropout\n self.add_pos_emb = add_pos_emb\n\n embed_dim = embed_tokens.embedding_dim\n self.padding_idx = embed_tokens.padding_idx\n self.proto_k = args.proto_k\n self.proto_emb_no_grad = getattr(args, 'proto_emb_no_grad', False)\n\n print(\"| ---- [encoder] building prob encoder, layers = {}, add_pos_emb = {}, \"\n \"proto_k = {}, proto_emb_no_grad = {}\".format(\n args.encoder_layers, add_pos_emb, self.proto_k, self.proto_emb_no_grad))\n\n self.embed_tokens = embed_tokens\n self.embed_scale = math.sqrt(embed_dim)\n self.embed_positions = PositionalEmbedding(\n 1024, embed_dim, self.padding_idx,\n left_pad=left_pad,\n learned=args.encoder_learned_pos,\n )\n\n self.layers = nn.ModuleList([])\n self.layers.extend([\n TransformerEncoderLayer(args)\n for i in range(args.encoder_layers)\n ])\n\n def forward(self, src_tokens, src_lengths, src_scores=None, weighted_comb=False):\n\n def _get_weighted_emb(src_scores):\n x = self.embed_tokens(src_tokens) # B x T x k x C\n s1, s2, s3 = x.size(0), x.size(1), x.size(2)\n if src_scores is None:\n src_scores = x.new(s1, s2, s3).fill_(1. / self.proto_k)\n src_scores = src_scores.view(s1, s2, s3, 1)\n x = (x * src_scores).sum(2) # B x T x C\n return x\n\n # embed tokens and positions\n if not weighted_comb:\n x = self.embed_tokens(src_tokens) # B x T x C\n else:\n if self.proto_emb_no_grad:\n with torch.no_grad():\n x = _get_weighted_emb(src_scores)\n else:\n x = _get_weighted_emb(src_scores)\n\n x *= self.embed_scale\n if self.add_pos_emb:\n x += self.embed_positions(src_tokens if not weighted_comb else src_tokens[:, :, 0])\n x = F.dropout(x, p=self.dropout, training=self.training)\n\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n\n # compute padding mask\n encoder_padding_mask = src_tokens.eq(self.padding_idx) \\\n if not weighted_comb else src_tokens[:, :, 0].eq(self.padding_idx)\n if not encoder_padding_mask.any():\n encoder_padding_mask = None\n\n # encoder layers\n for layer in self.layers:\n x = layer(x, encoder_padding_mask)\n\n return {\n 'encoder_out': x, # T x B x C\n 'encoder_padding_mask': encoder_padding_mask, # B x T\n }\n\n def reorder_encoder_out(self, encoder_out_dict, new_order):\n if encoder_out_dict.get('encoder_out') is not None:\n encoder_out_dict['encoder_out'] = \\\n encoder_out_dict['encoder_out'].index_select(1, new_order)\n if encoder_out_dict.get('encoder_padding_mask') is not None:\n encoder_out_dict['encoder_padding_mask'] = \\\n encoder_out_dict['encoder_padding_mask'].index_select(0, new_order)\n return encoder_out_dict\n\n def max_positions(self):\n \"\"\"Maximum input length supported by the encoder.\"\"\"\n # return self.embed_positions.max_positions()\n return int(1e7) # an arbitrary large number\n\n def upgrade_state_dict(self, state_dict):\n return state_dict\n\n\nclass TransformerProtoDecoder(FairseqIncrementalDecoder):\n \"\"\"Transformer decoder.\"\"\"\n\n def __init__(self, args, dictionary, embed_tokens, left_pad=False):\n super().__init__(dictionary)\n print(\"| [model] building soft prototype decoder, layers = {}, shared = {}\".format(\n args.decoder_layers, args.share_encoder_params))\n\n self.dropout = args.dropout\n self.share_input_output_embed = args.share_decoder_input_output_embed\n self.share_encoder_params = args.share_encoder_params\n\n embed_dim = embed_tokens.embedding_dim\n padding_idx = embed_tokens.padding_idx\n\n self.embed_tokens = embed_tokens\n self.embed_scale = math.sqrt(embed_dim)\n self.embed_positions = PositionalEmbedding(\n 1024, embed_dim, padding_idx,\n left_pad=left_pad,\n learned=args.decoder_learned_pos,\n )\n\n self.proto_layers = [int(i) for i in args.proto_layers.split(\";\")] \\\n if args.proto_layers != \"all\" else [i for i in range(args.decoder_layers)]\n print(\"| ---- [decoder] adding soft prototype to layer: {}\".format(args.proto_layers))\n\n self.layers = nn.ModuleList([])\n self.layers.extend([\n TransformerProtoDecoderLayer(args) if i in self.proto_layers\n else TransformerDecoderLayer(args)\n for i in range(args.decoder_layers)\n ])\n\n if not self.share_input_output_embed:\n self.embed_out = nn.Parameter(torch.Tensor(len(dictionary), embed_dim))\n nn.init.normal_(self.embed_out, mean=0, std=embed_dim ** -0.5)\n\n def forward(self, prev_output_tokens, encoder_out, incremental_state=None):\n # embed positions\n positions = self.embed_positions(\n prev_output_tokens,\n incremental_state=incremental_state,\n )\n\n if incremental_state is not None:\n prev_output_tokens = prev_output_tokens[:, -1:]\n positions = positions[:, -1:]\n\n # embed tokens and positions\n x = self.embed_scale * self.embed_tokens(prev_output_tokens)\n x += positions\n x = F.dropout(x, p=self.dropout, training=self.training)\n\n # B x T x C -> T x B x C\n x = x.transpose(0, 1)\n\n incremental_state_single = incremental_state\n if incremental_state is not None and self.share_encoder_params:\n incremental_state_single = incremental_state[0]\n\n # decoder layers\n for layer_id, layer in enumerate(self.layers):\n x, attn = layer(\n x,\n (encoder_out['encoder_out_1'], encoder_out['encoder_out_2']),\n (encoder_out['encoder_padding_mask_1'], encoder_out['encoder_padding_mask_2']),\n incremental_state,\n ) if layer_id in self.proto_layers else layer(\n x,\n encoder_out['encoder_out_1'],\n encoder_out['encoder_padding_mask_1'],\n incremental_state_single,\n )\n\n # T x B x C -> B x T x C\n x = x.transpose(0, 1)\n\n # project back to size of vocabulary\n if self.share_input_output_embed:\n x = F.linear(x, self.embed_tokens.weight)\n else:\n x = F.linear(x, self.embed_out)\n\n return x, attn\n\n def max_positions(self):\n \"\"\"Maximum output length supported by the decoder.\"\"\"\n # return self.embed_positions.max_positions()\n return int(1e7)\n\n def upgrade_state_dict(self, state_dict):\n if isinstance(self.embed_positions, SinusoidalPositionalEmbedding):\n if 'decoder.embed_positions.weights' in state_dict:\n del state_dict['decoder.embed_positions.weights']\n if 'decoder.embed_positions._float_tensor' not in state_dict:\n state_dict['decoder.embed_positions._float_tensor'] = torch.FloatTensor()\n return state_dict\n\n def reorder_incremental_state(self, incremental_state, new_order):\n \"\"\"Reorder incremental state.\n\n This should be called when the order of the input has changed from the\n previous time step. A typical use case is beam search, where the input\n order changes between time steps based on the selection of beams.\n \"\"\"\n def apply_reorder_incremental_state(module):\n if module != self and hasattr(module, 'reorder_incremental_state'):\n if self.share_encoder_params and len(incremental_state) == 2:\n module.reorder_incremental_state(\n incremental_state[0],\n new_order,\n )\n module.reorder_incremental_state(\n incremental_state[1],\n new_order,\n )\n else:\n module.reorder_incremental_state(\n incremental_state,\n new_order,\n )\n self.apply(apply_reorder_incremental_state)\n\n\nclass TransformerProtoDecoderLayer(nn.Module):\n \"\"\"Decoder layer block.\"\"\"\n\n def __init__(self, args):\n super().__init__()\n self.embed_dim = args.decoder_embed_dim\n self.share_encoder_params = args.share_encoder_params\n\n self.self_attn = MultiheadAttention(\n self.embed_dim, args.decoder_attention_heads,\n dropout=args.attention_dropout,\n )\n self.dropout = args.dropout\n self.relu_dropout = args.relu_dropout\n self.normalize_before = args.decoder_normalize_before\n self.encoder_attn_1 = MultiheadAttention(\n self.embed_dim, args.decoder_attention_heads,\n dropout=args.attention_dropout,\n )\n self.encoder_attn_2 = MultiheadAttention(\n self.embed_dim, args.decoder_attention_heads,\n dropout=args.attention_dropout\n ) if not self.share_encoder_params else None\n self.fc1 = Linear(self.embed_dim, args.decoder_ffn_embed_dim)\n self.fc2 = Linear(args.decoder_ffn_embed_dim, self.embed_dim)\n self.layer_norms = nn.ModuleList([LayerNorm(self.embed_dim) for i in range(3)])\n\n def forward(self, x, encoder_out, encoder_padding_mask, incremental_state):\n incremental_state_2 = None\n if incremental_state is not None and self.share_encoder_params:\n incremental_state, incremental_state_2 = incremental_state\n\n residual = x\n x = self.maybe_layer_norm(0, x, before=True)\n x, _ = self.self_attn(\n query=x,\n key=x,\n value=x,\n mask_future_timesteps=True,\n incremental_state=incremental_state,\n need_weights=False,\n )\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = residual + x\n x = self.maybe_layer_norm(0, x, after=True)\n\n residual = x\n x = self.maybe_layer_norm(1, x, before=True)\n x1, attn1 = self.encoder_attn_1(\n query=x,\n key=encoder_out[0],\n value=encoder_out[0],\n key_padding_mask=encoder_padding_mask[0],\n incremental_state=incremental_state,\n static_kv=True,\n )\n x2, attn2 = self.encoder_attn_2(\n query=x,\n key=encoder_out[1],\n value=encoder_out[1],\n key_padding_mask=encoder_padding_mask[1],\n incremental_state=incremental_state,\n static_kv=True,\n ) if not self.share_encoder_params else self.encoder_attn_1(\n query=x,\n key=encoder_out[1],\n value=encoder_out[1],\n key_padding_mask=encoder_padding_mask[1],\n incremental_state=incremental_state_2,\n static_kv=True,\n )\n x = x1 + x2\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = residual + x\n x = self.maybe_layer_norm(1, x, after=True)\n\n residual = x\n x = self.maybe_layer_norm(2, x, before=True)\n x = F.relu(self.fc1(x))\n x = F.dropout(x, p=self.relu_dropout, training=self.training)\n x = self.fc2(x)\n x = F.dropout(x, p=self.dropout, training=self.training)\n x = residual + x\n x = self.maybe_layer_norm(2, x, after=True)\n return x, attn1\n\n def maybe_layer_norm(self, i, x, before=False, after=False):\n assert before ^ after\n if after ^ self.normalize_before:\n return self.layer_norms[i](x)\n else:\n return x\n\n\ndef Embedding(num_embeddings, embedding_dim, padding_idx):\n m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx)\n nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)\n return m\n\n\ndef LayerNorm(embedding_dim):\n m = nn.LayerNorm(embedding_dim)\n return m\n\n\ndef Linear(in_features, out_features, bias=True):\n m = nn.Linear(in_features, out_features, bias)\n nn.init.xavier_uniform_(m.weight)\n nn.init.constant_(m.bias, 0.)\n return m\n\n\ndef PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False):\n if learned:\n m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad)\n nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5)\n nn.init.constant_(m.weight[padding_idx], 0)\n else:\n m = SinusoidalPositionalEmbedding(embedding_dim, padding_idx, left_pad, num_embeddings)\n return m\n\n\n@register_model_architecture('transformer_soft_proto', 'transformer_soft_proto')\ndef base_architecture(args):\n args.encoder_embed_path = getattr(args, 'encoder_embed_path', None)\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048)\n args.encoder_layers = getattr(args, 'encoder_layers', 6)\n args.encoder2_layers = getattr(args, 'encoder2_layers', args.encoder_layers)\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8)\n args.decoder_embed_path = getattr(args, 'decoder_embed_path', None)\n args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim)\n args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim)\n args.decoder_layers = getattr(args, 'decoder_layers', 6)\n args.proto_layers = getattr(args, 'proto_layers', 'all')\n args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8)\n args.attention_dropout = getattr(args, 'attention_dropout', 0.)\n args.relu_dropout = getattr(args, 'relu_dropout', 0.)\n args.dropout = getattr(args, 'dropout', 0.1)\n args.encoder1_pos_emb = getattr(args, 'encoder1_pos_emb', \"timing\") # add positional embedding\n args.encoder2_pos_emb = getattr(args, 'encoder2_pos_emb', \"none\") # no positional embedding\n\n\n@register_model_architecture('transformer_soft_proto', 'transformer_soft_proto_base_v1')\ndef transformer_proto_base_v1(args):\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512)\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048)\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8)\n args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False)\n args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512)\n args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 2048)\n args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8)\n args.dropout = getattr(args, 'dropout', 0.1)\n base_architecture(args)\n\n\n@register_model_architecture('transformer_soft_proto', 'transformer_soft_proto_base_v2')\ndef transformer_proto_base_v2(args):\n args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True)\n args.encoder_normalize_before = getattr(args, 'decoder_normalize_before', True)\n args.attention_dropout = getattr(args, 'attention_dropout', 0.1)\n args.relu_dropout = getattr(args, 'relu_dropout', 0.1)\n transformer_proto_big_v1(args)\n\n\n# parameters used in the \"Attention Is All You Need\" paper (Vaswani, et al, 2017)\n@register_model_architecture('transformer_soft_proto', 'transformer_soft_proto_big_v1')\ndef transformer_proto_big_v1(args):\n args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024)\n args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4096)\n args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16)\n args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False)\n args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024)\n args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096)\n args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16)\n args.dropout = getattr(args, 'dropout', 0.3)\n base_architecture(args)\n\n\n# default parameters used in tensor2tensor implementation\n@register_model_architecture('transformer_soft_proto', 'transformer_soft_proto_big_v2')\ndef transformer_proto_big_v2(args):\n args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True)\n args.encoder_normalize_before = getattr(args, 'decoder_normalize_before', True)\n args.attention_dropout = getattr(args, 'attention_dropout', 0.1)\n args.relu_dropout = getattr(args, 'relu_dropout', 0.1)\n transformer_proto_big_v1(args)\n\n"
] |
[
[
"torch.nn.functional.dropout",
"torch.nn.init.constant_",
"torch.nn.ModuleList",
"torch.nn.Embedding",
"torch.nn.LayerNorm",
"torch.nn.Linear",
"torch.nn.init.normal_",
"torch.FloatTensor",
"torch.no_grad",
"torch.nn.init.xavier_uniform_",
"torch.nn.functional.linear"
]
] |
antonvs88/multiobj-guided-evac
|
[
"84d78ac29419011d7af45391f230f50e8cbe30f4",
"ece2e12204bd41596173af5aacc0933acfd6b7c1"
] |
[
"crowddynamics-simulation/complex_variance.py",
"crowddynamics/crowddynamics/core/motion/fluctuation.py"
] |
[
"import numpy as np\nfrom crowddynamics.core.geometry import geom_to_linear_obstacles\nfrom crowddynamics.simulation.agents import Circular, ThreeCircle, NO_TARGET, \\\n Agents, AgentGroup\nfrom crowddynamics.simulation.field import Field\nfrom crowddynamics.simulation.logic import Reset, InsideDomain, Integrator, \\\n Fluctuation, Adjusting, Navigation, ExitDetection, \\\n Orientation, AgentAgentInteractions, AgentObstacleInteractions, \\\n LeaderFollower, TargetReached\nfrom crowddynamics.simulation.multiagent import MultiAgentSimulation\nfrom shapely.geometry import Polygon, Point, LineString, MultiPolygon, MultiLineString, LinearRing\nfrom traitlets.traitlets import Enum, Int, default\n\nfrom shapely.ops import polygonize\nfrom scipy.spatial.qhull import Delaunay\nfrom crowddynamics.core.sampling import triangle_area_cumsum, random_sample_triangle\nfrom crowddynamics.core.vector2D import length\nfrom crowddynamics.core.distance import distance_circle_line, distance_circles\nfrom crowddynamics.simulation.agents import Agents, AgentGroup, Circular\n\n\nclass ComplexFloorField(Field):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n left_hall_width = 40\n left_hall_height = 5 #10\n\n right_hall_width = left_hall_width\n right_hall_height = left_hall_height\n\n upper_hall_width = 5 #10\n upper_hall_height = 40 # 40\n\n lower_hall_width = 5\n lower_hall_height = 40\n\n narrow_exit_width = 1.2\n broad_exit_width = 2.5\n\n spawn_left_width = 5 #10\n spawn_left_height = 5 #10\n spawn_left_separation = 15\n\n spawn_right_width = 5 #10\n spawn_right_height = 5 #10\n spawn_right_separation = 15\n\n spawn_upper_width = 5 #10\n spawn_upper_height = 5 #10\n spawn_upper_separation = 15\n\n spawn_lower_width = 5 #10\n spawn_lower_height = 5 #10\n spawn_lower_separation = 15\n\n # Buffer (so that spawned agents are not intersecting with obstacles)\n buffer = 0.27\n\n def f(value, scale=1):\n if value:\n return tuple(map(lambda x: scale * x, value))\n else:\n return None\n\n # Corner points of the domain counterclockwards\n crossing = list(map(f, [\n None,\n (0, lower_hall_height),\n (left_hall_width, lower_hall_height),\n (left_hall_width, 0),\n (left_hall_width + lower_hall_width, 0),\n (left_hall_width + lower_hall_width, lower_hall_height),\n (left_hall_width + lower_hall_width + right_hall_width, lower_hall_height),\n (left_hall_width + lower_hall_width + right_hall_width, lower_hall_height + right_hall_height),\n (left_hall_width + lower_hall_width, lower_hall_height + right_hall_height),\n (left_hall_width + lower_hall_width, lower_hall_height + right_hall_height + upper_hall_height),\n (left_hall_width, lower_hall_height + left_hall_height + upper_hall_height),\n (left_hall_width, lower_hall_height + left_hall_height),\n (0, lower_hall_height + left_hall_height),\n ]))\n\n # Exitpoints for both exits\n exitpoints = list(map(f, [\n None,\n (0, lower_hall_height + left_hall_height / 2 + narrow_exit_width / 2),\n (0, lower_hall_height + left_hall_height / 2 - narrow_exit_width / 2),\n (left_hall_width + lower_hall_width / 2 - narrow_exit_width / 2, 0),\n (left_hall_width + lower_hall_width / 2 + narrow_exit_width / 2, 0),\n (left_hall_width + lower_hall_width + right_hall_width, lower_hall_height + right_hall_height /2 - narrow_exit_width / 2),\n (left_hall_width + lower_hall_width + right_hall_width, lower_hall_height + right_hall_height /2 + narrow_exit_width / 2),\n (left_hall_width + lower_hall_width / 2 + narrow_exit_width / 2, lower_hall_height + right_hall_height + upper_hall_height),\n (left_hall_width + lower_hall_width / 2 - narrow_exit_width / 2, lower_hall_height + right_hall_height + upper_hall_height),\n ]))\n\n # Spawn left area corner points\n spawn_left_points = list(map(f, [\n None,\n (spawn_left_separation + buffer, lower_hall_height + buffer),\n (spawn_left_separation + spawn_left_width - buffer, lower_hall_height + buffer),\n (spawn_left_separation + spawn_left_width - buffer, lower_hall_height + spawn_left_height - buffer),\n (spawn_left_separation + buffer, lower_hall_height + spawn_left_height - buffer),\n ]))\n\n # Spawn right area corner points\n spawn_right_points = list(map(f, [\n None,\n (left_hall_width + lower_hall_width + right_hall_width - spawn_right_separation - spawn_right_width + buffer, lower_hall_height + buffer),\n (left_hall_width + lower_hall_width + right_hall_width - spawn_right_separation - buffer, lower_hall_height + buffer),\n (left_hall_width + lower_hall_width + right_hall_width - spawn_right_separation - buffer, lower_hall_height + right_hall_height - buffer),\n (left_hall_width + lower_hall_width + right_hall_width - spawn_right_separation - spawn_right_width + buffer, lower_hall_height + right_hall_height - buffer),\n ]))\n\n # Spawn upper area corner points\n spawn_upper_points = list(map(f, [\n None,\n (left_hall_width + buffer, lower_hall_height + left_hall_height + upper_hall_height - spawn_upper_separation - buffer),\n (left_hall_width + buffer, lower_hall_height + left_hall_height + upper_hall_height - spawn_upper_separation - spawn_upper_height + buffer),\n (left_hall_width + upper_hall_width - buffer, lower_hall_height + left_hall_height + upper_hall_height - spawn_upper_separation - spawn_upper_height + buffer),\n (left_hall_width + upper_hall_width - buffer, lower_hall_height + left_hall_height + upper_hall_height - spawn_upper_separation - buffer),\n ]))\n\n # Spawn lower area corner points\n spawn_lower_points = list(map(f, [\n None,\n (left_hall_width + buffer, spawn_lower_separation + spawn_lower_height - buffer),\n (left_hall_width + buffer, spawn_lower_separation + buffer),\n (left_hall_width + lower_hall_width - buffer, spawn_lower_separation + buffer),\n (left_hall_width + lower_hall_width - buffer, spawn_lower_separation + spawn_lower_height - buffer),\n ]))\n\n # Obstacles counterclockwards\n obstacles = Polygon()\n\n obstacles |= LineString(\n [exitpoints[2]] + [crossing[1]] + [crossing[2]] + [crossing[3]] + [exitpoints[3]]\n )\n obstacles |= LineString(\n [exitpoints[4]] + [crossing[4]] + [crossing[5]] + [crossing[6]] + [exitpoints[5]]\n )\n obstacles |= LineString(\n [exitpoints[6]] + [crossing[7]] + [crossing[8]] + [crossing[9]] + [exitpoints[7]]\n )\n obstacles |= LineString(\n [exitpoints[8]] + [crossing[10]] + [crossing[11]] + [crossing[12]] + [exitpoints[1]]\n )\n\n floorplan = Polygon([\n crossing[1], crossing[2], crossing[3], crossing[4], crossing[5], crossing[6], crossing[7], crossing[8], crossing[9], crossing[10], crossing[11], crossing[12]]\n )\n\n # Exits from the upper right piece counterclockwards\n exit1 = LineString([exitpoints[1], exitpoints[2]])\n exit2 = LineString([exitpoints[3], exitpoints[4]])\n exit3 = LineString([exitpoints[5], exitpoints[6]])\n exit4 = LineString([exitpoints[7], exitpoints[8]])\n\n # Spawn areas from the upper left piece counterclockwards\n spawn_left = Polygon([\n spawn_left_points[1], spawn_left_points[2], spawn_left_points[3], spawn_left_points[4]]\n )\n spawn_lower = Polygon([\n spawn_lower_points[1], spawn_lower_points[2], spawn_lower_points[3], spawn_lower_points[4]]\n )\n spawn_right = Polygon([\n spawn_right_points[1], spawn_right_points[2], spawn_right_points[3], spawn_right_points[4]]\n )\n spawn_upper = Polygon([\n spawn_upper_points[1], spawn_upper_points[2], spawn_upper_points[3], spawn_upper_points[4]]\n )\n\n # Spawns\n spawns = [\n spawn_left,\n spawn_lower,\n spawn_right,\n spawn_upper\n ]\n\n targets = [exit1, exit2, exit3, exit4]\n\n self.obstacles = obstacles # obstacles\n self.targets = targets\n self.spawns = spawns\n self.domain = floorplan\n\n\nclass ComplexFloor(MultiAgentSimulation):\n # def __init__(self, kokeilu):\n # self.kokeilu = kokeilu\n\n size_spawn_left = Int(\n default_value=50, min=0, max=200, help='')\n size_spawn_lower = Int(\n default_value=50, min=0, max=200, help='')\n size_spawn_right = Int(\n default_value=50, min=0, max=200, help='')\n size_spawn_upper = Int(\n default_value=50, min=0, max=200, help='')\n size_leader = Int(\n default_value=0, min=0, max=6, help='')\n\n agent_type = Enum(\n default_value=Circular,\n values=(Circular, ThreeCircle))\n body_type = Enum(\n default_value='adult',\n values=('adult',))\n\n # CHECK THE GUIDE GENERATOR FUNCTION\n # A helper function to create spawn points for leaders out of their cell coordinates.\n # The input is the array of leader spawn cells and the number of leaders in the simulation.\n # def generate_leader_pos(cell, n_lead, seed_number):\n def generate_leader_pos(self, cell, n_lead):\n\n # FIRST THE DATA HAS TO BE CREATED\n # Load data of followers\n followers = np.load('complex/spawn_complex.npy')\n follower_positions = followers['position']\n follower_radii = followers['radius']\n\n # Minimal radius of a guide (the same value given in agents.py to the guides).\n max_r = 0.27\n\n # Number of times spawned leaders are allowed to overlap each other before the program is\n # terminated.\n overlaps = 10000\n\n # Import Complex floor field\n field = ComplexFloor().field\n\n # Bound box representing the room.\n width = 90\n height = 90\n\n # Create a grid structure over the room geometry.\n # Cell size in the grid, determines the resolution of the micro-macro converted data\n cell_size = 2\n m = np.round(width / cell_size)\n n = np.round(height / cell_size)\n m = m.astype(int)\n n = n.astype(int)\n X = np.linspace(0, width, m + 1)\n Y = np.linspace(0, height, n + 1)\n hlines = [((x1, yi), (x2, yi)) for x1, x2 in zip(X[:-1], X[1:]) for yi in Y]\n vlines = [((xi, y1), (xi, y2)) for y1, y2 in zip(Y[:-1], Y[1:]) for xi in X]\n grids = list(polygonize(MultiLineString(hlines + vlines)))\n\n # Leaders' spawn areas\n leader_spawns = []\n\n # Leader's spawn points\n spawn_points = []\n\n # Loop through the cells and calculate intersections with spawn areas.\n for i in range(n_lead):\n\n poly = field.domain.intersection(grids[cell[i]])\n if not poly.is_empty:\n leader_spawns.append(poly)\n\n # Import obstacles\n obstacles = field.obstacles\n\n # Spawn a random position from the starting area.\n # Loop through all the leaders.\n # (1) Take into account that there might be obstacles in the spawn areas, and take also\n # into account that agents have a buffer radius.\n # (2) If the spawn area is a MultiPolygon, loop through the polygons in a MultiPolygon. Create a\n # mesh grid of the spawn area with Delaunay triangulation.\n # (2.1) Spawn a random point from the mesh grid.\n # (2.2) Check that the position doesn't interfere with other agents' positions\n # (2.3) Set the Boolean value for if the leader is initially inside the Finlandiahall\n # (this is needed for the movement simulation).\n # (3) If the spawn area is not a MultiPolygon, just directly create a mesh grid of the spawn area\n # with Delaunay triangulation.\n # (3.1) Spawn a random point from the mesh grid.\n # (3.2) Check that the position doesn't interfere with other agents' positions\n # (3.3) Set the Boolean value for if the leader is initially inside the Finlandiahall (this is\n # is needed for the movement simulation).\n for i in range(n_lead):\n seed = 0\n # (1)\n n_spawnpoints = len(spawn_points)\n geom = leader_spawns[i] - obstacles.buffer(max_r)\n j = 0 # set overlaps counter to zero\n # (2)\n if isinstance(geom, MultiPolygon):\n n_polygons = len(geom)\n for j in range(n_polygons):\n vertices = np.asarray(geom[j].convex_hull.exterior)\n delaunay = Delaunay(vertices)\n mesh = vertices[delaunay.simplices]\n if j == 0:\n meshes = mesh\n else:\n meshes = np.concatenate((mesh, meshes), axis=0)\n # Computes cumulative sum of the areas of the triangle mesh.\n weights = triangle_area_cumsum(meshes)\n weights /= weights[-1]\n\n while j < overlaps:\n seed += 1\n distances = [] # temporarily store distances from the spawned point to the previously spawned\n n_overlaps = 0 # for each attempt to position the guide, set number of overlaps to zero\n # (2.1) Spawn a random point for the guide.\n np.random.seed(seed)\n x = np.random.random()\n k = np.searchsorted(weights, x)\n a, b, c = meshes[k]\n spawn_point = random_sample_triangle(a, b, c)\n # spawn_point = random_sample_triangle(a, b, c, seed)\n # (2.2)\n if n_spawnpoints != 0: # if there are no other spawned guides skip this step\n for k in range(0, n_spawnpoints):\n d = length(spawn_point - spawn_points[k])\n h = d - 2 * max_r\n distances.append(h)\n distances_array = distances\n distances_array = np.asarray(distances_array)\n n_overlaps += len(np.where(distances_array < 0)[0])\n for obstacle in obstacles:\n obstacle = list(obstacle.coords)\n n_obstacle_points = len(obstacle)\n for k in range(0, n_obstacle_points):\n if k == n_obstacle_points - 1:\n h, _ = distance_circle_line(spawn_point, max_r, np.asarray(obstacle[k]),\n np.asarray(obstacle[0]))\n else:\n h, _ = distance_circle_line(spawn_point, max_r, np.asarray(obstacle[k]),\n np.asarray(obstacle[k + 1]))\n if h < 0.0:\n n_overlaps += 1\n for agent in range(len(follower_radii)):\n h, _ = distance_circles(follower_positions[agent], follower_radii[agent], spawn_point, max_r)\n if h < 0.0:\n n_overlaps += 1\n\n if n_overlaps == 0:\n # (2.3)\n # Append the point to spawn points\n spawn_points.append([spawn_point[0], spawn_point[1]])\n # print(\"Guide spawned\")\n # sys.stdout.flush()\n break\n j += 1\n if j == overlaps:\n raise Exception('Leaders do not fit in the cell')\n # (3)\n else:\n vertices = np.asarray(geom.convex_hull.exterior)\n delaunay = Delaunay(vertices)\n mesh = vertices[delaunay.simplices]\n weights = triangle_area_cumsum(mesh)\n weights /= weights[-1]\n\n while j < overlaps:\n seed += 1\n distances = [] # temporarily store distances from the spawned point to the previously spawned\n n_overlaps = 0 # for each attempt to position the guide, set number of overlaps to zero\n # (3.1) Spawn a random point for the guide\n np.random.seed(seed)\n x = np.random.random()\n k = np.searchsorted(weights, x)\n a, b, c = mesh[k]\n spawn_point = random_sample_triangle(a, b, c)\n # spawn_point = random_sample_triangle(a, b, c, seed)\n if n_spawnpoints != 0:\n for k in range(0, n_spawnpoints):\n d = length(spawn_point - spawn_points[k])\n h = d - 2 * max_r\n distances.append(h)\n distances_array = distances\n distances_array = np.asarray(distances_array)\n n_overlaps += len(np.where(distances_array < 0)[0])\n for obstacle in obstacles:\n obstacle = list(obstacle.coords)\n n_obstacle_points = len(obstacle)\n for k in range(0, n_obstacle_points):\n if k == n_obstacle_points - 1:\n h, _ = distance_circle_line(spawn_point, max_r, np.asarray(obstacle[k]),\n np.asarray(obstacle[0]))\n else:\n h, _ = distance_circle_line(spawn_point, max_r, np.asarray(obstacle[k]),\n np.asarray(obstacle[k + 1]))\n if h < 0.0:\n n_overlaps += 1\n for agent in range(len(follower_radii)):\n h, _ = distance_circles(follower_positions[agent], follower_radii[agent], spawn_point, max_r)\n if h < 0.0:\n n_overlaps += 1\n\n if n_overlaps == 0:\n # (3.3)\n # Append the point to spawn points\n spawn_points.append([spawn_point[0], spawn_point[1]])\n # print(\"Guide spawned\")\n # sys.stdout.flush()\n break\n j += 1\n if j == overlaps:\n raise Exception('Leaders do not fit in the cell')\n return spawn_points\n\n # CHECK ATTRIBUTES\n def attributes(self, familiar, has_target: bool = True, is_follower: bool = True):\n def wrapper():\n target = familiar if has_target else NO_TARGET\n orientation = np.random.uniform(-np.pi, np.pi)\n d = dict(\n target=target,\n is_leader=not is_follower,\n is_follower=is_follower,\n body_type=self.body_type,\n orientation=orientation,\n velocity=np.zeros(2),\n angular_velocity=0.0,\n target_direction=np.zeros(2),\n target_orientation=orientation,\n familiar_exit=familiar,\n )\n return d\n\n return wrapper\n\n def attributes_leader(self, target_iter, has_target: bool = True, is_follower: bool = False):\n def wrapper():\n target = next(target_iter)\n orientation = np.random.uniform(-np.pi, np.pi)\n d = dict(\n target=target,\n is_leader=not is_follower,\n is_follower=is_follower,\n body_type=self.body_type,\n orientation=orientation,\n velocity=np.zeros(2),\n angular_velocity=0.0,\n target_direction=np.zeros(2),\n target_orientation=orientation,\n familiar_exit=4,\n )\n return d\n\n return wrapper\n\n @default('logic')\n def _default_logic(self):\n return Reset(self) << \\\n TargetReached(self) << (\n Integrator(self) << (\n #Fluctuation(self),\n Adjusting(self) << (\n Navigation(self) << LeaderFollower(self),\n Orientation(self)),\n AgentAgentInteractions(self),\n AgentObstacleInteractions(self)))\n\n @default('field')\n def _default_field(self):\n return ComplexFloorField()\n\n @default('agents')\n def _default_agents(self):\n agents = Agents(agent_type=self.agent_type)\n\n # Generate iterators for group of leaders.\n #target_exits = [0,1,0]\n #cells = [913,695,652]\n target_exits = []\n cells = []\n n_guides = len(target_exits)\n\n speed_left = \"fast\"\n speed_lower = \"fast\"\n speed_right = \"fast\"\n speed_upper = \"fast\"\n\n # Exiting agents in left spawn\n group_follower_spawn_left = AgentGroup(\n agent_type=self.agent_type,\n size=getattr(self, 'size_spawn_left'),\n attributes=self.attributes(familiar=2, has_target=True, is_follower=True))\n\n agents.add_non_overlapping_group(\n speed_left,\n \"spawn_left\",\n group_follower_spawn_left,\n position_gen=False,\n position_iter=iter([]),\n spawn=0,\n obstacles=geom_to_linear_obstacles(self.field.obstacles))\n\n # Exiting agents in lower spawn\n group_follower_spawn_lower = AgentGroup(\n agent_type=self.agent_type,\n size=getattr(self, 'size_spawn_lower'),\n attributes=self.attributes(familiar=3, has_target=True, is_follower=True))\n\n agents.add_non_overlapping_group(\n speed_lower,\n \"spawn_lower\",\n group_follower_spawn_lower,\n position_gen=False,\n position_iter=iter([]),\n spawn=0,\n obstacles=geom_to_linear_obstacles(self.field.obstacles))\n\n # Exiting agents in right spawn\n group_follower_spawn_right = AgentGroup(\n agent_type=self.agent_type,\n size=getattr(self, 'size_spawn_right'),\n attributes=self.attributes(familiar=0, has_target=True, is_follower=True))\n\n agents.add_non_overlapping_group(\n speed_right,\n \"spawn_right\",\n group_follower_spawn_right,\n position_gen=False,\n position_iter=iter([]),\n spawn=2,\n obstacles=geom_to_linear_obstacles(self.field.obstacles))\n\n # Exiting agents in upper spawn\n group_follower_spawn_upper = AgentGroup(\n agent_type=self.agent_type,\n size=getattr(self, 'size_spawn_upper'),\n attributes=self.attributes(familiar=1, has_target=True, is_follower=True))\n\n agents.add_non_overlapping_group(\n speed_upper,\n \"spawn_upper\",\n group_follower_spawn_upper,\n position_gen=False,\n position_iter=iter([]),\n spawn=3,\n obstacles=geom_to_linear_obstacles(self.field.obstacles))\n\n if n_guides != 0:\n init_pos = self.generate_leader_pos(cells, n_guides)\n print(init_pos)\n # init_pos = [[8, 6]]\n target_exits = iter(target_exits)\n init_pos = iter(init_pos)\n\n # Guides in Variance Dilemma\n group_leader = AgentGroup(\n agent_type=self.agent_type,\n size=n_guides,\n attributes=self.attributes_leader(target_iter=target_exits, has_target=True, is_follower=False))\n\n agents.add_non_overlapping_group(\n \"group_leader\",\n group_leader,\n position_gen=True,\n position_iter=init_pos,\n spawn=0,\n obstacles=geom_to_linear_obstacles(self.field.obstacles))\n\n return agents\n",
"r\"\"\"\nFluctuation\n-----------\nFluctuation force and torque are stochastic in nature and analogous to heat in\nparticle systems. For modeling fluctuation we use :math:`\\mathcal{U}(a, b)` for\ncontinuous uniform distribution and :math:`\\mathcal{N}(\\mu, \\sigma^{2})` for\ntruncated normal distribution.\n\"\"\"\nimport numpy as np\n\nfrom crowddynamics.core.rand import truncnorm\n\n\ndef force_fluctuation(mass, scale):\n r\"\"\"\n Truncated normal distribution with standard deviation of 3.\n\n .. math::\n \\boldsymbol{\\xi} = \\xi \\cdot \\mathbf{\\hat{e}}(\\varphi)\n\n where\n\n - :math:`\\xi \\sim \\mathcal{N}(\\mu, \\sigma^{2})`\n - :math:`\\varphi \\sim \\mathcal{U}(-\\pi, \\pi)`\n - :math:`\\mathbf{\\hat{e}}(\\varphi)` is unit vector to direction of\n :math:`\\varphi`.\n\n Args:\n mass (numpy.ndarray):\n Mass\n\n scale (numpy.ndarray):\n Standard deviation of truncated normal distribution\n\n Returns:\n numpy.ndarray: Fluctuation force vector\n \"\"\"\n size = len(mass)\n phi = np.random.uniform(0.0, 2.0 * np.pi, size=size)\n unit_vector = np.array((np.cos(phi), np.sin(phi)))\n magnitude = truncnorm(0.0, 3.0, loc=0.0, scale=scale, size=size)\n return (mass * magnitude * unit_vector).T\n\n\ndef torque_fluctuation(inertia_rot, scale):\n r\"\"\"Random torque\n\n .. math::\n \\eta \\sim \\mathcal{N}(\\mu, \\sigma^{2})\n\n Args:\n inertia_rot (numpy.ndarray):\n Rotational intertial\n\n scale (numpy.ndarray):\n Standard deviation of truncated normal distribution\n\n Returns:\n numpy.ndarray: Fluctuation torque scalar\n \"\"\"\n size = len(inertia_rot)\n return inertia_rot * truncnorm(-3.0, 3.0, loc=0.0, scale=scale, size=size)\n"
] |
[
[
"scipy.spatial.qhull.Delaunay",
"numpy.random.random",
"numpy.linspace",
"numpy.random.seed",
"numpy.asarray",
"numpy.round",
"numpy.random.uniform",
"numpy.concatenate",
"numpy.searchsorted",
"numpy.load",
"numpy.zeros",
"numpy.where"
],
[
"numpy.random.uniform",
"numpy.cos",
"numpy.sin"
]
] |
miramirakim227/SwapNeRF
|
[
"f9eba3ad054af30bc138c5460ef363165280c5e0"
] |
[
"im2scene/training.py"
] |
[
"from collections import defaultdict\nfrom torch import autograd\nimport torch.nn.functional as F\nimport numpy as np\n\n\nclass BaseTrainer(object):\n ''' Base trainer class.\n '''\n\n def evaluate(self, data, *args, **kwargs):\n ''' Performs an evaluation.\n '''\n eval_list = defaultdict(list)\n\n # for data in tqdm(val_loader):\n eval_step_dict = self.eval_step()\n\n for k, v in eval_step_dict.items():\n eval_list[k].append(v)\n # eval_dict = {k: v for k, v in eval_list.items()}\n eval_dict = {k: np.mean(v) for k, v in eval_list.items()}\n return eval_dict\n\n def train_step(self, *args, **kwargs):\n ''' Performs a training step.\n '''\n raise NotImplementedError\n\n def eval_step(self, *args, **kwargs):\n ''' Performs an evaluation step.\n '''\n raise NotImplementedError\n\n def visualize(self, *args, **kwargs):\n ''' Performs visualization.\n '''\n raise NotImplementedError\n\n\ndef toggle_grad(model, requires_grad):\n for p in model.parameters():\n p.requires_grad_(requires_grad)\n\n\ndef compute_grad2(d_out, x_in):\n batch_size = x_in.size(0)\n grad_dout = autograd.grad(\n outputs=d_out.sum(), inputs=x_in,\n create_graph=True, retain_graph=True, only_inputs=True\n )[0]\n grad_dout2 = grad_dout.pow(2)\n assert(grad_dout2.size() == x_in.size())\n reg = grad_dout2.reshape(batch_size, -1).sum(1)\n return reg\n\n\ndef update_average(model_tgt, model_src, beta):\n toggle_grad(model_src, False)\n toggle_grad(model_tgt, False)\n\n param_dict_src = dict(model_src.named_parameters())\n\n for p_name, p_tgt in model_tgt.named_parameters():\n p_src = param_dict_src[p_name]\n assert(p_src is not p_tgt)\n p_tgt.copy_(beta*p_tgt + (1. - beta)*p_src)\n\n\ndef compute_bce(d_out, target):\n targets = d_out.new_full(size=d_out.size(), fill_value=target)\n loss = F.binary_cross_entropy_with_logits(d_out, targets)\n return loss\n\n\n"
] |
[
[
"torch.nn.functional.binary_cross_entropy_with_logits",
"numpy.mean"
]
] |
Jordy24/spacetech-kubesat
|
[
"e64372cc4cf71d9db7fe2395ba60d93722fccff6"
] |
[
"kubesat/orekit.py"
] |
[
"# Copyright 2020 IBM Corporation\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"\nOreKit Utilities File\nWrapped Orekit Functions for Easy Use of Orbital Simulations\nFunction Summaries:\nstring_to_frame: allows creation of orekit frame objects from\n\t\t\t\t\t\t\t\t set amount of strings\nframe_to_string: converts orekit frame object to string that\n\t\t\t\t\t\t\t\t works with string_to_frame function\nt1_lte_t2_string: boolean comparison (time1 <= time2), time in ISO 8601 format\nt1_gte_t2_string: boolean comparison (time1 >= time2), time in ISO 8601 format\nabsolute_time_converter_utc_manual: turn time inputs into orekit absolute time object\nabsolute_time_converter_utc_string: turn ISO 8601 string inputs into orekit absolute time object\nconvert_tle_string_to_TLE: convert two tle line strings into orekit TLE object\nTODO update references (prop1, prop2)\nfind_sat_distance: distance between two propagators's at a given time\nsetup_orekit_zip_file: sets up orekit with orekit-data.zip file (allows specification of zip file location)\nkeplerian_orbit: creates a keplerian orbit orekit object\nvisible_above_horizon: returns whether a satellite is above the planet limb (horizon)\n\t\t\t\t\t\t\t\t as viewed from another satellite in orbit at the specified time period\nget_keplerian_parameters: returns keplarian orbit parameters from orekit spacecraft state object\n\n\nstr_tle_propagator: turns TLE string into orekit TLE propogator object\nanalytical_propagator: returns EcksteinHechlerPropagator for a orekit orbit object\nmoving_body_pointing_law: helper function for attitude_provider_constructor for pointing\n at a moving object that can be defined with a propagator\n\nground_pointing_law: helper function for attitude_provider_constructor for pointing\n at an object on or very near earth's surface\n\nnadir_pointing_law: helper function for attitude_provider_constructor for pointing\n\t\t\t\t\t\t\t\t at the nadir point (ground point directly below satellite)\nattitude_provider_constructor: with dictionary of inputs can return an altitude provider that\n\t\t\t\t\t\t\t\t can be attached to a spacecraft object to define its pointing law\nget_ground_passes: provides times where satellite is visible overhead a certain point\n\t\t\t\t\t\t\t\t on the earth (very useful for ground stations and IoT sensors)\n\ncheck_iot_in_range: very similar to get_ground_passes, but returns bool value for one\n time input\n\"\"\"\nimport queue\nimport os\nimport queue\nfrom enum import Enum\nimport numpy as np\nfrom math import radians, pi, degrees\n\nimport orekit\nfrom org.hipparchus.geometry.euclidean.threed import Vector3D\nfrom orekit.pyhelpers import setup_orekit_curdir\nfrom org.orekit.frames import FramesFactory, TopocentricFrame\nfrom org.orekit.bodies import OneAxisEllipsoid, GeodeticPoint, CelestialBodyFactory\nfrom org.orekit.time import TimeScalesFactory, AbsoluteDate, DateComponents, TimeComponents\nfrom org.orekit.utils import IERSConventions, Constants, ElevationMask\nfrom org.orekit.propagation.analytical.tle import TLE, TLEPropagator\nfrom org.orekit.data import DataProvidersManager, ZipJarCrawler\nfrom org.orekit.orbits import KeplerianOrbit, PositionAngle\nfrom org.orekit.attitudes import CelestialBodyPointed, TargetPointing, NadirPointing\nfrom org.orekit.propagation import SpacecraftState\nfrom org.orekit.propagation.analytical import EcksteinHechlerPropagator, KeplerianPropagator\nfrom org.orekit.propagation.events import EclipseDetector, EventsLogger, ElevationDetector, InterSatDirectViewDetector, FieldOfViewDetector\nfrom org.orekit.propagation.events.handlers import ContinueOnEvent\nfrom org.orekit.utils import IERSConventions\nfrom org.orekit.propagation import SpacecraftState\nfrom org.orekit.geometry.fov import CircularFieldOfView\n\nfrom java.io import File\n\nvm = orekit.initVM()\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\nclass utils(str, Enum):\n\t\"\"\"\n\tTODO: CLEAN UP....Enumeration for constants used in \n\t\"\"\"\n\tITRF = \"ITRF\"\n\tEME = \"EME\"\n\tTEME = \"TEME\"\n\tTOPOCENTRIC = \"Topocentric\"\n\tMOVING_BODY_TRACKING = \"moving_body_tracking\"\n\tGROUND_TRACKING = \"ground_tracking\"\n\tNADIR_TRACKING = \"nadir_tracking\"\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef field_of_view_detector(sat_propagator, latitude, longitude, altitude, start_time, degree_fov, duration=0, stepsize=1):\n \"\"\"\n Determines if a ground point will be within the field of view (defined as a\n circular feild of view of however many degrees from the sat) for a specific\n sat_propagator that should include an integrated attitude provider.\n Args:\n sat_propagator: orekit propagator object that should include at the least\n an internal orbit and attitude law (this law should either\n be ground pointing or nadir pointing)\n latitude, longitude, altitude: (floats in degrees and meters) coordinate point\n to be checked if within feild of view of camera\n start_time: orekit absolute time object (start time of checking)\n degree_fov: (float in degrees) the full degree field of view of the camera/instrument\n duration: (int in seconds) duration to check after start time, if not inputed\n will default to zero, and function will return a boolean for the\n state at only the start time\n stepsize: (int >= 1) size in seconds between each prediction (smallest step is 1 second)\n Returns:\n duration=0:\n bool value that tells if the ground point is in the feild of view at the\n start time\n else:\n array of structure [[time_start, end_time], ... ,[start_end, end_time]] that\n contains the entry/exit times of the feild of view prediction.\n \"\"\"\n earth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,\n Constants.WGS84_EARTH_FLATTENING,\n FramesFactory.getITRF(IERSConventions.IERS_2010, True))\n ground_target = GeodeticPoint(radians(float(latitude)),radians(float(longitude)), float(altitude))\n ground_target_frame = TopocentricFrame(earth, ground_target, \"ground_target\")\n circular_fov = CircularFieldOfView(Vector3D.PLUS_K, radians(float(degree_fov/2)),radians(0.))\n fov_detector = FieldOfViewDetector(ground_target_frame, circular_fov).withHandler(ContinueOnEvent())\n elevation_detector = ElevationDetector(ground_target_frame).withConstantElevation(0.0).withHandler(ContinueOnEvent())\n\n if (duration <= 0):\n return ((fov_detector.g(sat_propagator.propagate(start_time))<0) and (elevation_detector.g(sat_propagator.propagate(start_time))>0))\n\n time_within_fov = []\n time_array = [start_time.shiftedBy(float(time)) for time in np.arange(0, duration, stepsize)]\n entry_empty = True\n entry_time = 0\n for time in time_array:\n within_fov = ((fov_detector.g(sat_propagator.propagate(time))<0) and (elevation_detector.g(sat_propagator.propagate(time))>0))\n if (entry_empty and within_fov):\n entry_time = time\n entry_empty = False\n elif ((not entry_empty) and (not within_fov)):\n time_within_fov.append([entry_time,time])\n entry_empty = True\n entry_time = 0\n elif ((not entry_empty) and (time == time_array[-1])):\n time_within_fov.append([entry_time,time])\n\n return time_within_fov\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef string_to_frame(frame_name, latitude=0., longitude=0., altitude=0., name=\"\"):\n\t\"\"\"\n\tGiven a string with the following defined options below, the fucntion returns the orekit\n\tassociated frame object.\n\tArgs:\n\t\tframe_name: (string) with the following options...\n\t\t\t\t\t\"ITRF\" ... returns the ITRF (geocentric and rotates with earth for use\n\t\t\t\t\t\t\t\tfor points near or on earth's surface--very accurate)\n\t\t\t\t\t\"EME2000\"/\"J2000\" ... Earth Centered Inertial (ECI) Frame\n\t\t\t\t\t\t\t\t the frame is fixed to the celetial grid and doesn't rotate\n\t\t\t\t\t\t\t\t with the earth\n\t\t\t\t\t\"TEME\" ... another ECI frame, but specifically used by NORAD TLEs\n\t\t\t\t\t\"Topocentric\" ... very specific frame defined at an coordinate on or near\n\t\t\t\t\t\t\t\t\t the surface of an object (here we define earth). Rotates\n\t\t\t\t\t\t\t\t\t with body defined by ITRF frame (can think as an offset\n\t\t\t\t\t\t\t\t\t of ITRF frame for things like ground stations)\n\t\tlatitude, longitude: (float in degrees) for defining the topocentric frame origin--not\n\t\t\t\t\t\t\t required otherwise\n\t\taltitude: (float in meters) for defining the topocentric frame origin--not required otherwise\n\t\tname: (string) for defining the topocentric frame origin label--not required otherwise\n\tReturns:\n\t\torekit frame object OR -1 if undefined string\n\t\"\"\"\n\tif (frame_name == utils.ITRF):\n\t\treturn FramesFactory.getITRF(IERSConventions.IERS_2010, True)\n\telif ((frame_name == utils.EME) or (frame_name == \"J2000\")):\n\t\treturn FramesFactory.getEME2000()\n\telif (frame_name == utils.TEME):\n\t\treturn FramesFactory.getTEME()\n\telif (frame_name == utils.TOPOCENTRIC):\n\t\tearth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,\n\t\t\t\t\t\tConstants.WGS84_EARTH_FLATTENING,\n\t\t\t\t\t\tFramesFactory.getITRF(IERSConventions.IERS_2010, True))\n\t\tlocation = GeodeticPoint(radians(latitude), radians(longitude), float(altitude))\n\t\treturn TopocentricFrame(earth, location, name)\n\telse:\n\t\treturn -1\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef frame_to_string(frame):\n\t\"\"\"\n\tGiven a orekit frame object with the following defined options below, the fucntion returns the orekit\n\tassociated frame string.\n\tArgs:\n\t\tframe: (Frame) with the following options...\n\t\t\t\t\tITRF (geocentric and rotates with earth for use\n\t\t\t\t\t\tfor points near or on earth's surface--very accurate)\n\t\t\t\t\tEarth Centered Inertial (ECI) Frame\n\t\t\t\t\t\tthe frame is fixed to the celetial grid and doesn't rotate\n\t\t\t\t\t\twith the earth\n\t\t\t\t\tECI frame, but specifically used by NORAD TLEs\n\t\t\t\t\tvery specific frame defined at an coordinate on or near\n\t\t\t\t\t\t\t\t\t the surface of an object (here we define earth). Rotates\n\t\t\t\t\t\t\t\t\t with body defined by ITRF frame (can think as an offset\n\t\t\t\t\t\t\t\t\t of ITRF frame for things like ground stations)\n\tReturns:\n\t\tstring OR -1 if undefined Frame\n\t\"\"\"\n\tif frame == FramesFactory.getITRF(IERSConventions.IERS_2010, True):\n\t\treturn utils.ITRF\n\telif frame == FramesFactory.getEME2000():\n\t\treturn utils.EME\n\telif frame== FramesFactory.getTEME():\n\t\treturn utils.TEME\n\telse:\n\t\treturn -1\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef visible_above_horizon(propagator_main_sat, propagator_tracked_sat, start_time, duration=0, stepsize=1, return_queue=False):\n\t\"\"\"\n\tBased on two propagators, determines if the main_sat can \"see\" another tracked_sat determinant on\n\tif the tracked_sat is above the planet limb (horizon) from the perspective of the main_sat, see\n\tdifferent return options below.\n\tArgs:\n\t\tpropagator_main_sat, propagator_tracked_sat: any type of analytical propagator (ex. TLEPropagator)\n\t\tstart_time: Orekit absolute time object (start time of tracking)\n\t\tduration: (int) seconds, how long Orekit will predict if visible. IF ZERO: ignores and\n\t\t\t\t returns boolean cooresponding to start time\n\t\tstepsize: (int >= 1) size in seconds between each prediction (smallest step is 1 second)\n\t\treturn_queue: (boolean) if True, changes return type to queue of durations since start time\n\t\t\t\t\t that includes {start time, end time, start time, ...} as queue (for mapping)\n\tReturns: (Dependent on inputs...)\n\t\tbool: booleen value if duration is not entered, kept zero, or negative (this corresponds to if\n\t\tthe tracked sat is visible at the start time)\n\t\ttime_IsVisible: array of structure [[time_start, end_time], ... ,[start_end, end_time]] that\n\t\t\t\t\t\tcontains the entry/exit times of the above horizon prediction.\n\t\t\t\t\t\tor\n\t\t\t\t\t\tif return_queue = True, then returns a queue of duration since start_time for\n\t\t\t\t\t\tthese dates (for mapping function)\n\t\"\"\"\n\t#setup detector\n\tITRF = FramesFactory.getITRF(IERSConventions.IERS_2010, True)\n\tearth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,\n\t\t\t\t\t\t Constants.WGS84_EARTH_FLATTENING,\n\t\t\t\t\t\t ITRF)\n\tdetector = InterSatDirectViewDetector(earth,propagator_tracked_sat).withHandler(ContinueOnEvent())\n\t#propogate for duration and create array of [time-stamp, bool] that tells if tracked_sat is visible to main_sat\n\tif (return_queue==True):\n\t\ttime_IsVisible = queue.Queue(0)\n\telif (duration > 0):\n\t\ttime_IsVisible = []\n\telse:\n\t\treturn(detector.g(propagator_main_sat.propagate(start_time)) > 0)\n\ttime_array = [start_time.shiftedBy(float(time)) for time in np.arange(0, duration, stepsize)]\n\tentry_time = 0\n\texit_time = 0\n\tfor time in time_array:\n\t\tdetector_value = detector.g(propagator_main_sat.propagate(time))\n\t\t#g here is the function that returns positive values if visible and negative if not visible\n\t\tif ((entry_time == 0) and (detector_value > 0)):\n\t\t\tentry_time = time\n\t\telif ((entry_time != 0) and (detector_value <= 0) and (exit_time == 0)):\n\t\t\texit_time = time\n\t\telif ((entry_time != 0) and (exit_time != 0)):\n\t\t\tif (return_queue==True):\n\t\t\t\ttime_IsVisible.put(exit_time.durationFrom(entry_time))\n\t\t\telse:\n\t\t\t\ttime_IsVisible.append([entry_time,exit_time])\n\t\t\tentry_time = 0\n\t\t\texit_time = 0\n\t\telif ((entry_time != 0) and (exit_time == 0) and (time == time_array[-1])):\n\t\t\tif (return_queue==True):\n\t\t\t\ttime_IsVisible.put(time.durationFrom(entry_time))\n\t\t\telse:\n\t\t\t\ttime_IsVisible.append([entry_time,time])\n\treturn time_IsVisible\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef setup_orekit_zip_file(filename=' '):\n\t\"\"\"\n\tThis function attempts to load the orekit-data.zip from 5 places: the user's home directory\n\tthe root directory, where the user specified + the \"orekit-data.zip\", where the user\n\tspecified, and in the directory the function was called from.\n\tIf successful, it sets up the Orekit DataProviders to access it and sets up the java\n\tengine with orekit.\n\tnote -- Java VM needs to be initiated prior to calling this function with\n\t\t\torekit.initVM()\n\tInputs: filename (str): Path of zip with orekit data\n\tOutputs: Boolean true if successful\n\t\"\"\"\n\tprospective_files = []\n\n\t# Try the user's home directory\n\thome = os.path.expanduser(\"~\")\n\tpath = os.path.join(home, 'orekit-data.zip')\n\tprospective_files.append(File(path))\n\tprospective_files[0] = File(prospective_files[0].absolutePath)\n\n\t# Try in the root directory\n\n\troot = ('/orekit-data.zip')\n\tprospective_files.append(File(path))\n\tprospective_files[1] = File(prospective_files[1].absolutePath)\n\n\t# Try with the user's path + '/orekit-data.zip'\n\n\tpath = os.path.join(filename, 'orekit-data.zip')\n\tprospective_files.append(File(path))\n\tprospective_files[2] = File(prospective_files[2].absolutePath)\n\n\t# Try what the user actually entered\n\n\tprospective_files.append(File(path))\n\tprospective_files[3] = File(prospective_files[3].absolutePath)\n\n\t# Try 'orekit-data.zip' in the current directory\n\n\tpath = 'orekit-data.zip'\n\tprospective_files.append(File(path))\n\tprospective_files[4] = File(prospective_files[4].absolutePath)\n\n\n\tdatafile = prospective_files[0] #initialize datafile\n\n\tif prospective_files[1].exists():\n\t\tdatafile = prospective_files[1]\n\n\telif prospective_files[2].exists():\n\t\tdatafile = prospective_files[2]\n\n\telif prospective_files[3].exists():\n\t\tdatafile = prospective_files[3]\n\n\telif prospective_files[4].exists():\n\t\tdatafile = prospective_files[4]\n\n\tif not datafile.exists():\n\t\tprint('File not found in:', prospective_files[1].absolutePath, '\\n',\n\t\t\t prospective_files[2].absolutePath, '\\n',\n\t\t\t prospective_files[3].absolutePath, '\\n',\n\t\t\t prospective_files[4].absolutePath, '\\n')\n\t\tprint(\"\"\"\n\t\tThe Orekit library relies on some external data for physical models.\n\t\tTypical data are the Earth Orientation Parameters and the leap seconds history,\n\t\tboth being provided by the IERS or the planetary ephemerides provided by JPL.\n\t\tSuch data is stored in text or binary files with specific formats that Orekit knows\n\t\thow to read, and needs to be provided for the library to work.\n\t\tYou can download a starting file with this data from the orekit gitlab at:\n\t\thttps://gitlab.orekit.org/orekit/orekit-data\n\t\tor by the function:\n\t\torekit.pyhelpers.download_orekit_data_curdir()\n\t\t\"\"\")\n\t\treturn False\n\n\tDM = DataProvidersManager.getInstance()\n\tcrawler = ZipJarCrawler(datafile)\n\tDM.clearProviders()\n\tDM.addProvider(crawler)\n\treturn True\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef t1_gte_t2_string(time1, time2):\n\t\"\"\"\n\tReturns true of time1 comes after or is equal to time2\n\tArgs:\n\t\ttime1 (string): time1 in ISO-8601 standard\n\t\ttime2 (string): time2 in ISO-8601 standard\n\t\tEx. '2020-12-03T00:00:00.000'\n\tReturns:\n\t\tboolean: true if time1 comes after or is equal to time2\n\t\"\"\"\n\treturn absolute_time_converter_utc_string(time1).isAfterOrEqualTo(absolute_time_converter_utc_string(time2))\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef t1_lte_t2_string(time1, time2):\n\t\"\"\"\n\tInputs: time1, time2 (two strings)\n\tOutput: booleen value (true if time1 less than or equal to time2)\n\t\"\"\"\n\treturn absolute_time_converter_utc_string(time1).isBeforeOrEqualTo(absolute_time_converter_utc_string(time2))\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef absolute_time_converter_utc_manual(year, month, day, hour=0, minute=0, second=0.0):\n\t\"\"\"\n\tturn time into orekit absolute time object\n\tInputs: time scales in UTC\n\tOutput: absolute time object from orekit\n\t\"\"\"\n\treturn AbsoluteDate(int(year), int(month), int(day), int(hour), int(minute), float(second), TimeScalesFactory.getUTC())\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef absolute_time_converter_utc_string(time_string):\n\t\"\"\"\n\tturn time_string into orekit absolute time object\n\tInputs: time scales in UTC\n\tOutput: absolute time object from orekit\n\t\"\"\"\n\treturn AbsoluteDate(time_string, TimeScalesFactory.getUTC())\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef convert_tle_string_to_TLE(tle_line1, tle_line2):\n\t\"\"\"\n\tconvert two tle line strings into orekit TLE object\n\tInputs: tle_line1, tle_line2 (tle two line element strings)\n\t\tEx: tle_line1 = \"1 25544U 98067A 20174.66385417 .00000447 00000-0 16048-4 0 9992\"\n\t\t\ttle_line2 = \"2 25544 51.6446 321.3575 0002606 75.8243 105.9183 15.49453790232862\"\n\tOutput: Orekit TLE object\n\t\"\"\"\n\treturn TLE(tle_line1,tle_line2)\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef find_sat_distance(prop1, prop2, time):\n\t\"\"\"\n\tdistance between two propagators at a given time\n\tInputs: prop1/prop2 (Two orekit propagator objects), time (orekit absolute time object--utc)\n\tOutput: Distance (meters)\n\t\"\"\"\n\tITRF = FramesFactory.getITRF(IERSConventions.IERS_2010, True)\n\tearth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS, Constants.WGS84_EARTH_FLATTENING, ITRF)\n\n\tpv_1 = prop1.getPVCoordinates(time, prop1.getFrame())\n\tpv_2 = prop2.getPVCoordinates(time, prop2.getFrame())\n\n\tp_1 = pv_1.getPosition()\n\tp_2 = pv_2.getPosition()\n\n\treturn abs(Vector3D.distance(p_1, p_2))\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef check_sats_in_range(callback_function):\n\t\"\"\"\n\tDO NOT DELETE -- FOR NATS MESSAGING\n\t\"\"\"\n\treturn callback_function\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef keplerian_orbit(parameters):\n \"\"\"\n\tGiven a dictionary of parameters containg eccentricity, semimajor_axis, inclination, perigee_argument, right\n\tacension of ascending node, anomaly, anomaly_type and orbit_update_date this function returns a keplerian\n\torbit orekit object\n\tArgs:\n\t\tparameters (dict): dictionary of parameters containg eccentricity, semimajor_axis (meters),\n inclination, perigee argument, right ascension of ascending node, orbit_update_date,\n and anomoly with another defining key\n [\"anomaly_type\"] = \"MEAN\" or \"TRUE\"\n [\"frame\"] = \"EME2000\", \"J2000\", or \"TEME\" only\n Ex.\n parameters = {\n \"eccentricity\": 0.0008641,\n \"semimajor_axis\": 6801395.04,\n \"inclination\": radians(87.0),\n \"perigee_argument\": radians(20.0),\n \"right_ascension_of_ascending_node\":radians(10.0),\n \"anomaly\": radians(0.0),\n \"anomaly_type\": \"TRUE\",\n \"orbit_update_date\":'2021-12-02T00:00:00.000',\n \"frame\": \"EME\"}\n\tReturns:\n\t\tKeplerianOrbit: Keplerian orbit orekit object\n\t\"\"\"\n eccentricity = float(parameters[\"eccentricity\"])\n semimajor_axis = float(parameters[\"semimajor_axis\"])\n inclination = float(parameters[\"inclination\"])\n perigee_argument = float(parameters[\"perigee_argument\"])\n right_ascension_of_ascending_node = float(parameters[\"right_ascension_of_ascending_node\"])\n anomaly = float(parameters[\"anomaly\"])\n orbit_update_date = absolute_time_converter_utc_string(parameters[\"orbit_update_date\"])\n frame = string_to_frame(parameters[\"frame\"])\n\n if (parameters[\"anomaly_type\"] == \"TRUE\"):\n return KeplerianOrbit(semimajor_axis, eccentricity, inclination, perigee_argument, right_ascension_of_ascending_node,\n anomaly, PositionAngle.TRUE, frame, orbit_update_date, Constants.WGS84_EARTH_MU)\n elif (parameters[\"anomaly_type\"] == \"MEAN\"):\n return KeplerianOrbit(semimajor_axis, eccentricity, inclination, perigee_argument, right_ascension_of_ascending_node,\n anomaly, PositionAngle.MEAN, frame, orbit_update_date, Constants.WGS84_EARTH_MU)\n else:\n return(\"Error: Need to redefine anomoly_type, see function documentation\")\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef get_keplerian_parameters(spacecraft_state, anomaly_type = \"TRUE\"):\n \"\"\"\n\tGiven a SpaceCraftState object this function computes the keplerian orbit parameters\n Note: parameter values may change but they'll define the same orbit\n\tArgs:\n\t\tspacecraft_state (SpaceCraftState): SpaceCraftState orekit object that has an orbit attribute\n anomaly_type (string; \"MEAN\" or \"TRUE\"): tells to return true or mean anomaly, defaults to TRUE\n\tReturns:\n\t\tdict: dictionary of parameters containg eccentricity, semimajor_axis, inclination, perigee argument, right\n\t\tascension of ascending node, anomaly, anomaly_type, and orbit_update_date\n \"\"\"\n parameters = dict()\n new_orbit = KeplerianOrbit(spacecraft_state.getOrbit())\n\n parameters[\"semimajor_axis\"] = new_orbit.getA()\n parameters[\"eccentricity\"] = new_orbit.getE()\n parameters[\"inclination\"] = new_orbit.getI()\n parameters[\"perigee_argument\"] = new_orbit.getPerigeeArgument()\n parameters[\"right_ascension_of_ascending_node\"] = new_orbit.getRightAscensionOfAscendingNode()\n parameters[\"orbit_update_date\"] = new_orbit.getDate().toString()\n parameters[\"frame\"] = frame_to_string(spacecraft_state.getFrame())\n if (anomaly_type == \"MEAN\"):\n parameters[\"anomaly\"] = new_orbit.getMeanAnomaly()\n parameters[\"anomaly_type\"] = \"MEAN\"\n else:\n parameters[\"anomaly\"] = new_orbit.getTrueAnomaly()\n parameters[\"anomaly_type\"] = \"TRUE\"\n return parameters\n\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef str_tle_propagator(tle_1, tle_2):\n\t\"\"\"\n\tCreates propogator for string format TLE\n\tArgs:\n\t\ttle_1, tle_2 (strings) line 1 and line 2 of a NORAD TLE\n\tReturns:\n\t\tTLEPropagator orekit object\n\t\"\"\"\n\treturn TLEPropagator.selectExtrapolator(convert_tle_string_to_TLE(tle_1, tle_2))\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef analytical_propagator(parameters):\n\t\"\"\"\n\tTakes in a dictionary of keplarian parameters and returns an Keplarian analytical propogator\n\tArgs:\n\t\tArgs:\n \t\tparameters (dict): dictionary of parameters containg eccentricity, semimajor_axis (meters),\n inclination, perigee argument, right ascension of ascending node, orbit_update_date, and\n anomoly with another defining key\n [\"anomaly_type\"] = \"MEAN\" or \"TRUE\"\n [\"frame\"] = \"EME2000\", \"J2000\", or \"TEME\" only\n Ex.\n parameters = {\n \"eccentricity\": 0.0008641,\n \"semimajor_axis\": 6801395.04,\n \"inclination\": radians(87.0),\n \"perigee_argument\": radians(20.0),\n \"right_ascension_of_ascending_node\":radians(10.0),\n \"anomaly\": radians(0.0),\n \"anomaly_type\": \"TRUE\",\n \"orbit_update_date\":'2021-12-02T00:00:00.000',\n \"frame\": \"EME\"}\n\tReturns:\n\t\tAbstractAnalyticalPropagator: propagator that can be used to propagate an orbit\n and acts as a PVCoordinatesProvider\n (PV = position, velocity)\n\t\"\"\"\n\treturn KeplerianPropagator(keplerian_orbit(parameters), Constants.WGS84_EARTH_MU)\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef moving_body_pointing_law(orbit_to_track_propagator, parameters):\n\t\"\"\"Takes in the propagator of a satellite and returns a attitude law or attituded provider to track that satellite\n\tArgs:\n\t\torbit_to_track_propagator: (AbstractAnalyticalPropagator or PVCoordinateProvider)\n propagator for the orbit desired to be tracked\n parameters: dictionary containing at least...\n parameters[\"frame\"] = \"EME2000\", \"J2000\", or \"TEME\" only\n\tReturns:\n\t\tAttitudeProvider: AttitudeLaw that can be added to a propagator in order to simulate tracking\n\t\"\"\"\n\tframe = string_to_frame(parameters[\"frame\"])\n\treturn CelestialBodyPointed(frame, orbit_to_track_propagator,\n\t\t\t\t\t\t\t\t\tVector3D.PLUS_K, Vector3D.PLUS_K, Vector3D.MINUS_J)\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef ground_pointing_law(parameters):\n\t\"\"\"\n\tGiven a longitude, lattitude, and altitude it returns a ground pointing attitude law\n\tArgs:\n\t\tparameters: dictionary containing at least...\n parameters[\"frame\"] = (str) \"EME2000\", \"J2000\", or \"TEME\" only\n parameters[\"latitude\"] = (float -- radians) latitude\n parameters[\"longitude\"] = (float -- radians) longitude\n parameters[\"altitude\"] = (float -- meters) altitude above sea level\n\tReturns:\n\t\tAttidueProvider: attitude law that tells the satellite to point at a specific point on the ground\n\t\"\"\"\n\tITRF = FramesFactory.getITRF(IERSConventions.IERS_2010, True)\n\tearth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,\n\t\t\t\t\t\t\t Constants.WGS84_EARTH_FLATTENING,\n\t\t\t\t\t\t\t ITRF)\n\tpoint = GeodeticPoint(float(parameters[\"latitude\"]), float(parameters[\"longitude\"]), float(parameters[\"altitude\"]))\n\tframe = string_to_frame(parameters[\"frame\"])\n\treturn TargetPointing(frame, point, earth)\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef nadir_pointing_law(parameters):\n \"\"\"\n Returns a nadir pointing attitude law (points to ground point directly below) for the earth as the\n celestial body orbited\n Args:\n parameters: dictionary containing at least...\n parameters[\"frame\"] = (str) \"EME\", \"J2000\", or \"TEME\" only\n Returns:\n AttidueProvider: attitude law that tells the satellite to point at nadir\n \"\"\"\n ITRF = FramesFactory.getITRF(IERSConventions.IERS_2010, True)\n earth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,\n Constants.WGS84_EARTH_FLATTENING,\n ITRF)\n frame = string_to_frame(parameters[\"frame\"])\n return NadirPointing(frame, earth)\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef attitude_provider_constructor(attitude_provider_type, parameters):\n\t\"\"\"\n\tTakes in an attitude provider type and the parameters necessary for that type\n to return a desired attitude law provider...\n\tArgs:\n Dependent on the attitude_provider_type, the accompaning parameters dictionary\n should contain different information for the pointing...\n\n attitude_provider_type (string): the name of pointing law\n \"moving_body_tracking\", \"ground_tracking\",\n or \"nadir_tracking\"\n parameters (dict): values dependent on attitude_provider_type\n \"moving_body_tracking\":\n parameters contains eccentricity, semimajor_axis (meters), inclination,\n perigee argument, right ascension of ascending node, orbit_update_date,\n and anomoly with another defining key\n [\"anomaly_type\"] = \"MEAN\" or \"TRUE\"\n [\"frame\"] = \"EME2000\", \"J2000\", or \"TEME\" only\n ALL OF THESE DESCRIBE THE ORBIT OF THE SAT BEING TRACKED, NOT THE\n TRACKING SAT\n ex.\n parameters = {\n \"eccentricity\": 0.0008641,\n \"semimajor_axis\": 6801395.04,\n \"inclination\": radians(87.0),\n \"perigee_argument\": radians(20.0),\n \"right_ascension_of_ascending_node\":radians(10.0),\n \"anomaly\": radians(0.0),\n \"anomaly_type\": \"TRUE\",\n \"orbit_update_date\":'2021-12-02T00:00:00.000',\n \"frame\": \"EME\"}\n \"ground_tracking\":\n parameters should be a dictonary containing the frame (of the tracking\n satellite), lattitude, longitude, and altitude of the location with\n respect to the earth (see ground_pointing_law for more documentation)\n \"nadir_tracking\":\n parameters should be a dictonary containing the frame of the tracking\n satellite (parameters['frame'])\n [\"frame\"] = \"EME2000\", \"J2000\", or \"TEME\" only\n\n\tReturns:\n\t\tAttitudeProvider: Attitude provider of specified pointing law, can be added\n to propagator to define satellite's pointing\n\t\"\"\"\n\tif attitude_provider_type == utils.MOVING_BODY_TRACKING:\n\n\t\torbit_to_track_propagator = analytical_propagator(parameters)\n\n\t\treturn moving_body_pointing_law(orbit_to_track_propagator, parameters)\n\n\telif attitude_provider_type == utils.GROUND_TRACKING:\n\t\treturn ground_pointing_law(parameters)\n\n\telif attitude_provider_type == utils.NADIR_TRACKING:\n\t\treturn nadir_pointing_law(parameters)\n\telse:\n\t\treturn \"Attitude Law type unknown\"\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef get_ground_passes(propagator, grstn_latitude, grstn_longitude, grstn_altitude, start, stop, ploting_param=False):\n\t\"\"\"\n\tGets all passes for a specific satellite occuring during the given range. Pass is defined as 10° above the horizon,\n\tbelow this is unusable (for our purposes)\n\tArgs:\n\t\tpropagator ([any] OreKit orbit propagator): propagator, TLEPropagator or KeplerianPropagator for the\n\t\t\t\t\t\t\t\t\t\t\t\t\tsatellite in question\n\t\tgrstn_latitude (Float): latitude of the ground station in degrees\n\t\tgrstn_longitude (Float): longitude of the ground station in degrees\n\t\tstart (OreKit AbsoluteDate): the beginning of the desired time interval\n\t\tstop (OreKit AbsoluteDate): the end of the desired time interval\n\t\tplotting_param (Boolean): do not use, used by potential plotter\n\tReturn value:\n\t\tA dictionary with {\"start\":[OreKit AbsoluteDate], \"stop\":[OreKit AbsoluteDate], \"duration\": (seconds) [float]}\n\t\tAlternatively, returns a queue of times in reference to the start time for ease of plotting ground passes.\n\tNotes:\n\t\tuse absolutedate_to_datetime() to convert from AbsoluteDate\n\tTODO: add ElevationMask around ground station to deal with topography blocking communications\n\t\"\"\"\n\n\tITRF = FramesFactory.getITRF(IERSConventions.IERS_2010, True)\n\tearth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,\n\t\t\t\t\t\t Constants.WGS84_EARTH_FLATTENING,\n\t\t\t\t\t\t ITRF)\n\n\tgs_location = GeodeticPoint(radians(grstn_latitude), radians(grstn_longitude), float(grstn_altitude))\n\tgs_frame = TopocentricFrame(earth, gs_location, \"ground station\")\n\n\televation_detector = ElevationDetector(gs_frame).withConstantElevation(0.0).withHandler(ContinueOnEvent())\n\tlogger = EventsLogger()\n\tlogged_detector = logger.monitorDetector(elevation_detector)\n\n\tpropagator.addEventDetector(logged_detector)\n\tstate = propagator.propagate(start, stop)\n\n\tevents = logger.getLoggedEvents()\n\tpass_start_time = None\n\tresult = []\n\tif not ploting_param:\n\t\tfor event in logger.getLoggedEvents():\n\t\t\tif event.isIncreasing():\n\t\t\t\tpass_start_time = event.getState().getDate()\n\t\t\telse:\n\t\t\t\tstop_time = event.getState().getDate()\n\t\t\t\tresult.append({\"start\": pass_start_time,\n\t\t\t\t\t\t\t \"stop\": stop_time,\n\t\t\t\t\t\t\t \"duration\": stop_time.durationFrom(start)/60})\n\t\t\t\tpass_start_time = None\n\telse:\n\t\tresult = queue.Queue(0)\n\t\tfor event in logger.getLoggedEvents():\n\t\t\tif event.isIncreasing():\n\t\t\t\tpass_start_time = event.getState().getDate()\n\t\t\telse:\n\t\t\t\tpass_stop_time = event.getState().getDate()\n\t\t\t\tresult.put(pass_start_time.durationFrom(start)) # start is the initial time of interest\n\t\t\t\tresult.put(pass_stop_time.durationFrom(start))\n\t\t\t\tpass_start_time = None\n\n\treturn result\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\ndef check_iot_in_range(propagator, grstn_latitude, grstn_longitude, grstn_altitude, time):\n\t\"\"\"\n\tDetermines whether a satellite is above the horizon at a specific time\n\tin the reference frame of a ground station\n\tArgs:\n propagator: orekit propagator object of overhead satellite\n\t\tgrstn_latitude (float): (degrees) groudn station latitude\n\t\tgrstn_longitude (float): (degrees) ground station longitude\n\t\tgrstn_altitude (float): (meters) ground station altitude\n\t\ttime (string): time at which the range check is to occur.\n\t\"\"\"\n\tITRF = FramesFactory.getITRF(IERSConventions.IERS_2010, True)\n\tearth = OneAxisEllipsoid(Constants.WGS84_EARTH_EQUATORIAL_RADIUS,\n\t\t\t\t\t\t Constants.WGS84_EARTH_FLATTENING,\n\t\t\t\t\t\t ITRF)\n\n\tgs_location = GeodeticPoint(radians(grstn_latitude), radians(grstn_longitude), float(grstn_altitude))\n\tgs_frame = TopocentricFrame(earth, gs_location, \"ground station\")\n\tpv = propagator.getPVCoordinates(time, propagator.getFrame())\n\televation = degrees(gs_frame.getElevation(pv.getPosition(),\n\t\t\t\t\tpropagator.getFrame(),time))\n\n\tif elevation > 0:\n\t\treturn True\n\n\treturn False\n#-------------------------------------------------------------------------------\n#-------------------------------------------------------------------------------\nsetup_orekit_zip_file()\n"
] |
[
[
"numpy.arange"
]
] |
cityinspain/baseball-analytics
|
[
"f84b3856748cf8dec8f64db7e90fa94a17a0b7e9"
] |
[
"download_scripts/retrosheet_wrangle.py"
] |
[
"#!/usr/bin/env python3\n\n\"\"\"Wrangle Retrosheet Data from {data_dir}/retrosheet/raw to {data_dir}/retrosheet/wrangled\n\nWrangles: player per game and team per game data\n\"\"\"\n\n__author__ = 'Stephen Diehl'\n\nimport argparse\nimport re\nimport shutil\nfrom pathlib import Path\nimport logging\nimport sys\nimport collections\n\nimport pandas as pd\nimport numpy as np\n\nimport data_helper as dh\n\nlogger = logging.getLogger(__name__)\nlogger.setLevel(logging.DEBUG)\n\n\ndef get_parser():\n \"\"\"Args Description\"\"\"\n\n parser = argparse.ArgumentParser(\n description=__doc__,\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n\n parser.add_argument(\"--data-dir\", type=str, help=\"baseball data directory\", default='../data')\n parser.add_argument(\"-v\", \"--verbose\", help=\"verbose output\", action=\"store_true\")\n parser.add_argument(\"--log\", dest=\"log_level\", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],\n help=\"Set the logging level\")\n\n return parser\n\n\ndef get_game(p_retrosheet_collected):\n \"\"\"Read in collected results of the cwgame parser.\"\"\"\n logger.info('Reading game.csv.gz ...')\n filename = p_retrosheet_collected / 'game.csv.gz'\n game = dh.from_csv_with_types(filename)\n n_rows, n_cols = game.shape\n logger.info(f'game loaded {n_rows:,d} rows with {n_cols:,d} columns')\n return game\n\n\ndef get_player_game(p_retrosheet_collected):\n \"\"\"Read in collected results of the cwdaily parser.\"\"\"\n logger.info('Reading player_game.csv.gz ...')\n filename = p_retrosheet_collected / 'player_game.csv.gz'\n player_game = dh.from_csv_with_types(filename)\n n_rows, n_cols = player_game.shape\n logger.info(f'player_game loaded {n_rows:,d} rows with {n_cols:,d} columns')\n return player_game\n\n\ndef clean_player_game(player_game):\n \"\"\"Ensure Primary Key is Unique.\"\"\"\n\n # Fix Duplicate Primary Key\n pkey = ['game_id', 'player_id']\n if not dh.is_unique(player_game, pkey):\n # if pkey is dup, sum the stat rows for the dups\n dups = player_game.duplicated(subset=pkey)\n df_dups = player_game.loc[dups, pkey]\n logger.warning(f'Dup PKey Found - summing stats for:\\n{df_dups.to_string()}')\n\n # TODO flag fields should be ORed not summed\n # this is not currently a problem with the single dup found\n # data integrity tests verify that all flag fields are either 0 or 1\n \"\"\"Flag Fields (value is 0 or 1):\n b_g b_g_dh b_g_ph b_g_pr p_g p_gs p_cg p_sho p_gf p_w p_l p_sv f_p_g f_p_gs f_c_g \n f_c_gs f_1b_g f_1b_gs f_2b_g f_2b_gs f_3b_g f_3b_gs f_ss_g f_ss_gs f_lf_g f_lf_gs \n f_cf_g f_cf_gs f_rf_g f_rf_gs \n \"\"\"\n\n # player stat columns b_ for batter, p_ for pitcher, f_ for fielder\n stat_columns = [col for col in player_game.columns if re.search(r'^[bpf]_', col)]\n stat_columns.remove('b_g') # don't sum this column\n\n player_game = dh.sum_stats_for_dups(player_game, pkey, stat_columns)\n\n return player_game\n\n\ndef create_batting(player_game, game_start, p_retrosheet_wrangled):\n \"\"\"Create batting.csv for batting attributes per player per game.\"\"\"\n # column names of the batting attributes\n b_cols = [col for col in player_game.columns if col.startswith('b_')]\n\n # Note: any player who is in a game in any role, will have b_g = 1\n # even if b_pa == 0 (no plate appearances)\n\n # fields which uniquely identify a record\n pkey = ['game_id', 'player_id']\n\n # fields to join to other \"tables\"\n fkey = ['team_id']\n\n batting = player_game.loc[:, pkey + fkey + b_cols].copy()\n\n # remove b_ from the column names, except for b_2b and b_3b\n b_cols_new = {col: col[2:] for col in b_cols}\n b_cols_new['b_2b'] = 'double'\n b_cols_new['b_3b'] = 'triple'\n b_cols_new['b_gdp'] = 'gidp' # to match Lahman\n b_cols_new['b_hp'] = 'hbp' # to match Lahman\n batting.rename(columns=b_cols_new, inplace=True)\n\n # add game_start.dt.year as many queries use year\n batting = pd.merge(batting, game_start[['game_id', 'game_start']])\n batting['year'] = batting['game_start'].dt.year.astype('int16')\n\n dh.optimize_df_dtypes(batting, ignore=['year'])\n logger.info('Writing and compressing batting. This could take several minutes ...')\n dh.to_csv_with_types(batting, p_retrosheet_wrangled / 'batting.csv.gz')\n\n\ndef create_pitching(player_game, game_start, p_retrosheet_wrangled):\n \"\"\"Create pitching.csv for pitching attributes per player per game.\"\"\"\n # column names of the pitching attributes\n p_cols = [col for col in player_game.columns if col.startswith('p_')]\n\n # if all pitching attributes are 0 then the player did not pitch\n # note: all attributes are unsigned integers, so if their sum is zero, all are zero\n p_filt = player_game[p_cols].sum(axis=1) == 0\n\n # fields which uniquely identify a record\n pkey = ['game_id', 'player_id']\n\n # fields to join to other \"tables\"\n fkey = ['team_id']\n\n # data with some non-zero attributes\n pitching = player_game.loc[~p_filt, pkey + fkey + p_cols].copy()\n\n # remove p_ from the column names, except for p_2b and p_3b\n p_cols_new = {col: col[2:] for col in p_cols}\n p_cols_new['p_2b'] = 'double'\n p_cols_new['p_3b'] = 'triple'\n p_cols_new['p_gdp'] = 'gidp' # to match Lahman\n p_cols_new['p_hp'] = 'hbp' # to match Lahman\n pitching.rename(columns=p_cols_new, inplace=True)\n\n # add game_start.dt.year as many queries use year\n pitching = pd.merge(pitching, game_start[['game_id', 'game_start']])\n pitching['year'] = pitching['game_start'].dt.year.astype('int16')\n\n dh.optimize_df_dtypes(pitching, ignore=['year'])\n logger.info('Writing and compressing pitching. This could take several minutes ...')\n dh.to_csv_with_types(pitching, p_retrosheet_wrangled / 'pitching.csv.gz')\n\n\ndef create_fielding(player_game, game_start, p_retrosheet_wrangled):\n \"\"\"Create fielding.csv for fielding attributes per player per game.\"\"\"\n # column names for fielding attributes\n f_cols = [col for col in player_game.columns if col.startswith('f_')]\n\n # create orig_cols dictionary which maps fielder's pos to original fielding columns names\n # create new_cols dictionary which maps fielder's pos to new fielding column names\n # pos: P, C, 1B, 2B, 3B, SS, LF, CF, RF\n # column name pattern: f_{pos}_{stat}\n orig_cols = collections.defaultdict(list)\n new_cols = collections.defaultdict(list)\n for col in f_cols:\n match = re.search(r'f_(\\w{1,2})_(\\w*)', col)\n pos = match.group(1)\n stat = match.group(2)\n orig_cols[pos].append(col)\n stat = stat.replace('out', 'inn_outs') # to match Lahman\n new_cols[pos].append(stat)\n\n # full pkey will be: ['game_id', 'player_id', 'pos']\n pkey = ['game_id', 'player_id']\n\n # fields to join to other \"tables\"\n fkey = ['team_id']\n\n \"\"\"For each record created by cwdaily, create up to 9 new records, one per position.\n Each record will temporarily go in its own dataframe and then be concatenated.\n \n Each dataframe has the same columns.\"\"\"\n dfs = []\n for pos in orig_cols.keys():\n # if all fielding attributes for this pos are 0 then the player did not play that pos\n # note: all attributes are unsigned integers\n f_filt = player_game[orig_cols[pos]].sum(axis=1) == 0\n\n df = pd.DataFrame()\n df[pkey + fkey + new_cols[pos]] = \\\n player_game.loc[~f_filt, pkey + fkey + orig_cols[pos]].copy()\n\n # add the position column to the df\n # use upper case to match Lahman position values\n df.insert(2, 'pos', pos.upper())\n\n # orig_cols['c'] has pb and xi columns\n # all other positions do not have pb and xi\n if pos != 'c':\n df[f'pb'] = 0\n df[f'xi'] = 0\n\n dfs.append(df)\n\n fielding = pd.concat(dfs, ignore_index=True)\n\n # add game_start.dt.year as many queries use year\n fielding = pd.merge(fielding, game_start[['game_id', 'game_start']])\n fielding['year'] = fielding['game_start'].dt.year.astype('int16')\n\n dh.optimize_df_dtypes(fielding, ignore=['year'])\n logger.info('Writing and compressing fielding. This could take several minutes ...')\n dh.to_csv_with_types(fielding, p_retrosheet_wrangled / 'fielding.csv.gz')\n\n\ndef wrangle_game(game, p_retrosheet_wrangled):\n \"\"\"Tidy the Game Data\n\n There are 3 types of data:\n\n data specific to a game -- the 'game' columns below\n data specific to the home team for that game -- the 'home' columns below\n data specific to the away team for that game -- the 'away' columns below\n The attributes for the home team are identical to the attributes for the away team.\n\n This suggests breaking this out into 2 csv files.\n\n 1. team_game.csv with key (game_id, team_id) -- stats per team per game (e.g. runs scored)\n 2. game.csv with key (game_id) -- stats per game (e.g. attendance)\n \"\"\"\n\n home_cols = [col for col in game.columns if col.startswith('home')]\n away_cols = [col for col in game.columns if col.startswith('away')]\n game_cols = [col for col in game.columns\n if not col.startswith('home') and not col.startswith('away')]\n\n game_tidy = game[game_cols].copy()\n home_team_game = game[['game_id'] + home_cols].copy()\n away_team_game = game[['game_id'] + away_cols].copy()\n\n home_team_game['bat_last'] = True\n away_team_game['bat_last'] = False\n home_team_game = dh.move_column_after(home_team_game, 'game_id', 'bat_last')\n away_team_game = dh.move_column_after(away_team_game, 'game_id', 'bat_last')\n\n # remove leading 'home_' and 'away_' suffix from fields\n home_team_game.rename(columns=lambda col: col[5:] if col.startswith('home_') else col, inplace=True)\n away_team_game.rename(columns=lambda col: col[5:] if col.startswith('away_') else col, inplace=True)\n\n # include opponent team_id in each row\n home_team_game.insert(4, 'opponent_team_id', away_team_game['team_id'])\n away_team_game.insert(4, 'opponent_team_id', home_team_game['team_id'])\n team_game = pd.concat([home_team_game, away_team_game])\n\n # improve column names\n names = {col: col.replace('_ct', '') for col in team_game.columns if col.endswith('_ct')}\n\n # handle invalid identifiers\n names['2b_ct'] = 'double'\n names['3b_ct'] = 'triple'\n\n # pitcher_ct (number of pitchers) is a good name though, keep it\n names.pop('pitcher_ct')\n\n # additional fields to rename for consistency\n names['bi_ct'] = 'rbi'\n names['gdp_ct'] = 'gidp'\n names['hits_ct'] = 'h'\n names['hp_ct'] = 'hbp'\n names['err_ct'] = 'e'\n names['score_ct'] = 'r'\n\n team_game = team_game.rename(columns=names)\n\n # create new datetime column\n game_tidy['game_start'] = game_tidy.apply(parse_datetime, axis=1)\n game_tidy = dh.move_column_after(game_tidy, 'game_id', 'game_start')\n\n # these fields are no longer necessary\n game_tidy = game_tidy.drop(['start_game_tm', 'game_dt', 'game_dy'], axis=1)\n\n # add the game_start column to team_game to simplify queries\n team_game = pd.merge(team_game, game_tidy[['game_id', 'game_start']])\n team_game['year'] = team_game['game_start'].dt.year.astype('int16')\n\n logger.info('Writing and compressing team_game. This could take several minutes ...')\n dh.optimize_df_dtypes(team_game, ignore=['year'])\n dh.to_csv_with_types(team_game, p_retrosheet_wrangled / 'team_game.csv.gz')\n\n # convert designated hitter to True/False and rename\n game_tidy['dh'] = False\n filt = game_tidy['dh_fl'] == 'T'\n game_tidy.loc[filt, 'dh'] = True\n game_tidy.drop('dh_fl', axis=1, inplace=True)\n\n # convert impossible attendance values to null and rename\n filt = game_tidy['attend_park_ct'] <= 0\n impossible_values = game_tidy.loc[filt, 'attend_park_ct'].unique()\n game_tidy['attendance'] = game_tidy['attend_park_ct'].replace(impossible_values, np.nan)\n game_tidy.drop('attend_park_ct', axis=1, inplace=True)\n\n # convert impossible temperature values to null and rename\n filt = game_tidy['temp_park_ct'] <= 0\n impossible_values = game_tidy.loc[filt, 'temp_park_ct'].unique()\n game_tidy['temperature'] = game_tidy['temp_park_ct'].replace(impossible_values, np.nan)\n game_tidy.drop('temp_park_ct', axis=1, inplace=True)\n\n # replace code values with strings\n # http://chadwick.sourceforge.net/doc/cwgame.html#cwtools-cwgame-winddirection\n direction = {\n 0: 'unknown',\n 1: 'to_lf',\n 2: 'to_cf',\n 3: 'to_rf',\n 4: 'l_to_r',\n 5: 'from_lf',\n 6: 'from_cf',\n 7: 'from_rf',\n 8: 'r_to_l'}\n game_tidy['wind_direction'] = \\\n game_tidy['wind_direction_park_cd'].map(direction).replace('unknown', np.nan)\n game_tidy.drop('wind_direction_park_cd', axis=1, inplace=True)\n\n # http://chadwick.sourceforge.net/doc/cwgame.html#cwtools-cwgame-windspeed\n # convert impossible wind speed values to null and rename\n filt = game_tidy['wind_speed_park_ct'] < 0\n impossible_values = game_tidy.loc[filt, 'wind_speed_park_ct'].unique()\n game_tidy['wind_speed'] = game_tidy['wind_speed_park_ct'].replace(impossible_values, np.nan)\n game_tidy.drop('wind_speed_park_ct', axis=1, inplace=True)\n\n # replace code values with strings\n # http://chadwick.sourceforge.net/doc/cwgame.html#cwtools-cwgame-fieldcondition\n condition = {\n 0: 'unknown',\n 1: 'soaked',\n 2: 'wet',\n 3: 'damp',\n 4: 'dry'}\n game_tidy['field_condition'] = \\\n game_tidy['field_park_cd'].map(condition).replace('unknown', np.nan)\n game_tidy.drop('field_park_cd', axis=1, inplace=True)\n\n # replace code values with strings\n # http://chadwick.sourceforge.net/doc/cwgame.html#cwtools-cwgame-precipitation\n precip = {\n 0: 'unknown',\n 1: 'none',\n 2: 'drizzle',\n 3: 'showers',\n 4: 'rain',\n 5: 'snow'}\n game_tidy['precip_type'] = \\\n game_tidy['precip_park_cd'].map(precip).replace('unknown', np.nan)\n game_tidy.drop('precip_park_cd', axis=1, inplace=True)\n\n # replace code values with strings\n # http://chadwick.sourceforge.net/doc/cwgame.html#cwtools-cwgame-sky\n sky = {\n 0: 'unknown',\n 1: 'sunny',\n 2: 'cloudy',\n 3: 'overcast',\n 4: 'night',\n 5: 'dome'}\n game_tidy['sky_condition'] = \\\n game_tidy['sky_park_cd'].map(sky).replace('unknown', np.nan)\n game_tidy.drop('sky_park_cd', axis=1, inplace=True)\n\n logger.info('Writing and compressing game. This could take several minutes ...')\n dh.optimize_df_dtypes(game_tidy)\n dh.to_csv_with_types(game_tidy, p_retrosheet_wrangled / 'game.csv.gz')\n\n # to add game date to other tables\n return game_tidy[['game_id', 'game_start']]\n\n\ndef parse_datetime(row):\n \"\"\"Determine AM/PM from MLB domain knowledge and Day/Night Flag\n\n Here is the relevant information.\n\n * am/pm is not specified\n * start_game_tm is an integer\n * example: 130 represents 1:30 (am or pm)\n * start_game_tm == 0 means the game start time is unknown\n * there are no start_game_tm < 100 that are not exactly zero\n * daynight_park_cd is never missing\n * based on the data, almost always a game that starts between 5 and 9 is classified as a night game\n This is likely because \"night\" actually means that the stadium lights must be turned on before a\n game of typical length ends.\n * MLB domain knowledge: A game may start \"early\" to allow for travel, but games never start\n before 9 am so: 100 <= start_game_tm < 900 => pm\n * example: 830 => 8:30 pm\n * MLB domain knowledge: A game may start \"late\" due to rain delay, but games never start\n after midnight so: 900 < start_game_tm < 1200 => am or pm depending on the day/night flag\n * example: 1030 Day => 10:30 am\n * example: 1030 Night => 10:30 pm\n \"\"\"\n date = row['game_dt']\n time = row['start_game_tm']\n day_night = row['daynight_park_cd']\n\n if 0 < time < 900:\n time += 1200\n elif (900 <= time < 1200) and day_night == 'N':\n time += 1200\n\n time_str = f'{time // 100:02d}:{time % 100:02d}'\n datetime_str = str(date) + ' ' + time_str\n return pd.to_datetime(datetime_str, format='%Y%m%d %H:%M')\n\n\ndef wrangle_event(p_retrosheet_collected, p_retrosheet_wrangled):\n \"\"\"Wrangle event\n\n At this time, there is nothing to do, just copy the collected data.\"\"\"\n source = p_retrosheet_collected / 'event.csv.gz'\n destination = p_retrosheet_wrangled / 'event.csv.gz'\n shutil.copyfile(source, destination)\n\n source = p_retrosheet_collected / 'event_types.csv'\n destination = p_retrosheet_wrangled / 'event_types.csv'\n shutil.copyfile(source, destination)\n\n\ndef wrangle_parks(data_dir, retrosheet_wrangle):\n parks_filename = data_dir / 'retrosheet/raw/misc/parkcode.txt'\n parks = pd.read_csv(parks_filename, parse_dates=['START', 'END'])\n cols = [col.lower() for col in parks.columns]\n parks.columns = cols\n parks = parks.rename(columns={'parkid': 'park_id'})\n dh.to_csv_with_types(parks, retrosheet_wrangle / 'parks.csv')\n\n\ndef wrangle_teams(data_dir, retrosheet_wrangle):\n team_dir = data_dir / 'retrosheet/raw/event/regular'\n\n dfs = []\n team_files = team_dir.glob('TEAM*')\n for team in sorted(team_files):\n year = int(team.name[-4:])\n df = pd.read_csv(team, header=None, names=['team_id', 'lg_id', 'city', 'name'])\n df.insert(1, 'year', year)\n dfs.append(df)\n retro_teams = pd.concat(dfs, ignore_index=True)\n dh.to_csv_with_types(retro_teams, retrosheet_wrangle / 'teams.csv')\n\n\ndef main():\n \"\"\"Wrangle the data.\n \"\"\"\n parser = get_parser()\n args = parser.parse_args()\n\n if args.log_level:\n fh = logging.FileHandler('download.log')\n formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s: %(message)s')\n fh.setFormatter(formatter)\n fh.setLevel(args.log_level)\n logger.addHandler(fh)\n\n if args.verbose:\n # send INFO level logging to stdout\n sh = logging.StreamHandler(sys.stdout)\n formatter = logging.Formatter('%(asctime)s:%(name)s:%(levelname)s: %(message)s')\n sh.setFormatter(formatter)\n sh.setLevel(logging.INFO)\n logger.addHandler(sh)\n\n data_dir = Path(args.data_dir)\n p_retrosheet_collected = (data_dir / 'retrosheet/collected').resolve()\n p_retrosheet_wrangled = (data_dir / 'retrosheet/wrangled').resolve()\n\n # get collected data from parsers\n game = get_game(p_retrosheet_collected) # cwgame\n game_start = wrangle_game(game, p_retrosheet_wrangled)\n\n player_game = get_player_game(p_retrosheet_collected) # cwdaily\n player_game = clean_player_game(player_game)\n\n create_batting(player_game, game_start, p_retrosheet_wrangled)\n create_pitching(player_game, game_start, p_retrosheet_wrangled)\n create_fielding(player_game, game_start, p_retrosheet_wrangled)\n\n wrangle_event(p_retrosheet_collected, p_retrosheet_wrangled) # cwevent\n\n # parks.txt is included with the retrosheet data. It is a csv file.\n wrangle_parks(data_dir, p_retrosheet_wrangled)\n\n # TEAM<YYYY> is included in the retrosheet data. They are csv files.\n wrangle_teams(data_dir, p_retrosheet_wrangled)\n\n logger.info('Finished')\n\n\nif __name__ == '__main__':\n main()"
] |
[
[
"pandas.merge",
"pandas.to_datetime",
"pandas.read_csv",
"pandas.concat",
"pandas.DataFrame"
]
] |
chaitanya9899/Project_Ml_python_AI
|
[
"ba718e6fb5d8386e8402b605d7dc6180e9b7fceb"
] |
[
"Color Detector & Tracker/detector.py"
] |
[
"# pip install opencv-python\n# pip install opencv-contrib-python\n# pip install pillow\n\nimport cv2\nimport pandas as pd\nfrom PIL import Image, ImageTk\n\ncsv_path = 'assets/colors.csv'\nindex = ['color', 'color_name', 'hex', 'R', 'G', 'B']\ndf = pd.read_csv(csv_path, names=index, header=None)\n\ndef from_rgb(rgb):\n\t\"\"\"translates an rgb tuple of int to a tkinter friendly color code\n\t\"\"\"\n\tr, g, b = rgb\n\treturn f'#{r:02x}{g:02x}{b:02x}'\n\ndef get_color_name(R,G,B):\n\tminimum = 1000\n\tfor i in range(len(df)):\n\t\td = abs(R - int(df.loc[i,'R'])) + abs(G - int(df.loc[i,'G'])) + abs(B - int(df.loc[i,'B']))\n\t\tif d <= minimum:\n\t\t\tminimum = d\n\t\t\tcname = df.loc[i, 'color_name']\n\n\treturn cname\n\nclass ColorDetector:\n\tdef __init__(self, file):\n\t\tself.image = cv2.imread(file)\n\t\tself.image = cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)\n\n\tdef display_image(self, size):\n\t\tself.image = cv2.resize(self.image, size)\n\t\ttkimg = Image.fromarray(self.image)\n\t\ttkimg = ImageTk.PhotoImage(tkimg)\n\n\t\treturn tkimg\n\n\tdef get_pixel_value(self, pos):\n\t\tx, y = pos\n\t\treturn self.image[y,x]\n\n"
] |
[
[
"pandas.read_csv"
]
] |
websterkovacek/keras
|
[
"631102a7c9efb57a351355090796d5850285663c",
"631102a7c9efb57a351355090796d5850285663c",
"631102a7c9efb57a351355090796d5850285663c",
"631102a7c9efb57a351355090796d5850285663c",
"631102a7c9efb57a351355090796d5850285663c",
"631102a7c9efb57a351355090796d5850285663c"
] |
[
"keras/distribute/keras_premade_models_test.py",
"keras/tests/model_subclassing_compiled_test.py",
"keras/distribute/mirrored_variable_test.py",
"keras/tests/custom_training_loop_test.py",
"keras/layers/preprocessing/string_lookup_v1.py",
"keras/layers/preprocessing/discretization_v1.py"
] |
[
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for keras premade models using tf.distribute.Strategy.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom absl.testing import parameterized\nimport numpy as np\nfrom keras.engine import sequential\nfrom keras.layers import core\nfrom keras.optimizer_v2 import adagrad\nfrom keras.optimizer_v2 import gradient_descent\nfrom keras.premade import linear\nfrom keras.premade import wide_deep\n\n\ndef strategy_combinations_eager_data_fn():\n return tf.__internal__.test.combinations.combine(\n distribution=[\n tf.__internal__.distribute.combinations.default_strategy,\n tf.__internal__.distribute.combinations.one_device_strategy,\n tf.__internal__.distribute.combinations.one_device_strategy_gpu,\n tf.__internal__.distribute.combinations.mirrored_strategy_with_gpu_and_cpu,\n tf.__internal__.distribute.combinations.mirrored_strategy_with_two_gpus,\n tf.__internal__.distribute.combinations.multi_worker_mirrored_2x1_cpu,\n tf.__internal__.distribute.combinations.multi_worker_mirrored_2x1_gpu,\n tf.__internal__.distribute.combinations.multi_worker_mirrored_2x2_gpu,\n # NOTE: TPUStrategy not tested because the models in this test are\n # sparse and do not work with TPUs.\n ],\n mode=['eager'],\n data_fn=['numpy', 'dataset'])\n\n\ndef get_numpy():\n inputs = np.random.uniform(low=-5, high=5, size=(64, 2)).astype(np.float32)\n output = .3 * inputs[:, 0] + .2 * inputs[:, 1]\n return inputs, output\n\n\ndef get_dataset():\n inputs, output = get_numpy()\n dataset = tf.data.Dataset.from_tensor_slices((inputs, output))\n dataset = dataset.batch(10).repeat(10)\n return dataset\n\n\nclass KerasPremadeModelsTest(tf.test.TestCase, parameterized.TestCase):\n\n @tf.__internal__.distribute.combinations.generate(strategy_combinations_eager_data_fn())\n def test_linear_model(self, distribution, data_fn):\n with distribution.scope():\n model = linear.LinearModel()\n opt = gradient_descent.SGD(learning_rate=0.1)\n model.compile(opt, 'mse')\n if data_fn == 'numpy':\n inputs, output = get_numpy()\n hist = model.fit(inputs, output, epochs=5)\n else:\n hist = model.fit(get_dataset(), epochs=5)\n self.assertLess(hist.history['loss'][4], 0.2)\n\n @tf.__internal__.distribute.combinations.generate(strategy_combinations_eager_data_fn())\n def test_wide_deep_model(self, distribution, data_fn):\n with distribution.scope():\n linear_model = linear.LinearModel(units=1)\n dnn_model = sequential.Sequential([core.Dense(units=1)])\n wide_deep_model = wide_deep.WideDeepModel(linear_model, dnn_model)\n linear_opt = gradient_descent.SGD(learning_rate=0.05)\n dnn_opt = adagrad.Adagrad(learning_rate=0.1)\n wide_deep_model.compile(\n optimizer=[linear_opt, dnn_opt],\n loss='mse')\n if data_fn == 'numpy':\n inputs, output = get_numpy()\n hist = wide_deep_model.fit(inputs, output, epochs=5)\n else:\n hist = wide_deep_model.fit(get_dataset(), epochs=5)\n self.assertLess(hist.history['loss'][4], 0.2)\n\n\nif __name__ == '__main__':\n tf.__internal__.distribute.multi_process_runner.test_main()\n",
"# Copyright 2018 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for compiled Model subclassing.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nimport os\n\nimport numpy as np\n\nimport keras\nfrom keras import keras_parameterized\nfrom keras import testing_utils\nfrom keras.tests import model_subclassing_test_util as model_util\n\ntry:\n import h5py # pylint:disable=g-import-not-at-top\nexcept ImportError:\n h5py = None\n\n\n@keras_parameterized.run_all_keras_modes\nclass ModelSubclassCompiledTest(keras_parameterized.TestCase):\n\n def test_single_io_workflow_with_np_arrays(self):\n num_classes = 2\n num_samples = 100\n input_dim = 50\n\n model = testing_utils.SmallSubclassMLP(\n num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n metrics=['acc', keras.metrics.CategoricalAccuracy()],\n run_eagerly=testing_utils.should_run_eagerly())\n\n x = np.ones((num_samples, input_dim))\n y = np.zeros((num_samples, num_classes))\n\n model.fit(x, y, epochs=2, batch_size=32, verbose=0)\n _ = model.evaluate(x, y, verbose=0)\n\n def test_multi_io_workflow_with_np_arrays(self):\n num_classes = (2, 3)\n num_samples = 1000\n input_dim = 50\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_dp=True, use_bn=True)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n metrics=['acc'],\n run_eagerly=testing_utils.should_run_eagerly())\n\n x1 = np.ones((num_samples, input_dim))\n x2 = np.ones((num_samples, input_dim))\n y1 = np.zeros((num_samples, num_classes[0]))\n y2 = np.zeros((num_samples, num_classes[1]))\n\n model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0)\n _ = model.evaluate([x1, x2], [y1, y2], verbose=0)\n\n def test_single_io_workflow_with_datasets(self):\n num_classes = 2\n num_samples = 10\n input_dim = 50\n\n with self.cached_session():\n model = testing_utils.SmallSubclassMLP(\n num_hidden=32, num_classes=num_classes, use_dp=True, use_bn=True)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n\n x = np.ones((num_samples, input_dim), dtype=np.float32)\n y = np.zeros((num_samples, num_classes), dtype=np.float32)\n dataset = tf.data.Dataset.from_tensor_slices((x, y))\n dataset = dataset.repeat(100)\n dataset = dataset.batch(10)\n\n model.fit(dataset, epochs=2, steps_per_epoch=10, verbose=0)\n _ = model.evaluate(dataset, steps=10, verbose=0)\n\n def test_attributes(self):\n # layers, weights, trainable_weights, non_trainable_weights, inputs, outputs\n\n num_classes = (2, 3)\n num_samples = 100\n input_dim = 50\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_bn=True)\n\n x1 = np.ones((num_samples, input_dim))\n x2 = np.ones((num_samples, input_dim))\n y1 = np.zeros((num_samples, num_classes[0]))\n y2 = np.zeros((num_samples, num_classes[1]))\n\n self.assertEqual(model.name, 'test_model')\n self.assertEqual(model.built, False)\n self.assertEqual(len(model.weights), 0)\n\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n model.train_on_batch([x1, x2], [y1, y2])\n\n self.assertEqual(model.built, True)\n self.assertEqual(len(model.layers), 4)\n self.assertEqual(len(model.weights), 10)\n self.assertEqual(len(model.trainable_weights), 8)\n self.assertEqual(len(model.non_trainable_weights), 2)\n\n def test_updates(self):\n # test that updates get run during training\n num_samples = 100\n input_dim = 50\n\n class BNNet(keras.Model):\n\n def __init__(self):\n super(BNNet, self).__init__()\n self.bn = keras.layers.BatchNormalization(beta_initializer='ones',\n gamma_initializer='ones')\n\n def call(self, inputs):\n return self.bn(inputs)\n\n x = np.ones((num_samples, input_dim))\n y = np.ones((num_samples, input_dim))\n\n model = BNNet()\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n y_ref = model.predict(x)\n\n model.train_on_batch(x, y)\n y_new = model.predict(x)\n self.assertGreater(np.sum(np.abs(y_ref - y_new)), 0.1)\n\n def test_training_and_inference_behavior(self):\n # test that dropout is applied in training and not inference\n\n num_samples = 100\n input_dim = 50\n\n class DPNet(keras.Model):\n\n def __init__(self):\n super(DPNet, self).__init__()\n self.dp = keras.layers.Dropout(0.5)\n self.dense = keras.layers.Dense(1,\n use_bias=False,\n kernel_initializer='ones')\n\n def call(self, inputs):\n x = self.dp(inputs)\n return self.dense(x)\n\n model = DPNet()\n x = np.ones((num_samples, input_dim))\n y = model.predict(x)\n self.assertEqual(np.sum(y), np.sum(x))\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n loss = model.train_on_batch(x, y)\n self.assertGreater(loss, 0.1)\n\n def test_training_methods(self):\n # test fit, train_on_batch\n # on different input types: list, dict\n\n num_classes = (2, 3)\n num_samples = 100\n input_dim = 50\n\n x1 = np.ones((num_samples, input_dim))\n x2 = np.ones((num_samples, input_dim))\n y1 = np.zeros((num_samples, num_classes[0]))\n y2 = np.zeros((num_samples, num_classes[1]))\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_bn=True)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0)\n model.fit({'input_1': x1, 'input_2': x2},\n {'output_1': y1, 'output_2': y2},\n epochs=2, batch_size=32)\n model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0,\n validation_data=([x1, x2], [y1, y2]))\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_bn=True)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n model.train_on_batch([x1, x2], [y1, y2])\n model.train_on_batch({'input_1': x1, 'input_2': x2},\n {'output_1': y1, 'output_2': y2})\n\n def test_inference_methods(self):\n # test predict, evaluate, test_on_batch, predict_on_batch\n # on different input types: list, dict\n num_classes = (2, 3)\n num_samples = 100\n input_dim = 50\n\n x1 = np.ones((num_samples, input_dim))\n x2 = np.ones((num_samples, input_dim))\n y1 = np.zeros((num_samples, num_classes[0]))\n y2 = np.zeros((num_samples, num_classes[1]))\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_bn=True)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n model.evaluate([x1, x2], [y1, y2])\n model.test_on_batch([x1, x2], [y1, y2])\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_bn=True)\n model.predict([x1, x2])\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_bn=True)\n model.predict_on_batch([x1, x2])\n\n def test_saving(self):\n num_classes = (2, 3)\n num_samples = 100\n input_dim = 50\n\n x1 = np.ones((num_samples, input_dim))\n x2 = np.ones((num_samples, input_dim))\n y1 = np.zeros((num_samples, num_classes[0]))\n y2 = np.zeros((num_samples, num_classes[1]))\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_bn=True)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n model.fit([x1, x2], [y1, y2], epochs=2, batch_size=32, verbose=0)\n y_ref_1, y_ref_2 = model.predict([x1, x2])\n\n tf_format_name = os.path.join(self.get_temp_dir(), 'ckpt')\n model.save_weights(tf_format_name)\n if h5py is not None:\n hdf5_format_name = os.path.join(self.get_temp_dir(), 'weights.h5')\n model.save_weights(hdf5_format_name)\n\n model = model_util.get_multi_io_subclass_model(\n num_classes=num_classes, use_bn=True)\n\n if h5py is not None:\n with self.assertRaises(ValueError):\n model.load_weights(hdf5_format_name)\n\n model.load_weights(tf_format_name)\n\n y1, y2 = model.predict([x1, x2])\n self.assertAllClose(y_ref_1, y1, atol=1e-5)\n self.assertAllClose(y_ref_2, y2, atol=1e-5)\n\n if h5py is not None:\n model.load_weights(hdf5_format_name)\n\n y1, y2 = model.predict([x1, x2])\n self.assertAllClose(y_ref_1, y1, atol=1e-5)\n self.assertAllClose(y_ref_2, y2, atol=1e-5)\n\n def test_subclass_nested_in_subclass(self):\n num_classes = 2\n num_samples = 100\n input_dim = 50\n\n model = model_util.NestedTestModel1(num_classes=num_classes)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n metrics=['acc'],\n run_eagerly=testing_utils.should_run_eagerly())\n\n x = np.ones((num_samples, input_dim))\n y = np.zeros((num_samples, num_classes))\n\n model.fit(x, y, epochs=2, batch_size=32, verbose=0)\n _ = model.evaluate(x, y, verbose=0)\n\n self.assertEqual(len(model.weights), 8 + len(model.test_net.weights))\n self.assertEqual(len(model.non_trainable_weights),\n 2 + len(model.test_net.non_trainable_weights))\n self.assertEqual(len(model.trainable_weights),\n 6 + len(model.test_net.trainable_weights))\n\n def test_graph_nested_in_subclass(self):\n num_classes = 2\n num_samples = 100\n input_dim = 50\n\n model = model_util.NestedTestModel2(num_classes=num_classes)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n metrics=['acc'],\n run_eagerly=testing_utils.should_run_eagerly())\n\n x = np.ones((num_samples, input_dim))\n y = np.zeros((num_samples, num_classes))\n\n model.fit(x, y, epochs=2, batch_size=32, verbose=0)\n _ = model.evaluate(x, y, verbose=0)\n\n self.assertEqual(len(model.weights), 8 + len(model.test_net.weights))\n self.assertEqual(len(model.non_trainable_weights),\n 2 + len(model.test_net.non_trainable_weights))\n self.assertEqual(len(model.trainable_weights),\n 6 + len(model.test_net.trainable_weights))\n\n def test_subclass_nested_in_graph(self):\n num_classes = 2\n num_samples = 100\n input_dim = 50\n\n model = model_util.get_nested_model_3(\n input_dim=input_dim, num_classes=num_classes)\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n metrics=['acc'],\n run_eagerly=testing_utils.should_run_eagerly())\n\n x = np.ones((num_samples, input_dim))\n y = np.zeros((num_samples, num_classes))\n\n model.fit(x, y, epochs=2, batch_size=32, verbose=0)\n _ = model.evaluate(x, y, verbose=0)\n\n self.assertEqual(len(model.weights), 16)\n self.assertEqual(len(model.non_trainable_weights), 4)\n self.assertEqual(len(model.trainable_weights), 12)\n\n def test_subclass_nested_in_sequential(self):\n num_classes = 2\n num_samples = 100\n input_dim = 50\n\n class Inner(keras.Model):\n\n def __init__(self):\n super(Inner, self).__init__()\n self.dense1 = keras.layers.Dense(32, activation='relu')\n self.dense2 = keras.layers.Dense(num_classes, activation='relu')\n self.bn = keras.layers.BatchNormalization()\n\n def call(self, inputs):\n x = self.dense1(inputs)\n x = self.dense2(x)\n return self.bn(x)\n\n model = keras.Sequential([Inner()])\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n metrics=['acc'],\n run_eagerly=testing_utils.should_run_eagerly())\n\n x = np.ones((num_samples, input_dim))\n y = np.zeros((num_samples, num_classes))\n model.fit(x, y, epochs=2, batch_size=32, verbose=0)\n _ = model.evaluate(x, y, verbose=0)\n\n self.assertEqual(len(model.weights), 8)\n self.assertEqual(len(model.non_trainable_weights), 2)\n self.assertEqual(len(model.trainable_weights), 6)\n\n def test_support_for_manual_training_arg(self):\n # In most cases, the `training` argument is left unspecified, in which\n # case it defaults to value corresponding to the Model method being used\n # (fit -> True, predict -> False, etc).\n # If the user writes their model `call` method to take\n # an explicit `training` argument, we must check that the correct value\n # is being passed to the model for each method call.\n\n class DPNet(keras.Model):\n\n def __init__(self):\n super(DPNet, self).__init__()\n self.dp = keras.layers.Dropout(0.5)\n self.dense = keras.layers.Dense(1,\n use_bias=False,\n kernel_initializer='ones')\n\n def call(self, inputs, training=False):\n x = self.dp(inputs, training=training)\n return self.dense(x)\n\n model = DPNet()\n x = np.ones((10, 10))\n y = model.predict(x)\n self.assertEqual(np.sum(y), np.sum(x))\n model.compile(\n loss='mse',\n optimizer='rmsprop',\n run_eagerly=testing_utils.should_run_eagerly())\n loss = model.train_on_batch(x, y)\n self.assertGreater(loss, 0.1)\n\n\nif __name__ == '__main__':\n tf.test.main()\n",
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Test MirroredVariable in MirroredStrategy and MultiWorkerMirroredStrategy.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nfrom tensorflow.python.distribute import combinations as ds_combinations\nfrom tensorflow.python.distribute import distribute_utils\nfrom keras.layers import core\n\n\ndef _mimic_two_cpus():\n cpus = tf.config.list_physical_devices(\"CPU\")\n\n tf.config.set_logical_device_configuration(cpus[0], [\n tf.config.LogicalDeviceConfiguration(),\n tf.config.LogicalDeviceConfiguration(),\n ])\n\n\n@tf.__internal__.distribute.combinations.generate(\n tf.__internal__.test.combinations.combine(\n distribution=[\n tf.__internal__.distribute.combinations.mirrored_strategy_with_gpu_and_cpu,\n ds_combinations.NamedDistribution(\n \"Collective2CPUs\",\n # pylint: disable=g-long-lambda\n lambda: tf.distribute.\n MultiWorkerMirroredStrategy._from_local_devices((\n \"/device:CPU:0\", \"/device:CPU:1\")),\n required_gpus=0)\n ],\n mode=[\"graph\", \"eager\"]))\nclass MirroredVariableCreationTest(tf.test.TestCase):\n \"\"\"Base class that tests mirrored variable creator.\n\n Currently it assumes all strategy objects have two replicas.\n \"\"\"\n\n @classmethod\n def setUpClass(cls):\n _mimic_two_cpus()\n\n def assertAllDifferent(self, objs):\n for i in range(len(objs)):\n for j in range(len(objs)):\n if i == j:\n continue\n self.assertIsNot(objs[i], objs[j])\n\n def testWithLayers(self, distribution):\n\n def model_fn(features):\n\n layer1 = core.Dense(1)\n layer1(features)\n layer2 = core.Dense(1)\n layer2(features)\n # We rely on names and orders to make sure replica references the same\n # MirroredVariable. Uniquifying names may involve global states,\n # merge_call switches threads so we need to test things work after\n # merge_call.\n tf.distribute.get_replica_context().merge_call(lambda _: _)\n layer3 = core.Dense(1)\n layer3(features)\n return [(layer1.kernel, layer1.bias), (layer2.kernel, layer2.bias),\n (layer3.kernel, layer3.bias)]\n\n iterator = distribution.make_input_fn_iterator(\n lambda _: tf.data.Dataset.from_tensors([[1.]]).repeat(10))\n self.evaluate(iterator.initializer)\n features = iterator.get_next()\n\n with distribution.scope():\n result = distribution.extended.call_for_each_replica(\n model_fn, args=(features,))\n for kernel, bias in result:\n self.assertTrue(distribute_utils.is_mirrored(kernel))\n self.assertAllDifferent(distribution.experimental_local_results(kernel))\n self.assertTrue(distribute_utils.is_mirrored(bias))\n self.assertAllDifferent(distribution.experimental_local_results(kernel))\n\n\nif __name__ == \"__main__\":\n tf.test.main()\n",
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tests for custom training loops.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nimport keras\nfrom keras import keras_parameterized\nfrom keras import testing_utils\n\n\nclass LayerWithLosses(keras.layers.Layer):\n\n def build(self, input_shape):\n self.v = self.add_weight(\n name='hey',\n shape=(),\n initializer='ones',\n regularizer=keras.regularizers.l1(100))\n\n def call(self, inputs):\n self.add_loss(tf.reduce_sum(inputs))\n return self.v * inputs\n\n\nclass LayerWithMetrics(keras.layers.Layer):\n\n def build(self, input_shape):\n self.mean = keras.metrics.Mean(name='mean_object')\n\n def call(self, inputs):\n self.add_metric(\n tf.reduce_mean(inputs), name='mean_tensor', aggregation='mean')\n self.add_metric(self.mean(inputs))\n return inputs\n\n\nclass LayerWithTrainingArg(keras.layers.Layer):\n\n def call(self, inputs, training=None):\n self.training = training\n if training:\n return inputs\n else:\n return 0. * inputs\n\n\ndef add_loss_step(defun):\n optimizer = keras.optimizer_v2.adam.Adam()\n model = testing_utils.get_model_from_layers([LayerWithLosses()],\n input_shape=(10,))\n\n def train_step(x):\n with tf.GradientTape() as tape:\n model(x)\n assert len(model.losses) == 2\n loss = tf.reduce_sum(model.losses)\n gradients = tape.gradient(loss, model.trainable_weights)\n optimizer.apply_gradients(zip(gradients, model.trainable_weights))\n return loss\n\n if defun:\n train_step = tf.function(train_step)\n\n x = tf.ones((10, 10))\n return train_step(x)\n\n\ndef batch_norm_step(defun):\n optimizer = keras.optimizer_v2.adadelta.Adadelta()\n model = testing_utils.get_model_from_layers([\n keras.layers.BatchNormalization(momentum=0.9),\n keras.layers.Dense(1, kernel_initializer='zeros', activation='softmax')\n ],\n input_shape=(10,))\n\n def train_step(x, y):\n with tf.GradientTape() as tape:\n y_pred = model(x, training=True)\n loss = keras.losses.binary_crossentropy(y, y_pred)\n gradients = tape.gradient(loss, model.trainable_weights)\n optimizer.apply_gradients(zip(gradients, model.trainable_weights))\n return loss, model(x, training=False)\n\n if defun:\n train_step = tf.function(train_step)\n\n x, y = tf.ones((10, 10)), tf.ones((10, 1))\n return train_step(x, y)\n\n\ndef add_metric_step(defun):\n optimizer = keras.optimizer_v2.rmsprop.RMSprop()\n model = testing_utils.get_model_from_layers([\n LayerWithMetrics(),\n keras.layers.Dense(1, kernel_initializer='zeros', activation='softmax')\n ],\n input_shape=(10,))\n\n def train_step(x, y):\n with tf.GradientTape() as tape:\n y_pred_1 = model(x)\n y_pred_2 = model(2 * x)\n y_pred = y_pred_1 + y_pred_2\n loss = keras.losses.mean_squared_error(y, y_pred)\n gradients = tape.gradient(loss, model.trainable_weights)\n optimizer.apply_gradients(zip(gradients, model.trainable_weights))\n assert len(model.metrics) == 2\n return [m.result() for m in model.metrics]\n\n if defun:\n train_step = tf.function(train_step)\n\n x, y = tf.ones((10, 10)), tf.zeros((10, 1))\n metrics = train_step(x, y)\n assert np.allclose(metrics[0], 1.5)\n assert np.allclose(metrics[1], 1.5)\n return metrics\n\n\n@keras_parameterized.run_with_all_model_types\nclass CustomTrainingLoopTest(keras_parameterized.TestCase):\n\n @parameterized.named_parameters(('add_loss_step', add_loss_step),\n ('add_metric_step', add_metric_step),\n ('batch_norm_step', batch_norm_step))\n def test_eager_and_tf_function(self, train_step):\n eager_result = train_step(defun=False)\n fn_result = train_step(defun=True)\n self.assertAllClose(eager_result, fn_result)\n\n @parameterized.named_parameters(('eager', False), ('defun', True))\n def test_training_arg_propagation(self, defun):\n\n model = testing_utils.get_model_from_layers([LayerWithTrainingArg()],\n input_shape=(1,))\n\n def train_step(x):\n return model(x), model(x, training=False), model(x, training=True)\n\n if defun:\n train_step = tf.function(train_step)\n\n x = tf.ones((1, 1))\n results = train_step(x)\n self.assertAllClose(results[0], tf.zeros((1, 1)))\n self.assertAllClose(results[1], tf.zeros((1, 1)))\n self.assertAllClose(results[2], tf.ones((1, 1)))\n\n @parameterized.named_parameters(('eager', False), ('defun', True))\n def test_learning_phase_propagation(self, defun):\n\n class MyModel(keras.layers.Layer):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.layer = LayerWithTrainingArg()\n\n def call(self, inputs):\n return self.layer(inputs)\n\n model = MyModel()\n\n def train_step(x):\n no_learning_phase_out = model(x)\n self.assertFalse(model.layer.training)\n with keras.backend.learning_phase_scope(0):\n inf_learning_phase_out = model(x)\n self.assertEqual(model.layer.training, 0)\n with keras.backend.learning_phase_scope(1):\n train_learning_phase_out = model(x)\n self.assertEqual(model.layer.training, 1)\n return [\n no_learning_phase_out, inf_learning_phase_out,\n train_learning_phase_out\n ]\n\n if defun:\n train_step = tf.function(train_step)\n\n x = tf.ones((1, 1))\n results = train_step(x)\n self.assertAllClose(results[0], tf.zeros((1, 1)))\n self.assertAllClose(results[1], tf.zeros((1, 1)))\n self.assertAllClose(results[2], tf.ones((1, 1)))\n\n @parameterized.named_parameters(('eager', False), ('defun', True))\n def test_training_arg_priorities(self, defun):\n\n class MyModel(keras.layers.Layer):\n\n def __init__(self):\n super(MyModel, self).__init__()\n self.layer = LayerWithTrainingArg()\n\n def call(self, inputs, training=False):\n return self.layer(inputs)\n\n model = MyModel()\n\n def train_step(x):\n explicit_out = model(x, training=True)\n default_out = model(x)\n with keras.backend.learning_phase_scope(1):\n parent_out = model(x, training=False)\n lr_out = model(x)\n return [explicit_out, default_out, parent_out, lr_out]\n\n if defun:\n train_step = tf.function(train_step)\n\n x = tf.ones((1, 1))\n results = train_step(x)\n self.assertAllClose(results[0], tf.ones((1, 1)))\n self.assertAllClose(results[1], tf.zeros((1, 1)))\n self.assertAllClose(results[2], tf.zeros((1, 1)))\n self.assertAllClose(results[3], tf.ones((1, 1)))\n\n\nif __name__ == '__main__':\n tf.compat.v1.enable_eager_execution()\n tf.test.main()\n",
"# Copyright 2020 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Keras string lookup preprocessing layer.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom keras.engine import base_preprocessing_layer\nfrom keras.layers.preprocessing import index_lookup_v1\nfrom keras.layers.preprocessing import string_lookup\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export(v1=[\"keras.layers.experimental.preprocessing.StringLookup\"])\nclass StringLookup(string_lookup.StringLookup, index_lookup_v1.IndexLookup):\n \"\"\"Maps strings from a vocabulary to integer indices.\"\"\"\n\n def __init__(self,\n max_tokens=None,\n num_oov_indices=1,\n mask_token=\"\",\n oov_token=\"[UNK]\",\n vocabulary=None,\n encoding=None,\n invert=False,\n **kwargs):\n super(StringLookup, self).__init__(\n max_tokens=max_tokens,\n num_oov_indices=num_oov_indices,\n mask_token=mask_token,\n oov_token=oov_token,\n vocabulary=vocabulary,\n invert=invert,\n **kwargs)\n base_preprocessing_layer.keras_kpl_gauge.get_cell(\n \"StringLookup_V1\").set(True)\n",
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n# ==============================================================================\n\"\"\"Tensorflow V1 version of the Discretization preprocessing layer.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom keras.engine import base_preprocessing_layer\nfrom keras.engine.base_preprocessing_layer_v1 import CombinerPreprocessingLayer\nfrom keras.layers.preprocessing import discretization\nfrom tensorflow.python.util.tf_export import keras_export\n\n\n@keras_export(v1=['keras.layers.experimental.preprocessing.Discretization'])\nclass Discretization(discretization.Discretization, CombinerPreprocessingLayer):\n base_preprocessing_layer.keras_kpl_gauge.get_cell(\n 'Discretization_V1').set(True)\n pass\n"
] |
[
[
"tensorflow.__internal__.distribute.multi_process_runner.test_main",
"tensorflow.data.Dataset.from_tensor_slices",
"numpy.random.uniform",
"tensorflow.__internal__.test.combinations.combine"
],
[
"numpy.abs",
"tensorflow.data.Dataset.from_tensor_slices",
"tensorflow.test.main",
"numpy.ones",
"numpy.zeros",
"numpy.sum"
],
[
"tensorflow.data.Dataset.from_tensors",
"tensorflow.config.LogicalDeviceConfiguration",
"tensorflow.distribute.get_replica_context",
"tensorflow.test.main",
"tensorflow.python.distribute.distribute_utils.is_mirrored",
"tensorflow.config.list_physical_devices",
"tensorflow.distribute.MultiWorkerMirroredStrategy._from_local_devices"
],
[
"numpy.allclose",
"tensorflow.zeros",
"tensorflow.reduce_mean",
"tensorflow.reduce_sum",
"tensorflow.compat.v1.enable_eager_execution",
"tensorflow.test.main",
"tensorflow.ones",
"tensorflow.function",
"tensorflow.GradientTape"
],
[
"tensorflow.python.util.tf_export.keras_export"
],
[
"tensorflow.python.util.tf_export.keras_export"
]
] |
jseltmann/vision-based-language
|
[
"c89e9309ca2cb7335136411771f1f34d81c3d53a"
] |
[
"eval_binary/bert/eval_bert_log_reg.py"
] |
[
"import spacy\nimport pickle\nimport gensim.downloader\nimport numpy as np\nimport transformers as tr\nimport torch\n\nclass BERT_log_reg_classifier:\n def __init__(self, trained_path):\n with open(trained_path, \"rb\") as clsf:\n self.classifier = pickle.load(clsf)\n if torch.cuda.is_available():\n self.device = \"cuda\"\n else:\n self.device = \"cpu\"\n self.tok = tr.BertTokenizer.from_pretrained('bert-base-uncased')\n self.bert = tr.BertModel.from_pretrained('bert-base-uncased')\n self.bert.to(self.device)\n\n def classify(self, example):\n svs = []\n for sent in example:\n inputs = self.tok(sent, return_tensors='pt')\n inputs.to(self.device)\n outputs = self.bert(**inputs).pooler_output\n outputs = np.array(outputs.cpu().detach())\n svs.append(outputs)\n combinedv = np.append(svs[0], [svs[1]])\n combinedv = np.expand_dims(combinedv, axis=0)\n outp = self.classifier.predict(combinedv)\n return outp\n"
] |
[
[
"numpy.append",
"numpy.expand_dims",
"torch.cuda.is_available"
]
] |
mhaminh/graphnet
|
[
"ef74573c259cd25868d0b26f17a7f86502ec2ffc"
] |
[
"src/graphnet/models/training/utils.py"
] |
[
"from collections import OrderedDict\nimport os\nfrom typing import List, Optional, Tuple\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nimport torch\nfrom torch.utils.data import DataLoader\nfrom torch_geometric.data.batch import Batch\n\nfrom graphnet.data.sqlite_dataset import SQLiteDataset\nfrom graphnet.models import Model\n\n\ndef make_dataloader(\n db: str,\n pulsemap: str,\n features: List[str],\n truth: List[str],\n *,\n batch_size: int,\n shuffle: bool,\n selection: List[int] = None,\n num_workers: int = 10,\n persistent_workers: bool = True,\n) -> DataLoader:\n\n dataset = SQLiteDataset(\n db,\n pulsemap,\n features,\n truth,\n selection=selection,\n )\n\n def collate_fn(graphs):\n # Remove graphs with less than two DOM hits. Should not occur in \"production.\"\n graphs = [g for g in graphs if g.n_pulses > 1]\n return Batch.from_data_list(graphs)\n\n dataloader = DataLoader(\n dataset,\n batch_size=batch_size,\n shuffle=shuffle,\n num_workers=num_workers,\n collate_fn=collate_fn,\n persistent_workers=persistent_workers,\n prefetch_factor=2,\n )\n\n return dataloader\n\ndef make_train_validation_dataloader(\n db: str,\n selection: List[int],\n pulsemap: str,\n features: List[str],\n truth: List[str],\n *,\n batch_size: int,\n database_indices: List[int] = None,\n seed: int = 42,\n test_size: float = 0.33,\n num_workers: int = 10,\n persistent_workers: bool = True,\n) -> Tuple[DataLoader]:\n\n # Reproducibility\n rng = np.random.RandomState(seed=seed)\n\n # Perform train/validation split\n if isinstance(db, list):\n df_for_shuffle = pd.DataFrame({'event_no': selection, 'db': database_indices})\n shuffled_df = df_for_shuffle.sample(frac=1, replace=False, random_state=rng)\n training_df, validation_df = train_test_split(shuffled_df, test_size=test_size, random_state=rng)\n training_selection = training_df.values.tolist()\n validation_selection = validation_df.values.tolist()\n else:\n training_selection, validation_selection = train_test_split(selection, test_size=test_size, random_state=rng)\n\n # Create DataLoaders\n common_kwargs = dict(\n db=db,\n pulsemap=pulsemap,\n features=features,\n truth=truth,\n batch_size=batch_size,\n num_workers=num_workers,\n persistent_workers=persistent_workers,\n )\n\n training_dataloader = make_dataloader(\n shuffle=True,\n selection=training_selection,\n **common_kwargs,\n )\n\n validation_dataloader = make_dataloader(\n shuffle=False,\n selection=validation_selection,\n **common_kwargs,\n )\n\n return training_dataloader, validation_dataloader # , {'valid_selection':validation_selection, 'training_selection':training_selection}\n\ndef get_predictions(trainer, model, dataloader, prediction_columns, additional_attributes=None):\n # Check(s)\n if additional_attributes is None:\n additional_attributes = []\n assert isinstance(additional_attributes, list)\n\n # Get predictions\n predictions_torch = trainer.predict(model, dataloader)\n predictions = [p[0].detach().cpu().numpy() for p in predictions_torch] # Assuming single task\n predictions = np.concatenate(predictions, axis=0)\n assert len(prediction_columns) == predictions.shape[1]\n\n # Get additional attributes\n attributes = OrderedDict([(attr, []) for attr in additional_attributes])\n for batch in dataloader:\n for attr in attributes:\n attributes[attr].extend(batch[attr].detach().cpu().numpy())\n\n data = np.concatenate([predictions] + [\n np.asarray(values)[:, np.newaxis] for values in attributes.values()\n ], axis=1)\n\n results = pd.DataFrame(data, columns=prediction_columns + additional_attributes)\n return results\n\ndef save_results(db, tag, results, archive,model):\n db_name = db.split('/')[-1].split('.')[0]\n path = archive + '/' + db_name + '/' + tag\n os.makedirs(path, exist_ok = True)\n results.to_csv(path + '/results.csv')\n torch.save(model.cpu().state_dict(), path + '/' + tag + '.pth')\n print('Results saved at: \\n %s'%path)\n\ndef load_model(db, tag, archive, detector, gnn, task, device):\n db_name = db.split('/')[-1].split('.')[0]\n path = archive + '/' + db_name + '/' + tag\n model = Model(\n detector=detector,\n gnn=gnn,\n tasks=[task],\n device=device,\n )\n model.load_state_dict(torch.load(path + '/' + tag + '.pth'))\n model.eval()\n return model\n"
] |
[
[
"torch.load",
"numpy.asarray",
"torch.utils.data.DataLoader",
"sklearn.model_selection.train_test_split",
"pandas.DataFrame",
"numpy.concatenate",
"numpy.random.RandomState"
]
] |
chaojin0310/Federated-learning-tensorflow
|
[
"a202a95e3d04d46c1a2a347ef3209aa46087d13e"
] |
[
"models/cifar-100/squeezenet.py"
] |
[
"import tensorflow as tf\nimport numpy as np\n\nfrom model import Model\nfrom baseline_constants import ACCURACY_KEY\nfrom utils.model_utils import batch_data\n\n\n# IMAGE_SIZE = 224\nIMAGE_SIZE = 32\n\n\nclass ClientModel(Model):\n def __init__(self, seed, lr, num_classes):\n self.num_classes = num_classes\n super(ClientModel, self).__init__(seed, lr)\n\n def create_model(self):\n input_ph = tf.placeholder(tf.float32, shape=(None, IMAGE_SIZE, IMAGE_SIZE, 3))\n label_ph = tf.placeholder(tf.int64, shape=(None,))\n self.is_training = tf.placeholder(tf.bool)\n\n def fire(inputs, squeeze_channels, expand1_channels, expand3_channels, name):\n with tf.variable_scope(name):\n with tf.variable_scope('squeeze_layer'):\n squeeze_layer = tf.layers.conv2d(inputs, squeeze_channels, kernel_size=(1, 1), strides=(1, 1),\n padding='same')\n squeeze_layer = tf.layers.batch_normalization(squeeze_layer, training=self.is_training)\n squeeze_layer = tf.nn.relu(squeeze_layer)\n\n with tf.variable_scope('expand1_layer'):\n expand1_layer = tf.layers.conv2d(squeeze_layer, expand1_channels, kernel_size=(1, 1), strides=(1, 1),\n padding='same')\n expand1_layer = tf.layers.batch_normalization(expand1_layer, training=self.is_training)\n expand1_layer = tf.nn.relu(expand1_layer)\n \n with tf.variable_scope('expand3_layer'):\n expand3_layer = tf.layers.conv2d(squeeze_layer, expand3_channels, kernel_size=(3, 3), strides=(1, 1),\n padding='same')\n expand3_layer = tf.layers.batch_normalization(expand3_layer, training=self.is_training)\n expand3_layer = tf.nn.relu(expand3_layer)\n\n net = tf.concat([expand1_layer, expand3_layer], axis=3)\n return net\n\n net = tf.layers.conv2d(input_ph, 96, kernel_size=(7, 7), strides=(2, 2), padding='same', name='conv1')\n net = tf.layers.batch_normalization(net, training=self.is_training)\n net = tf.nn.relu(net)\n\n net = tf.layers.max_pooling2d(net, pool_size=(3, 3), strides=(2, 2), padding='valid', name='pool1')\n\n net = fire(net, 16, 64, 64, 'fire2')\n net = fire(net, 16, 64, 64, 'fire3')\n net = fire(net, 32, 128, 128, 'fire4')\n\n net = tf.layers.max_pooling2d(net, pool_size=(3, 3), strides=(2, 2), padding='valid', name='pool2')\n\n net = fire(net, 32, 128, 128, 'fire5')\n net = fire(net, 48, 192, 192, 'fire6')\n net = fire(net, 48, 192, 192, 'fire7')\n net = fire(net, 64, 256, 256, 'fire8')\n\n net = tf.layers.max_pooling2d(net, pool_size=(3, 3), strides=(2, 2), padding='valid', name='pool3')\n\n net = fire(net, 64, 256, 256, 'fire9')\n net = tf.layers.dropout(net, rate=0.5, training=self.is_training)\n\n net = tf.layers.conv2d(net, filters=self.num_classes,\n kernel_size=(1, 1), strides=(1, 1), padding='same', name='conv10')\n\n net_shape = net.get_shape().as_list()\n pooling_size = [net_shape[1], net_shape[2]]\n net = tf.layers.average_pooling2d(net, pooling_size, strides=(1, 1), padding='valid')\n\n logits = tf.layers.flatten(net)\n\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(labels=label_ph, logits=logits)\n predictions = tf.argmax(logits, axis=1)\n # train_op = self.optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)\n with tf.control_dependencies(update_ops): # ensure that update_ops executes before train_op\n train_op = self.optimizer.minimize(loss=loss, global_step=tf.train.get_global_step())\n eval_metric_ops = tf.count_nonzero(tf.equal(label_ph, predictions))\n return input_ph, label_ph, train_op, eval_metric_ops, tf.math.reduce_mean(loss)\n\n def process_x(self, raw_x_batch):\n x_batch = np.array(raw_x_batch, dtype=np.float32)\n batch_size = x_batch.size // (IMAGE_SIZE * IMAGE_SIZE * 3)\n x_batch = x_batch.reshape((batch_size, 3, IMAGE_SIZE, IMAGE_SIZE)).transpose(0, 2, 3, 1)\n return x_batch\n\n def process_y(self, raw_y_batch):\n y_batch = np.array(raw_y_batch, dtype=np.int64)\n return y_batch\n\n def run_epoch(self, data, batch_size):\n for batched_x, batched_y in batch_data(data, batch_size, seed=self.seed):\n input_data = self.process_x(batched_x)\n target_data = self.process_y(batched_y)\n\n with self.graph.as_default():\n self.sess.run(self.train_op,\n feed_dict={\n self.features: input_data,\n self.labels: target_data,\n self.is_training: True\n })\n\n def test(self, data):\n x_vecs = self.process_x(data['x'])\n labels = self.process_y(data['y'])\n with self.graph.as_default():\n tot_acc, loss = self.sess.run(\n [self.eval_metric_ops, self.loss],\n feed_dict={self.features: x_vecs, self.labels: labels, self.is_training: False}\n )\n acc = float(tot_acc) / x_vecs.shape[0]\n return {ACCURACY_KEY: acc, 'loss': loss}\n"
] |
[
[
"tensorflow.nn.relu",
"tensorflow.layers.conv2d",
"tensorflow.layers.flatten",
"tensorflow.layers.batch_normalization",
"tensorflow.concat",
"tensorflow.control_dependencies",
"tensorflow.get_collection",
"tensorflow.layers.dropout",
"tensorflow.equal",
"tensorflow.layers.max_pooling2d",
"tensorflow.placeholder",
"tensorflow.math.reduce_mean",
"tensorflow.train.get_global_step",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.layers.average_pooling2d",
"tensorflow.variable_scope",
"tensorflow.argmax",
"numpy.array"
]
] |
taiakindaniil/Python-Programming
|
[
"93df499fabd9d440cc1c485dd938ba5a58d9d157"
] |
[
"Lab-4/app.py"
] |
[
"from tkinter import *\nfrom config import *\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport util\n\nsymbols = [\"SBER\", \"GAZP\", \"TATN\", \"VTBR\", \"ALRS\", \"AFLT\", \"HYDR\", \"MOEX\", \"NLMK\", \"CHMF\", \"DSKY\", \"POLY\", \"YNDX\", \"AFKS\", \"LSRG\", \"LSNGP\", \"LKOH\", \"MTSS\", \"NVTK\", \"PIKK\"]\n\n# recovery methods\n# - winsoring method\ndef winsoring(data: list):\n data_copy = data.copy()\n prev_val = None; next_val = None\n for (i, x) in enumerate(data_copy):\n if x == None:\n j = i+1\n while j < len(data_copy):\n if data_copy[j] != None:\n next_val = data_copy[j]; break\n j += 1\n else:\n prev_val = x\n \n data_copy[i] = prev_val or next_val\n\n return data_copy\n\n# - linear approximation\ndef linear_approximation(data: list):\n data_copy = data.copy()\n\n indices = [i for i, x in enumerate(data_copy) if x == None]\n for i in indices:\n # find nearest indexes to get an approximation\n prv, nxt = util.find_nearest_indexes(data_copy, i)\n\n a, b = util.mnk([prv, nxt], [data_copy[prv], data_copy[nxt]])\n\n r_y = a*i + b\n data_copy[i] = r_y\n\n return data_copy\n\n# - correlation\ndef correlation(values1, values2):\n for i, _ in enumerate(values1):\n if values1[i] == None:\n if i == len(values1) - 1:\n p1 = values1[i - 1]\n v1 = values2[i - 1]\n v2 = values2[i]\n values1[i] = p1 * v1 / v2\n else:\n p2 = values1[i + 1]\n v1 = values2[i]\n v2 = values2[i + 1]\n values1[i] = p2 * v2 / v1\n elif values2[i] == None:\n if i == len(values2) - 1:\n p1 = values1[i - 1]\n p2 = values1[i]\n v1 = values2[i - 1]\n values2[i] = p1 * v1 / p2\n else:\n p1 = values1[i]\n p2 = values1[i + 1]\n v2 = values2[i + 1]\n values2[i] = p2 * v2 / p1\n return values1, values2\n\n# print(prices)\n# print(correlation(util.rand_remove(prices), prices))\n\n\n# smoothing methods\n# - moving average with windowing\n# https://wiki.loginom.ru/articles/windowing-method.html\ndef MAW(Y, k=2):\n n = len(Y)\n temp_Y = Y[0:k]\n for t in range(k, n):\n slice_Y = Y[t-k:t]\n temp_Y.append(sum(slice_Y) / len(slice_Y))\n return temp_Y\n\ndef WMA(data):\n data_copy = data.copy()\n\n # количество значений исходной функции для расчёта скользящего среднего\n n = 2\n\n for t in range(n, len(data)):\n sum_data = 0\n for i in range(n):\n sum_data += (n-i)*data[t-i]\n \n for i in range(n):\n data_copy[t] = (2 / (n * (n+1))) * sum_data\n\n return data_copy\n\n\n# print(prices)\n# print(WMA(prices))\n\ndef std_deviation(orig_data: list, data: list):\n n = len(data)\n avg = sum(data) / n\n summ = 0\n for i in range(n):\n summ += (data[i] - orig_data[i])**2\n return ((1/n) * summ) ** 0.5\n\ndef App():\n\n root = Tk()\n root.title(\"Начинающий Брокер\")\n root.geometry(\"500x200\")\n root.resizable(width=False, height=False)\n\n frame = Frame(root, bg=bg_color)\n frame.place(relwidth=1, relheight=1)\n\n def option_menu(data: list, default_value) -> StringVar:\n variable = StringVar(frame)\n variable.set(default_value)\n OptionMenu(frame, variable, *data).pack()\n return variable\n\n symbol_variable = option_menu(symbols, \"Select Ticket\")\n recovery_variable = option_menu([\"Winsoring\", \"Linear approximation\", \"Correlation\"], \"Select Recovery Method\")\n antialising_variable = option_menu([\"Moving Average\", \"Moving Average w/ Windowing\"], \"Select Anti-aliasing Method\")\n\n title = Label(frame, text=\"Select second ticker if you've selected Correlation recovery method.\", bg=bg_color)\n title.pack()\n\n symbol2_variable = option_menu(symbols, \"Select Ticket\")\n\n def build_click():\n symbol = symbol_variable.get()\n symbol2 = symbol2_variable.get()\n recovery = recovery_variable.get()\n antialising = antialising_variable.get()\n\n df = pd.read_csv(f\"./data/{symbol}.csv\", sep=';', names=['date', 'price', 'change', 'cap'])\n # prices for 18 months\n i=0\n prices = util.rand_remove(list(df['price'][i:i+18]))\n\n recovered_prices = []\n if recovery == \"Winsoring\":\n recovered_prices = winsoring(prices)\n elif recovery == \"Linear approximation\":\n recovered_prices = linear_approximation(prices)\n elif recovery == \"Correlation\":\n df = pd.read_csv(f\"./data/{symbol2}.csv\", sep=';', names=['date', 'price', 'change', 'cap'])\n # prices for 18 months\n i=0\n prices2 = util.rand_remove(list(df['price'][i:i+18]))\n recovered_prices = correlation(prices, prices2)[0]\n\n antialised_prices = []\n if antialising == \"Moving Average\":\n antialised_prices = MAW(recovered_prices, k=2)\n elif antialising == \"Moving Average w/ Windowing\":\n antialised_prices = WMA(recovered_prices)\n\n # show what we've done\n fig, axs = plt.subplots(3)\n axs[0].set_title(\"Initial data\")\n axs[0].plot(range(len(prices)), prices, color=\"#CE7A60\")\n axs[1].set_title(\"Recovered data\")\n axs[1].plot(range(len(recovered_prices)), recovered_prices, color=\"#CE7A60\")\n axs[2].set_title(\"Antialised data\")\n axs[2].plot(range(len(antialised_prices)), antialised_prices, color=\"#FE7A60\")\n\n plt.text(0.5, 0.5, f\"σ = {std_deviation(recovered_prices, antialised_prices)}\")\n\n fig.tight_layout()\n plt.show()\n\n build_btn = Button(frame, text=\"Build\", bg=bg_color, borderwidth=0, command=build_click)\n build_btn.pack()\n\n root.mainloop()\n\nif __name__ == \"__main__\":\n App()"
] |
[
[
"pandas.read_csv",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.show"
]
] |
Saidsp19/Intelligent-attendance-system-using-face-recognition
|
[
"d8e588f592d4b7d92756a31f6570464ee1e1bea6"
] |
[
"Attendence system/dict.py"
] |
[
"\"\"\"\r\n@author: Saikumar Dandla\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\n\r\nname_dict = {0:'Avinash R' ,\r\n 1:'Durgendra Pandey',\r\n 2:'Rokkam Hari Sankar',\r\n 3:'Adurti Sai Mahesh',\r\n 4:'Manish Pratap Singh',\r\n 5:'RVNK Neeraj',\r\n 6:'Saikumar D',\r\n 7:'Boora Shiva',\r\n 8:'Jated Vikas',\r\n 9:'Vinod G',\r\n }\r\n\r\nnp.save('name_dict.npy',name_dict) "
] |
[
[
"numpy.save"
]
] |
KariukiKirubi/computer-vision-ai-saturdays
|
[
"e18c7557bc29a00c0586411f019fd33d2eb5ebb4"
] |
[
"1stMonth{ImageManipulation}/Files/1contrast.py"
] |
[
"import numpy as np\nimport cv2\nimport math\n\nimg = cv2.imread('../Images/bottle.jpg', cv2.IMREAD_ANYCOLOR)\nheight = img.shape[0]\nwidth = img.shape[1]\n\ncontrast = 5\n\nfor i in np.arange(height):\n for j in np.arange(width):\n for k in range(0,3,1):\n a = img.item(i,j,k)\n b = math.ceil(a * contrast)\n if b > 255:\n b = 255\n img.itemset((i,j,k), b)\n\ncv2.imwrite('../Images/1contrast.jpg', img)\n\ncv2.imshow('image2',img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()"
] |
[
[
"numpy.arange"
]
] |
goomhow/stock-manage-xgboost
|
[
"04299b1a0503da7948c769fda1dc7d3b6508ed6f",
"04299b1a0503da7948c769fda1dc7d3b6508ed6f"
] |
[
"ml/xgboost_model/broadband_model.py",
"util/hcode.py"
] |
[
"from datetime import datetime\nimport numpy as np\nimport pandas as pd\nfrom sklearn import metrics, learning_curve, svm\nfrom sklearn.model_selection import *\nfrom sklearn.externals import joblib\nimport xgboost as xgb\nfrom xgboost.sklearn import XGBClassifier\nfrom xgboost.plotting import plot_importance\nimport matplotlib.pyplot as plt\n\ndef single_model_xgb(d_train, flag=\"label\"):\n X = d_train.drop(flag, axis=1).drop(\"PRD_INST_ID\", axis=1)\n y = d_train[flag]\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=7)\n\n model = xgb.XGBClassifier(learning_rate=0.01,\n n_estimators=5000,\n max_depth=5,\n min_child_weight=3,\n gamma=0.3,\n subsample=0.85,\n colsample_bytree=0.75,\n objective='binary:logistic',\n scale_pos_weight=200,\n seed=27,\n nthread=12,\n reg_alpha=0.0005,\n reg_lambda=0.0005)\n\n # model = xgb.XGBClassifier(learning_rate=0.03,\n # n_estimators=150,\n # max_depth=7,\n # min_child_weight=3,\n # gamma=0.3,\n # subsample=0.80,\n # colsample_bytree=0.80,\n # objective='binary:logistic',\n # scale_pos_weight=1,\n # seed=43343,\n # nthread=12,\n # reg_alpha=0.01)\n\n model.fit(X_train, y_train) # 94.62%\n y_pred = model.predict(X_test)\n accuracy = metrics.accuracy_score(y_test, y_pred)\n print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n print('auc:', metrics.roc_auc_score(y_test, y_pred))\n print('精确率Accuracy:', metrics.accuracy_score(y_test, y_pred))\n train_report = metrics.classification_report(y_test, y_pred)\n print(train_report)\n return model\n\n\ndef learning_curve_fun(model, X, y, title=None, cv=None):\n cv = ShuffleSplit(n_splits=100, test_size=0.2, random_state=0)\n title = \"xgboost learning rate\"\n plot_learning_curve(model, title, X, y, ylim=(0.7, 1.01), cv=cv, n_jobs=4)\n\n\ndef plot_learning_curve(estimator, title, X, y, ylim=None, cv=None, n_jobs=1,\n train_sizes=np.linspace(.1, 1.0, 5)):\n plt.figure()\n plt.title(title)\n if ylim is not None:\n plt.ylim(*ylim)\n plt.xlabel(\"Training examples\")\n plt.ylabel(\"Score\")\n\n train_sizes, train_scores, test_scores = learning_curve(\n estimator, X, y, cv=cv, n_jobs=n_jobs, train_sizes=train_sizes)\n train_scores_mean = np.mean(train_scores, axis=1)\n train_scores_std = np.std(train_scores, axis=1)\n test_scores_mean = np.mean(test_scores, axis=1)\n test_scores_std = np.std(test_scores, axis=1)\n plt.grid()\n\n plt.fill_between(train_sizes, train_scores_mean - train_scores_std,\n train_scores_mean + train_scores_std, alpha=0.1,\n color=\"r\")\n plt.fill_between(train_sizes, test_scores_mean - test_scores_std,\n test_scores_mean + test_scores_std, alpha=0.1, color=\"g\")\n plt.plot(train_sizes, train_scores_mean, 'o-', color=\"r\",\n label=\"Training score\")\n plt.plot(train_sizes, test_scores_mean, 'o-', color=\"g\",\n label=\"Cross-validation score\")\n\n plt.legend(loc=\"best\")\n plt.show()\n\n\ndef svm_model(d_train, flag=\"label\"):\n from sklearn.preprocessing import MinMaxScaler, Normalizer\n normal = Normalizer()\n scaler = MinMaxScaler()\n X = d_train.drop(flag, axis=1, inplace=False)\n y = d_train[flag]\n X = normal.fit(X, y).transform(X)\n X = scaler.fit(X, y).transform(X)\n seed = 7\n test_size = 0.33\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=seed)\n model = svm.SVC()\n model.fit(X_train, y_train)\n y_pred = model.predict(X_test)\n accuracy = metrics.accuracy_score(y_test, y_pred)\n print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n print('auc:', metrics.roc_auc_score(y_test, y_pred))\n print('精确率Accuracy:', metrics.accuracy_score(y_test, y_pred))\n train_report = metrics.classification_report(y_test, y_pred)\n print(train_report)\n return model\n\n\ndef param_search(d_train, flag='label'):\n X = d_train.drop(flag, axis=1).drop('PRD_INST_ID', axis=1)\n y = d_train[flag]\n seed = 7\n test_size = 0.33\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=test_size, random_state=seed)\n tuned_parameters = [{'max_depth': [5, 6, 7],\n 'n_estimators':[2000, 3000],\n 'scale_pos_weight':[20, 50, 200],\n 'subsample':[0.75, 0.85, 0.95],\n 'colsample_bytree':[0.75, 0.85, 0.95],\n }]\n scores = ['precision', 'recall']\n for score in scores:\n print(\"# Tuning hyper-parameters for %s\" % score)\n print()\n\n clf = GridSearchCV(XGBClassifier(\n learning_rate=0.01,\n min_child_weight=3,\n gamma=0.3,\n objective='binary:logistic',\n seed=27,\n nthread=12,\n reg_alpha=0.01),\n tuned_parameters,\n cv=5,\n scoring='%s_macro' % score)\n clf.fit(X_train, y_train)\n\n print(\"Best parameters set found on development set:\")\n print()\n print(clf.best_params_)\n print()\n print(\"Grid scores on development set:\")\n print()\n means = clf.cv_results_['mean_test_score']\n stds = clf.cv_results_['std_test_score']\n for mean, std, params in zip(means, stds, clf.cv_results_['params']):\n print(\"%0.3f (+/-%0.03f) for %r\"\n % (mean, std * 2, params))\n print()\n print(\"Detailed classification report:\")\n print()\n print(\"The model is trained on the full development set.\")\n print(\"The scores are computed on the full evaluation set.\")\n print()\n y_true, y_pred = y_test, clf.predict(X_test)\n print(metrics.classification_report(y_true, y_pred))\n print()\n\n\ndef parse(data):\n f0 = ['INV_AMT_ALL', 'PRO_I_DUR_ALL', 'PRO_FLUX_ALL','THSC','YWQF','CWQF']\n f2 = [i for i in data.columns if i[-1] == '2']\n f3 = [i for i in data.columns if i[-1] == '3']\n f0.extend(f2)\n f0.extend(f3)\n for k in f0:\n data[k] = pd.cut(data[k], 7, labels=list(range(0, 7))).astype(np.int16)\n return data\n\n\ndef predict_df(model, df_test='', label='label', pfname=\"broadband_predict.csv\"):\n if not isinstance(df_test, pd.DataFrame):\n print('*'*10+'LOAD DATA'+'*'*10)\n df_test = pd.read_csv(pfname)\n df_test = df_test[df_test[label] == 0]\n print('*' * 10 + 'LOAD MODEL' + '*' * 10)\n bst = joblib.load(model)\n X_test = df_test.drop(label, axis=1).drop(\"PRD_INST_ID\", axis=1)\n y_pred = bst.predict(X_test)\n y_test_pred1 = bst.predict_proba(X_test)\n out = pd.DataFrame(\n {\n 'PRD_INST_ID': df_test[\"PRD_INST_ID\"].astype(np.int64),\n 'PREDICT': y_pred.astype(np.int32),\n 'POSSIBILITY': y_test_pred1[:, 1].astype(np.float)\n }\n )\n out = out[out['PREDICT'] == 1].sort_values(by=['PREDICT', 'POSSIBILITY'], ascending=False)\n out.to_csv(generate_filename(\"broadband_result{}.csv\"), header=True, index=None, )\n print(plot_importance(bst, max_num_features=20))\n return out\n\n\ndef generatorModel(data_file=\"broadband_train.csv\", save_file=None):\n data = pd.read_csv(data_file)\n model = single_model_xgb(data)\n if not save_file:\n save_file = generate_filename(\"broadband_xgb_{}.pkl\")\n joblib.dump(model, save_file)\n return save_file\n\n\ndef mixData(pfile,rfile,label='label', pfname=\"broadband_predict.csv\"):\n print('*' * 10 + 'LOAD DATA' + '*' * 10)\n df_test = pd.read_csv(pfname)\n df_test = df_test[df_test[label] == 0]\n precision_out = predict_df(pfile, df_test)\n recall_out = predict_df(rfile, df_test)\n ySet = set(precision_out['PRD_INST_ID'])\n another = recall_out.loc[lambda x:x.PRD_INST_ID not in ySet, :]\n append_size = 15000 - precision_out.shape[0]\n result = recall_out.append(another.iloc[:append_size, :])\n result.to_csv(generate_filename(\"broadband_mix{}.csv\"), header=True, index=None)\n return result\n\n\ndef generate_filename(fmt):\n date = datetime.now()\n date_str = date.strftime('%m%d%H%M')\n return fmt.format(date_str)\n\n\nd_train = pd.read_csv('dirbroadband_train.csv')\nX = d_train.drop('label', axis=1).drop(\"PRD_INST_ID\", axis=1)\ny = d_train['label']\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=7)\nparams = {'learning_rate':0.1,'n_estimators': 236, 'max_depth':6,'min_child_weight':3,'gamma':0.3,\n 'subsample':0.8,'colsample_bytree':0.8,'scale_pos_weight':200,'nthread':16,\n 'reg_alpha':0.01, 'reg_lambda':0.01}\n\n# def xgb_model(**kwargs):\n# model = xgb.XGBClassifier(**kwargs)\n# model.fit(X_train, y_train) # 94.62%\n# y_pred = model.predict(X_test)\n# accuracy = metrics.accuracy_score(y_test, y_pred)\n# print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n# print('auc:', metrics.roc_auc_score(y_test, y_pred))\n# print('PRECISION:', metrics.accuracy_score(y_test, y_pred))\n# print('RECALL:', metrics.recall_score(y_test, y_pred))\n# train_report = metrics.classification_report(y_test, y_pred)\n# print(train_report)\n# return model\n#\n#\n# def modelfit(alg, X = X,y = y, useTrainCV=True, cv_folds=5, early_stopping_rounds=50):\n# if useTrainCV:\n# xgb_param = alg.get_xgb_params()\n# xgtrain = xgb.DMatrix(X, label=y)\n# cvresult = xgb.cv(xgb_param, xgtrain, num_boost_round=alg.get_params()['n_estimators'], nfold=cv_folds,\n# metrics='auc', early_stopping_rounds=early_stopping_rounds)\n# alg.set_params(n_estimators=cvresult.shape[0])\n#\n# # Fit the algorithm on the data\n# alg.fit(X, y, eval_metric='auc')\n# # Predict training set:\n# dtrain_predictions = alg.predict(X)\n# dtrain_predprob = alg.predict_proba(X)[:, 1]\n# # Print model report:\n# print\n# \"\\nModel Report\"\n# print\n# \"Accuracy : %.4g\" % metrics.accuracy_score(X, dtrain_predictions)\n# print\n# \"AUC Score (Train): %f\" % metrics.roc_auc_score(X, dtrain_predprob)\n# feat_imp = pd.Series(alg.booster().get_fscore()).sort_values(ascending=False)\n# print(feat_imp)\n# def show_model(fmodel):\n# model = joblib.load(fmodel)\n# y_pred = model.predict(X_test)\n# accuracy = metrics.accuracy_score(y_test, y_pred)\n# print('*'*10+fmodel+'*'*10)\n# print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\n# print('auc:', metrics.roc_auc_score(y_test, y_pred))\n# print('精确率Accuracy:', metrics.accuracy_score(y_test, y_pred))\n# train_report = metrics.classification_report(y_test, y_pred)\n# print(train_report)\n# return model\n\n\n#broadband_xgb_06131154.pkl broadband_xgb_06131114.pkl\nif __name__ == '__main__':\n start = datetime.now()\n print(mixData('broadband_xgb_06131154.pkl','broadband_xgb_06131114.pkl'))\n end = datetime.now()\n print(\"model train cost {}s\".format((end-start).seconds))",
"import pandas as pd\nimport numpy as np\nimport json\nd = ['','T','M','U']\ndef parse(row):\n name = row[3].strip()\n t = str(row[0])[:7],[str(row[1]), name,d[row[2]]]\n return t\n\nif __name__ == '__main__':\n data = pd.read_csv(\"json.csv\", names=[\"a\",\"b\",\"c\",\"d\"],encoding='utf-8').fillna('')\n n = [parse(l) for l in data.values]\n m = {k:v for k,v in n}\n print(m)\n with open(\"hcode.json\", \"w\") as f:\n json.dump(m, f)"
] |
[
[
"matplotlib.pyplot.legend",
"sklearn.externals.joblib.dump",
"sklearn.metrics.roc_auc_score",
"numpy.linspace",
"matplotlib.pyplot.plot",
"numpy.mean",
"sklearn.externals.joblib.load",
"sklearn.metrics.classification_report",
"sklearn.preprocessing.MinMaxScaler",
"pandas.read_csv",
"numpy.std",
"sklearn.learning_curve",
"matplotlib.pyplot.figure",
"matplotlib.pyplot.title",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.fill_between",
"sklearn.svm.SVC",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.grid",
"sklearn.preprocessing.Normalizer",
"matplotlib.pyplot.xlabel",
"sklearn.metrics.accuracy_score"
],
[
"pandas.read_csv"
]
] |
gunpowder1473/mySSD
|
[
"ee7b44de1ef2f6013b6b17ca3cdefd52729ed479"
] |
[
"network/ssd_network_calc.py"
] |
[
"import tensorflow as tf\nimport math\nfrom Common import common_methods\nfrom tensorflow.python.framework import tensor_shape\n\nslim = tf.contrib.slim\n\n\ndef ssdDefaultboxResult(inputs, num_classes, sizes, ratios=[1], normalization=-1):\n net = inputs\n if normalization > 0:\n net = common_methods.l2_normalization(net, scaling=True)\n # defaultbox个数,每个featuremap除去对应的ratios的以外,额外添加2个,其aspect ratios = 1\n # 大小为sk与sqrt(sk*sk+1).\n num_default = len(sizes) + len(ratios)\n # 分别用3*3的卷积核去预测location与class的输出\n # Location. (x,y,w,h) 4个offset\n num_loc_pred = num_default * 4\n loc_pred = slim.conv2d(net, num_loc_pred, [3, 3], activation_fn=None, scope='conv_loc')\n # loc_pred转为NHWC\n loc_pred = common_methods.dataFormatChange(loc_pred)\n # 相当于增添了一维,将第三维拆开为num_default*4\n loc_pred = tf.reshape(loc_pred, common_methods.tensorShape(loc_pred, 4)[:-1] + [num_default, 4])\n # Class. 30种\n num_cls_pred = num_default * num_classes\n # 卷积核:3*3*net的第三维,无激活函数,30*num_default个卷积核,输出前两维同net,第三维30*num_default\n # 得到了每个defaultbox对30类的预测输出\n cls_pred = slim.conv2d(net, num_cls_pred, [3, 3], activation_fn=None, scope='conv_cls')\n # cls_pred转为NHWC\n cls_pred = common_methods.dataFormatChange(cls_pred)\n # 相当于增添了一维,将第三维拆开为num_default*30\n # 得到了每个defaultbox对4个误差的预测输出\n cls_pred = tf.reshape(cls_pred, common_methods.tensorShape(cls_pred, 4)[:-1] + [num_default, num_classes])\n return cls_pred, loc_pred\n\n\ndef ssd_losses(logits, localisations, gclasses, glocalisations, gscores, match_threshold=0.5,\n negative_ratio=3., alpha=1., scope=None):\n with tf.name_scope(scope, 'ssd_losses'):\n # 传到这里时每一个defaultbox对应的class是得分最高的\n # logits对应6个卷积层的输出,每一层的shape为(batch, x, x, defaultbox_per_featuremap, num_classes)\n # 其中x是对应的卷积层的大小\n lshape = common_methods.tensorShape(logits[0], 5)\n num_classes = lshape[-1]\n batch_size = lshape[0]\n flogits = []\n fgclasses = []\n fgscores = []\n flocalisations = []\n fglocalisations = []\n for i in range(len(logits)):\n flogits.append(tf.reshape(logits[i], [-1, num_classes]))\n fgclasses.append(tf.reshape(gclasses[i], [-1]))\n fgscores.append(tf.reshape(gscores[i], [-1]))\n flocalisations.append(tf.reshape(localisations[i], [-1, 4]))\n fglocalisations.append(tf.reshape(glocalisations[i], [-1, 4]))\n # num_defaultbox * num_classes,这里num_defaultbox是6个卷积层内包含的defaultbox的总和\n logits = tf.concat(flogits, axis=0)\n # num_defaultbox\n gclasses = tf.concat(fgclasses, axis=0)\n # num_defaultbox\n gscores = tf.concat(fgscores, axis=0)\n # num_defaultbox * 4\n localisations = tf.concat(flocalisations, axis=0)\n # num_dfaultbox * 4\n glocalisations = tf.concat(fglocalisations, axis=0)\n # glabels = tf.reshape(glabels, [-1])\n # glabels = tf.cast(glabels, tf.int32)\n # num_labels = glabels._shape_as_list()[0]\n dtype = logits.dtype\n # 去掉小于阈值的\n pmask = gscores > match_threshold\n # temp_mask = -(tf.cast(pmask, tf.int64))\n # # 超过阈值中被选中的类\n # be_choosed = temp_mask * gclasses\n # be_choosed = tf.cast(be_choosed, tf.int32)\n # in_or_out_flag = []\n # i = 0\n #\n # def isIn():\n # return True\n #\n # def isOut():\n # return False\n #\n # def shouldEnd(i):\n # return tf.less(i, num_classes)\n #\n # def shouldLoop(judge_result, i, j):\n # result = tf.logical_and(judge_result, tf.less(j, 1))\n # return result\n #\n # def isInLabels(i):\n # find = tf.convert_to_tensor(False)\n # for j in range(num_labels):\n # result = tf.cond(tf.equal(i, glabels[j]), isIn, isOut)\n # result = tf.cast(result, tf.bool)\n # find = tf.logical_or(result, find)\n # return find\n #\n # def loopBase(judge_result, i, j):\n # # 判断被选中的类中有无该类\n # temp_equal = tf.equal(i - 1, be_choosed)\n # temp_change = tf.cast(temp_equal, tf.int32)\n # sum = tf.reduce_sum(temp_change)\n # # 和大于0,说明被选中的类中存在该类\n # judge = tf.greater(sum, 0)\n # # (类,是否需要补(即不存在))\n # in_or_out_flag.append((i, judge))\n # j += 1\n # return judge_result, i, j\n #\n # def loopBody(i):\n # # 首先判断该类有没有被标注在当前图片中\n # # 若在,则执行loopBase\n # judge_result = isInLabels(i)\n # j = 0\n # i += 1\n # judge_result, i, j = tf.while_loop(shouldLoop, loopBase, [judge_result, i, j])\n # return i\n #\n # i = tf.while_loop(shouldEnd, loopBody, [i])\n #\n # def needFind(judge_tuple, j):\n # result = tf.greater(1, 2)#tf.logical_and(judge_tuple[1], tf.less(j, 1))\n # return result\n #\n # def addMax(judge_tuple, j):\n # # 将所有scores从大到小排列\n # # gscores与gclasses下标统一,通过下标去找到分类\n # _, val_classes = tf.nn.top_k(gscores, k=gscores._shape_as_list()[0])\n # not_get = tf.convert_to_tensor(True)\n # tf.while_loop(startFind, findLoop, [not_get, i, val_classes, judge_tuple])\n # # 只执行一次\n # j += 1\n # return judge_result, j\n #\n # def startFind(not_get, i, val_classes, judge_tuple):\n # result = tf.logical_and(not_get, tf.less(i, gclasses._shape_as_list()[0]))\n # return result\n #\n # def findLoop(not_get, i, val_classes, judge_tuple):\n # # i是遍历索引,val_classes[i]为在排序之前的索引,gclasses[val_classes[i]]为对应的分类\n # value = tf.cast(judge_tuple[0], tf.int32)\n # mask = tf.equal(gclasses[val_classes[i]], value)\n # # mask为真说明找到了,可以跳出循环\n # not_get = tf.where(mask, False, True)\n # i += 1\n # return not_get, i, val_classes, judge_tuple\n #\n # for i in range(len(in_or_out_flag)):\n # j = 0\n # judge_tuple = in_or_out_flag[i]\n # tf.while_loop(needFind, addMax, [judge_tuple, j])\n\n # 计算所有超过阈值的bbox的总数\n\n # 得到一个包含所有本次图像中包含的bbox的类别的无重复的列表\n actual_all_classes, _ = tf.unique(gclasses)\n actual_all_classes = tf.reshape(actual_all_classes, [-1])\n\n # 得到一个包含所有本次图像中大于阈值的bbox的类别的无重复的列表\n # 首先留下被选中的bboxes的类别\n choosen_class = tf.boolean_mask(gclasses, pmask)\n actual_choosen_classes, _ = tf.unique(choosen_class)\n actual_choosen_classes = tf.reshape(actual_choosen_classes, [-1])\n\n def notFind(i, pmask, include_not_choosen_num, include_not_choosen):\n mask = tf.less(i, include_not_choosen_num)\n return mask\n\n def findLoop(i, pmask, include_not_choosen_num, include_not_choosen):\n mask = tf.equal(gclasses, include_not_choosen[i])\n fmask = tf.cast(mask, gscores.dtype)\n # 留下那些得分都不过0.5的defaultbboxes\n cur_class_scores = gscores * fmask\n max_scores_index = tf.argmax(cur_class_scores, dimension=0)\n temp_pmask = tf.sparse_to_dense(max_scores_index, pmask.get_shape(), tf.constant(True), tf.constant(False))\n pmask = tf.logical_or(temp_pmask, pmask)\n return i + 1, pmask, include_not_choosen_num, include_not_choosen\n\n def needAdd(pmask):\n # include_not_choosen = tf.slice(tf.expand_dims(actual_all_classes, 0),\n # [0, tf.shape(actual_choosen_classes)[0]],\n # [1, tf.shape(actual_all_classes)[0] - tf.shape(actual_choosen_classes)[0]])\n # include_not_choosen = include_not_choosen[0]\n include_not_choosen = tf.boolean_mask(gclasses, tf.logical_not(pmask))\n include_not_choosen_num = tf.shape(include_not_choosen)[0]\n j = 0\n _, pmask, _, _ = tf.while_loop(notFind, findLoop,\n [j, pmask, include_not_choosen_num, include_not_choosen])\n return pmask\n\n # 长度不一样,说明有类别对应的bboxes得分均不过0.5\n is_need_add = tf.equal(tf.shape(actual_all_classes)[0], tf.shape(actual_choosen_classes)[0])\n pmask = tf.cond(is_need_add, lambda: needAdd(pmask), lambda: pmask)\n\n fpmask = tf.cast(pmask, dtype)\n n_positives = tf.reduce_sum(fpmask)\n\n # 经过前面的筛选后,去掉的negativebox很多,远多于positivebox\n # 使得两者不均衡,在置信度损失中第一项的x因子的大部分都是0,损失函数很小\n # 难以收敛,所以在negativebox中选择较大的,使得最后两者比例在3:1(这里由negative ratio决定)\n no_classes = tf.cast(pmask, tf.int32)\n predictions = slim.softmax(logits)\n nmask = tf.logical_and(tf.logical_not(pmask), gscores > -0.5)\n fnmask = tf.cast(nmask, dtype)\n # predictions[:,0]中0对应于Lconf中Neg的c的上表0,即第0个分类(背景,即无匹配对象)\n nvalues = tf.where(nmask, predictions[:, 0], 1. - fnmask)\n nvalues_flat = tf.reshape(nvalues, [-1])\n max_neg_entries = tf.cast(tf.reduce_sum(fnmask), tf.int32)\n n_neg = tf.cast(negative_ratio * n_positives, tf.int32) + batch_size\n n_neg = tf.minimum(n_neg, max_neg_entries)\n # 对无匹配类置信度最小,相当于对其他类置信度最大\n val, _ = tf.nn.top_k(-nvalues_flat, k=n_neg)\n # 选择其中最大的n_neg个\n max_neg_val = -val[-1]\n nmask = tf.logical_and(nmask, nvalues < max_neg_val)\n fnmask = tf.cast(nmask, dtype)\n\n # 交叉熵\n with tf.name_scope('cross_entropy_pos'):\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=gclasses)\n loss = tf.div(tf.reduce_sum(loss * fpmask), batch_size, name='value')\n tf.losses.add_loss(loss)\n\n with tf.name_scope('cross_entropy_neg'):\n loss = tf.nn.sparse_softmax_cross_entropy_with_logits(logits=logits, labels=no_classes)\n loss = tf.div(tf.reduce_sum(loss * fnmask), batch_size, name='value')\n tf.losses.add_loss(loss)\n\n # Loc损失\n with tf.name_scope('localization'):\n weights = tf.expand_dims(alpha * fpmask, axis=-1)\n loss = common_methods.abs_smooth(localisations - glocalisations)\n loss = tf.div(tf.reduce_sum(loss * weights), batch_size, name='value')\n tf.losses.add_loss(loss)\n"
] |
[
[
"tensorflow.concat",
"tensorflow.reduce_sum",
"tensorflow.cast",
"tensorflow.minimum",
"tensorflow.equal",
"tensorflow.where",
"tensorflow.boolean_mask",
"tensorflow.while_loop",
"tensorflow.logical_or",
"tensorflow.nn.top_k",
"tensorflow.name_scope",
"tensorflow.argmax",
"tensorflow.logical_not",
"tensorflow.unique",
"tensorflow.less",
"tensorflow.shape",
"tensorflow.nn.sparse_softmax_cross_entropy_with_logits",
"tensorflow.losses.add_loss",
"tensorflow.constant",
"tensorflow.reshape",
"tensorflow.expand_dims",
"tensorflow.logical_and"
]
] |
twobackfromtheend/challenger
|
[
"01d131487209029df342e68075e8aae133c4e632"
] |
[
"challenger_bot/reinforcement_learning/model/dense_model.py"
] |
[
"from typing import Sequence, TYPE_CHECKING\n\nfrom challenger_bot.reinforcement_learning.model.base_model import BaseModel\n\nif TYPE_CHECKING:\n from tensorflow.python.keras import Sequential\n\n\nclass DenseModel(BaseModel):\n\n def __init__(self, inputs: int, outputs: int, load_from_filepath: str = None,\n layer_nodes: Sequence[int] = (24, 24),\n inner_activation='relu', output_activation='linear',\n regularizer=None,\n **kwargs):\n import tensorflow as tf\n\n self.layer_nodes = layer_nodes\n self.inner_activation = inner_activation\n self.output_activation = output_activation\n self.regularizer = regularizer if regularizer is not None else tf.keras.regularizers.l2(1e-8)\n # self.learning_rate = learning_rate\n # self.loss_fn = self.get_loss_fn(loss_fn)\n\n super().__init__(inputs, outputs, load_from_filepath=load_from_filepath)\n\n def build_model(self) -> 'Sequential':\n from tensorflow import keras\n\n model = keras.Sequential()\n\n # Verbose version needed because https://github.com/tensorflow/tensorflow/issues/22837#issuecomment-428327601\n # model.add(keras.layers.Dense(self.inputs))\n model.add(keras.layers.Dense(input_shape=(self.inputs,), units=self.inputs))\n\n for _layer_nodes in self.layer_nodes:\n model.add(\n keras.layers.Dense(_layer_nodes, activation=self.inner_activation, kernel_regularizer=self.regularizer)\n )\n\n model.add(keras.layers.Dense(self.outputs, activation=self.output_activation))\n # optimizer = keras.optimizers.Adam(lr=self.learning_rate)\n # model.compile(loss=self.loss_fn, optimizer=optimizer, metrics=['mae'])\n return model\n"
] |
[
[
"tensorflow.keras.layers.Dense",
"tensorflow.keras.regularizers.l2",
"tensorflow.keras.Sequential"
]
] |
yuhonghong66/minpy
|
[
"2e44927ad0fbff9295e2acf6db636e588fdc5b42"
] |
[
"tests/unittest/test_autograd.py"
] |
[
"from __future__ import print_function\n\nimport minpy.numpy as mp\nimport numpy as np\nimport minpy.dispatch.policy as policy\nfrom minpy.core import convert_args, return_numpy, grad_and_loss, grad, minpy_to_numpy as mn, numpy_to_minpy as nm\nimport time\n\n# mp.set_policy(policy.OnlyNumPyPolicy())\n\ndef test_autograd():\n @convert_args\n def minpy_rnn_step_forward(x, prev_h, Wx, Wh, b):\n next_h = mp.tanh(x.dot(Wx) + prev_h.dot(Wh) + b)\n return next_h\n \n \n def rel_error(x, y):\n \"\"\" returns relative error \"\"\"\n return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y))))\n \n \n def rnn_step_forward(x, prev_h, Wx, Wh, b):\n next_h = np.tanh(prev_h.dot(Wh) + x.dot(Wx) + b)\n cache = next_h, prev_h, x, Wx, Wh\n return next_h, cache\n \n \n def rnn_step_backward(dnext_h, cache):\n dx, dprev_h, dWx, dWh, db = None, None, None, None, None\n # Load values from rnn_step_forward\n next_h, prev_h, x, Wx, Wh = cache\n # Gradients of loss wrt tanh\n dtanh = dnext_h * (1 - next_h * next_h) # (N, H)\n # Gradients of loss wrt x\n dx = dtanh.dot(Wx.T)\n # Gradients of loss wrt prev_h\n dprev_h = dtanh.dot(Wh.T)\n # Gradients of loss wrt Wx\n dWx = x.T.dot(dtanh) # (D, H)\n # Gradients of loss wrt Wh\n dWh = prev_h.T.dot(dtanh)\n # Gradients of loss wrt b. Note we broadcast b in practice. Thus result of\n # matrix ops are just sum over columns\n db = dtanh.sum(axis=0) # == np.ones([N, 1]).T.dot(dtanh)[0, :]\n return dx, dprev_h, dWx, dWh, db\n \n \n # preparation\n N, D, H = 4, 5, 6\n x = np.random.randn(N, D)\n h = np.random.randn(N, H)\n Wx = np.random.randn(D, H)\n Wh = np.random.randn(H, H)\n b = np.random.randn(H)\n out, cache = rnn_step_forward(x, h, Wx, Wh, b)\n dnext_h = np.random.randn(*out.shape)\n \n # test MinPy\n start = time.time()\n rnn_step_forward_loss = lambda x, h, Wx, Wh, b, dnext_h: minpy_rnn_step_forward(x, h, Wx, Wh, b) * nm(dnext_h)\n grad_loss_function = return_numpy(grad_and_loss(rnn_step_forward_loss, range(5)))\n grad_arrays = grad_loss_function(x, h, Wx, Wh, b, dnext_h)[0]\n end = time.time()\n print(\"MinPy total time elapsed:\", end - start)\n \n # test NumPy\n start = time.time()\n out, cache = rnn_step_forward(x, h, Wx, Wh, b)\n dx, dprev_h, dWx, dWh, db = rnn_step_backward(dnext_h, cache)\n out *= dnext_h # to agree with MinPy calculation\n end = time.time()\n print(\"NumPy total time elapsed:\", end - start)\n \n print()\n print(\"Result Check:\")\n print('dx error: ', rel_error(dx, grad_arrays[0]))\n print('dprev_h error: ', rel_error(dprev_h, grad_arrays[1]))\n print('dWx error: ', rel_error(dWx, grad_arrays[2]))\n print('dWh error: ', rel_error(dWh, grad_arrays[3]))\n print('db error: ', rel_error(db, grad_arrays[4]))\n\ndef test_zero_input_grad():\n def foo1(x):\n return 1\n bar1 = grad(foo1)\n assert bar1(0) == 0.0\n\ndef test_reduction():\n def test_sum():\n x_np = np.array([[1, 2], [3, 4], [5, 6]])\n x_grad = np.array([[1, 1], [1, 1], [1, 1]])\n def red1(x):\n return mp.sum(x)\n def red2(x):\n return mp.sum(x, axis=0)\n def red3(x):\n return mp.sum(x, axis=0, keepdims=True)\n grad1 = grad(red1)\n assert np.all(grad1(x_np).asnumpy() == x_grad)\n grad2 = grad(red2)\n assert np.all(grad2(x_np).asnumpy() == x_grad)\n grad3 = grad(red3)\n assert np.all(grad3(x_np).asnumpy() == x_grad)\n\n def test_max():\n x_np = np.array([[1, 2], [2, 1], [0, 0]])\n x_grad1 = np.array([[0, 1], [1, 0], [0, 0]])\n x_grad2 = np.array([[0, 1], [1, 0], [1, 1]])\n x_grad3 = np.array([[0, 1], [1, 0], [0, 0]])\n def red1(x):\n return mp.max(x)\n def red2(x):\n return mp.max(x, axis=1)\n def red3(x):\n return mp.max(x, axis=1, keepdims=True)\n def red4(x):\n return mp.max(x, axis=0)\n def red5(x):\n return mp.max(x, axis=0, keepdims=True)\n grad1 = grad(red1)\n assert np.all(grad1(x_np).asnumpy() == x_grad1)\n grad2 = grad(red2)\n assert np.all(grad2(x_np).asnumpy() == x_grad2)\n grad3 = grad(red3)\n assert np.all(grad3(x_np).asnumpy() == x_grad2)\n grad4 = grad(red4)\n assert np.all(grad4(x_np).asnumpy() == x_grad3)\n grad5 = grad(red5)\n assert np.all(grad5(x_np).asnumpy() == x_grad3)\n\n def test_min():\n x_np = np.array([[1, 2], [2, 1], [0, 0]])\n x_grad1 = np.array([[0, 0], [0, 0], [1, 1]])\n x_grad2 = np.array([[1, 0], [0, 1], [1, 1]])\n x_grad3 = np.array([[0, 0], [0, 0], [1, 1]])\n def red1(x):\n return mp.min(x)\n def red2(x):\n return mp.min(x, axis=1)\n def red3(x):\n return mp.min(x, axis=1, keepdims=True)\n def red4(x):\n return mp.min(x, axis=0)\n def red5(x):\n return mp.min(x, axis=0, keepdims=True)\n grad1 = grad(red1)\n assert np.all(grad1(x_np).asnumpy() == x_grad1)\n grad2 = grad(red2)\n assert np.all(grad2(x_np).asnumpy() == x_grad2)\n grad3 = grad(red3)\n assert np.all(grad3(x_np).asnumpy() == x_grad2)\n grad4 = grad(red4)\n assert np.all(grad4(x_np).asnumpy() == x_grad3)\n grad5 = grad(red5)\n assert np.all(grad5(x_np).asnumpy() == x_grad3)\n\n test_sum()\n test_max()\n test_min()\n\nif __name__ == \"__main__\":\n test_autograd()\n test_zero_input_grad()\n test_reduction()\n"
] |
[
[
"numpy.array",
"numpy.random.randn",
"numpy.abs"
]
] |
DeliciousHair/persim
|
[
"4702251c22d4fffbb1c29409f466745c6b6c26c5"
] |
[
"test/test_visuals.py"
] |
[
"import pytest\nimport numpy as np\n\nimport matplotlib.pyplot as plt\n\nimport persim\nfrom persim import plot_diagrams\n\n\n\"\"\"\n\n Testing visualization is a little more difficult, but still necessary. An example of how to get started:\n > https://stackoverflow.com/questions/27948126/how-can-i-write-unit-tests-against-code-that-uses-matplotlib\n\n ```\n def test_plot_square2():\n f, ax = plt.subplots()\n x, y = [0, 1, 2], [0, 1, 2]\n plot_square(x, y)\n x_plot, y_plot = ax.lines[0].get_xydata().T\n np.testing.assert_array_equal(y_plot, np.square(y))\n\n ```\n\n\n Notes\n -----\n\n ax.get_children() gives all the pieces in the plot, very useful\n Scatter data is of type `PathCollection` and will be a child of ax.\n\n\"\"\"\n\n\nclass TestPlotting:\n def test_single(self):\n \"\"\" Most just test this doesn't crash\n \"\"\"\n diagram = np.array([[0, 1], [1, 1], [2, 4], [3, 5]])\n\n f, ax = plt.subplots()\n plot_diagrams(diagram, show=False)\n\n x_plot, y_plot = ax.lines[0].get_xydata().T\n\n assert x_plot[0] <= np.min(diagram)\n assert x_plot[1] >= np.max(diagram)\n\n # get PathCollection\n pathcols = [child for child in ax.get_children()\n if child.__class__.__name__ == \"PathCollection\"]\n assert len(pathcols) == 1\n\n def test_multiple(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, show=False)\n\n pathcols = [child for child in ax.get_children()\n if child.__class__.__name__ == \"PathCollection\"]\n\n assert len(pathcols) == 2\n np.testing.assert_array_equal(pathcols[0].get_offsets(), diagrams[0])\n np.testing.assert_array_equal(pathcols[1].get_offsets(), diagrams[1])\n\n def test_plot_only(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n f, ax = plt.subplots()\n plot_diagrams(diagrams, legend=False, show=False, plot_only=[1])\n\n def test_legend_true(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, legend=True, show=False)\n legend = [child for child in ax.get_children()\n if child.__class__.__name__ == \"Legend\"]\n\n assert len(legend) == 1\n\n def test_legend_false(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, legend=False, show=False)\n legend = [child for child in ax.get_children()\n if child.__class__.__name__ == \"Legend\"]\n\n assert len(legend) == 0\n\n def test_set_title(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, title='my title', show=False)\n assert ax.get_title() == 'my title'\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, show=False)\n assert ax.get_title() == ''\n\n def test_default_square(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, show=False)\n diagonal = ax.lines[0].get_xydata()\n\n assert diagonal[0, 0] == diagonal[0, 1]\n assert diagonal[1, 0] == diagonal[1, 1]\n\n def test_default_label(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, show=False)\n\n assert ax.get_ylabel() == 'Death'\n assert ax.get_xlabel() == 'Birth'\n\n def test_lifetime(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, lifetime=True, show=False)\n\n assert ax.get_ylabel() == 'Lifetime'\n assert ax.get_xlabel() == 'Birth'\n\n line = ax.get_lines()[0]\n np.testing.assert_array_equal(line.get_ydata(), [0, 0])\n\n def test_lifetime_removes_birth(self):\n diagrams = [\n np.array([[0, 1], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, lifetime=True, show=False)\n\n pathcols = [child for child in ax.get_children()\n if child.__class__.__name__ == \"PathCollection\"]\n\n modded1 = diagrams[0]\n modded1[:, 1] = diagrams[0][:, 1] - diagrams[0][:, 0]\n modded2 = diagrams[1]\n modded2[:, 1] = diagrams[1][:, 1] - diagrams[1][:, 0]\n assert len(pathcols) == 2\n np.testing.assert_array_equal(pathcols[0].get_offsets(), modded1)\n np.testing.assert_array_equal(pathcols[1].get_offsets(), modded2)\n\n def test_infty(self):\n diagrams = [\n np.array([[0, np.inf], [1, 1], [2, 4], [3, 5]]),\n np.array([[0.5, 3], [2, 4], [4, 5], [10, 15]])\n ]\n\n f, ax = plt.subplots()\n plot_diagrams(diagrams, legend=True, show=False)\n\n # Right now just make sure nothing breaks\n\n\nclass TestMatching:\n def test_bottleneck_matching(self):\n dgm1 = np.array([\n [0.1, 0.2],\n [0.2, 0.4]\n ])\n dgm2 = np.array([\n [0.1, 0.2],\n [0.3, 0.45]\n ])\n\n d, matching = persim.bottleneck(dgm1, dgm2, matching=True)\n persim.bottleneck_matching(dgm1, dgm2, matching)\n\n def test_plot_labels(self):\n dgm1 = np.array([\n [0.1, 0.2],\n [0.2, 0.4]\n ])\n dgm2 = np.array([\n [0.1, 0.2],\n [0.3, 0.45]\n ])\n\n d, matching = persim.bottleneck(dgm1, dgm2, matching=True)\n persim.bottleneck_matching(\n dgm1, dgm2, matching, labels=[\"X\", \"Y\"])\n"
] |
[
[
"numpy.max",
"numpy.array",
"matplotlib.pyplot.subplots",
"numpy.min"
]
] |
wangning911/Transferability_Black-Box_Attacks_new
|
[
"938ee1bc6c899f21749504fef49c86c175e4814a"
] |
[
"demos-lifelong-transfer/demos-cnn/pytorch/main_pytorch.py"
] |
[
"import os\nimport sys\nsys.path.insert(1, os.path.join(sys.path[0], '../utils'))\nfrom torch.autograd import Variable\nimport config\nfrom models_pytorch import move_data_to_gpu, DecisionLevelMaxPooling, CnnPooling_Max, ResNet, Vggish, AlexNet, CnnAtrous, EWC\nfrom utilities import (create_folder, get_filename, create_logging,\n calculate_confusion_matrix, calculate_accuracy,\n plot_confusion_matrix, print_accuracy,\n write_leaderboard_submission, write_evaluation_submission)\nfrom data_generator import DataGenerator, TestDataGenerator\nimport torch.optim as optim\nimport torch.nn.functional as F\nimport torch.nn as nn\nimport torch\nimport copy\nimport logging\nimport time\nimport math\nimport h5py\nimport argparse\nimport numpy as np\n#选择第几个gpu跑\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = '0'\n\n\nModel_attacker = CnnAtrous\n# [DecisionLevelMaxPooling, Vggish, ResNet] [ResNet, Vggish, DecisionLevelMaxPooling]\nModel_target_list = [DecisionLevelMaxPooling, Vggish, ResNet]\nModel_attacker_folder = 'CnnAtrous'\n# ['models-basecnn', 'models-vgg16', 'models-resnet50'] ['models-resnet50', 'models-vgg16', 'models-basecnn']\nModel_target_folder_list = ['models-basecnn',\n 'models-vgg16', 'models-resnet50']\nModel_num = 3\n\nbatch_size = 16\n\n\ndef evaluate(model_attacker, model_target, generator, data_type, devices, max_iteration, cuda):\n \"\"\"Evaluate\n\n Args:\n model: object.\n generator: object.\n data_type: 'train' | 'validate'.\n devices: list of devices, e.g. ['a'] | ['a', 'b', 'c']\n max_iteration: int, maximum iteration for validation\n cuda: bool.\n\n Returns:\n accuracy: float\n \"\"\"\n\n # Generate function\n generate_func = generator.generate_validate(data_type=data_type,\n devices=devices,\n shuffle=True,\n max_iteration=max_iteration)\n\n # Forward\n dict = forward(model_attacker=model_attacker,\n model_target=model_target,\n generate_func=generate_func,\n cuda=cuda,\n return_target=True)\n\n outputs = dict['output'] # (audios_num, classes_num)\n outputs_adv = dict['output_adv'] # (audios_num, classes_num)\n targets = dict['target'] # (audios_num, classes_num)\n\n predictions = np.argmax(outputs, axis=-1) # (audios_num,)\n predictions_adv = np.argmax(outputs_adv, axis=-1) # (audios_num,)\n\n # Evaluate\n classes_num = outputs.shape[-1]\n\n loss = F.nll_loss(Variable(torch.Tensor(outputs)), Variable(\n torch.LongTensor(targets))).data.numpy()\n loss = float(loss)\n\n loss_adv = F.nll_loss(Variable(torch.Tensor(outputs_adv)), Variable(\n torch.LongTensor(targets))).data.numpy()\n loss_adv = float(loss_adv)\n\n accuracy = calculate_accuracy(targets, predictions, classes_num,\n average='macro')\n\n accuracy_adv = calculate_accuracy(targets, predictions_adv, classes_num,\n average='macro')\n\n return accuracy, loss, accuracy_adv, loss_adv\n\n# forward: model_pytorch--- Return_heatmap = False\n# forward_heatmap: model_pytorch--- Return_heatmap = True\n\n\ndef forward(model_attacker, model_target, generate_func, cuda, return_target):\n \"\"\"Forward data to a model.\n\n Args:\n generate_func: generate function\n cuda: bool\n return_target: bool\n\n Returns:\n dict, keys: 'audio_name', 'output'; optional keys: 'target'\n \"\"\"\n\n outputs = []\n audio_names = []\n outputs_adv = []\n\n if return_target:\n targets = []\n\n # Evaluate on mini-batch\n for data in generate_func:\n\n if return_target:\n (batch_x, batch_y, batch_audio_names) = data\n\n else:\n (batch_x, batch_audio_names) = data\n\n batch_x = move_data_to_gpu(batch_x, cuda)\n\n # Predict\n model_attacker.eval()\n model_target.eval()\n batch_output = model_target(batch_x)\n\n # advesarial predict\n batch_x_adv = batch_x + model_attacker(batch_x)\n batch_output_adv = model_target(batch_x_adv)\n\n # Append data\n outputs.append(batch_output.data.cpu().numpy())\n audio_names.append(batch_audio_names)\n outputs_adv.append(batch_output_adv.data.cpu().numpy())\n\n if return_target:\n targets.append(batch_y)\n\n dict = {}\n\n outputs = np.concatenate(outputs, axis=0)\n dict['output'] = outputs\n\n audio_names = np.concatenate(audio_names, axis=0)\n dict['audio_name'] = audio_names\n\n outputs_adv = np.concatenate(outputs_adv, axis=0)\n dict['output_adv'] = outputs_adv\n\n if return_target:\n targets = np.concatenate(targets, axis=0)\n dict['target'] = targets\n\n return dict\n\n\ndef forward_test(model_attacker, model_target, generate_func, cuda, return_target):\n \"\"\"Forward data to a model.\n\n Args:\n generate_func: generate function\n cuda: bool\n return_target: bool\n\n Returns:\n dict, keys: 'audio_name', 'output'; optional keys: 'target'\n \"\"\"\n\n outputs = []\n audio_names = []\n outputs_adv = []\n mseloss = 0\n outputs_heatmap = []\n inputs_heatmap = []\n noise_heatmap = []\n\n if return_target:\n targets = []\n\n # Evaluate on mini-batch\n for data in generate_func:\n\n if return_target:\n (batch_x, batch_y, batch_audio_names) = data\n\n else:\n (batch_x, batch_audio_names) = data\n\n batch_x = move_data_to_gpu(batch_x, cuda)\n\n # Predict\n model_attacker.eval()\n model_target.eval()\n batch_output = model_target(batch_x)\n\n # advesarial predict\n batch_noise = model_attacker(batch_x)\n batch_x_adv = batch_x + batch_noise\n batch_output_adv = model_target(batch_x_adv)\n\n mseloss = mseloss + \\\n F.mse_loss(batch_x_adv.data.cpu(), batch_x.data.cpu()).data.numpy()\n mseloss = float(mseloss)\n\n # Append data\n outputs.append(batch_output.data.cpu().numpy())\n audio_names.append(batch_audio_names)\n outputs_adv.append(batch_output_adv.data.cpu().numpy())\n\n noise_heatmap.append(batch_noise.data.cpu().numpy())\n inputs_heatmap.append(batch_x.data.cpu().numpy())\n outputs_heatmap.append(batch_x_adv.data.cpu().numpy())\n\n if return_target:\n targets.append(batch_y)\n\n dict = {}\n\n outputs = np.concatenate(outputs, axis=0)\n dict['output'] = outputs\n\n audio_names = np.concatenate(audio_names, axis=0)\n dict['audio_name'] = audio_names\n\n outputs_adv = np.concatenate(outputs_adv, axis=0)\n dict['output_adv'] = outputs_adv\n\n if return_target:\n targets = np.concatenate(targets, axis=0)\n dict['target'] = targets\n\n inputs_heatmap = np.concatenate(inputs_heatmap, axis=0)\n dict['inputs_heatmap'] = inputs_heatmap\n outputs_heatmap = np.concatenate(outputs_heatmap, axis=0)\n dict['outputs_heatmap'] = outputs_heatmap\n noise_heatmap = np.concatenate(noise_heatmap, axis=0)\n dict['noise_heatmap'] = noise_heatmap\n\n dict['mseloss'] = mseloss/len(audio_names)\n\n return dict\n\n\ndef train(args):\n\n # Arugments & parameters\n dataset_dir = args.dataset_dir\n subdir = args.subdir\n workspace = args.workspace\n feature_type = args.feature_type\n filename = args.filename\n validation = args.validation\n holdout_fold = args.holdout_fold\n mini_data = args.mini_data\n cuda = args.cuda\n\n labels = config.labels\n\n ite_base = 10000\n\n if 'mobile' in subdir:\n devices = ['a', 'b', 'c']\n else:\n devices = ['a']\n\n classes_num = len(labels)\n\n for model_num in range(1, Model_num):\n Model_target = Model_target_list[model_num]\n Model_target_folder = Model_target_folder_list[model_num]\n # Paths\n # if mini_data:\n # hdf5_path = os.path.join(\n # workspace, 'features', feature_type, 'mini_development.h5')\n # else:\n hdf5_path = os.path.join(\n workspace, 'features', feature_type, 'development.h5')\n\n if validation:\n\n dev_train_csv = os.path.join(dataset_dir, subdir, 'evaluation_setup',\n 'fold{}_train.txt'.format(holdout_fold))\n\n dev_validate_csv = os.path.join(dataset_dir, subdir, 'evaluation_setup',\n 'fold{}_devel.txt'.format(holdout_fold))\n\n models_attacker_dir = os.path.join(workspace, 'models', Model_attacker_folder, subdir, filename,\n 'holdout_fold={}'.format(holdout_fold))\n\n models_target_path = os.path.join(workspace, 'models', Model_target_folder, subdir, filename,\n 'holdout_fold={}'.format(holdout_fold), 'md_10000_iters.tar')\n\n else:\n # dev_train_csv = os.path.join(dataset_dir, subdir, 'evaluation_setup',\n # 'fold{}_traindevel.txt'.format(holdout_fold))\n dev_train_csv = \"/home/nwang/emotion/train_dataset.csv\"\n # dev_validate_csv = os.path.join(dataset_dir, subdir, 'evaluation_setup',\n # 'fold{}_test.txt'.format(holdout_fold))\n dev_validate_csv = \"/home/nwang/emotion/dev_dataset.csv\"\n # models_attacker_dir = os.path.join(workspace, 'models', Model_attacker_folder, subdir, filename,\n # 'full_train')\n models_attacker_dir = os.path.join(workspace, 'models', Model_attacker_folder, subdir, filename,\n 'full_train')\n # models_target_path = os.path.join(workspace, 'models', Model_target_folder, subdir, filename,\n # 'full_train', 'md_10000_iters.tar')\n models_target_path = os.path.join(workspace, 'models', Model_target_folder, subdir, filename,\n 'full_train', 'md_10000_iters.tar')\n create_folder(models_attacker_dir)\n\n # estimate fisher\n if not model_num == 0:\n # path\n Model_target_pre = Model_target_list[model_num-1]\n\n models_attacker_path_pre = os.path.join(\n models_attacker_dir, 'md_{}_iters.tar'.format(ite_base*(model_num)))\n if validation:\n models_target_path_pre = os.path.join(workspace, 'models', Model_target_folder_list[model_num-1], subdir, filename,\n 'holdout_fold={}'.format(holdout_fold), 'md_10000_iters.tar')\n else:\n models_target_path_pre = os.path.join(workspace, 'models', Model_target_folder_list[model_num-1], subdir, filename,\n 'full_train', 'md_10000_iters.tar')\n # models_target_path_pre_bef = os.path.join(workspace, 'models', Model_target_folder_list[model_num-1], subdir, filename,\n # 'full_train')\n # create_folder(models_target_path_pre_bef)\n\n # model\n model_attacker_pre = Model_attacker()\n model_target_pre = Model_target_pre(classes_num)\n\n checkpoint = torch.load(models_attacker_path_pre)\n model_attacker_pre.load_state_dict(checkpoint['state_dict'])\n del checkpoint\n checkpoint = torch.load(models_target_path_pre)\n model_target_pre.load_state_dict(checkpoint['state_dict'])\n del checkpoint\n\n if cuda:\n model_attacker_pre.cuda()\n model_target_pre.cuda()\n # loss\n # Data generator\n generator = DataGenerator(hdf5_path=hdf5_path,\n batch_size=batch_size,\n dev_train_csv=dev_train_csv,\n dev_validate_csv=dev_validate_csv)\n ewc = EWC(model_attack=model_attacker_pre,\n model_target=model_target_pre,\n generator=generator,\n data_type='train',\n devices=devices,\n classes_num=classes_num,\n cuda=cuda)\n del generator\n del model_attacker_pre\n del model_target_pre\n\n # Model\n model_attacker = Model_attacker()\n model_target = Model_target(classes_num)\n checkpoint = torch.load(models_target_path)\n model_target.load_state_dict(checkpoint['state_dict'])\n del checkpoint\n if not model_num == 0:\n checkpoint = torch.load(models_attacker_path_pre)\n model_attacker.load_state_dict(checkpoint['state_dict'])\n del checkpoint\n\n if cuda:\n model_attacker.cuda()\n model_target.cuda()\n\n # Data generator\n generator = DataGenerator(hdf5_path=hdf5_path,\n batch_size=batch_size,\n dev_train_csv=dev_train_csv,\n dev_validate_csv=dev_validate_csv)\n\n # Optimizer\n lr = 1e-3\n optimizer_attacker = optim.Adam(model_attacker.parameters(\n ), lr=lr, betas=(0.9, 0.999), eps=1e-08, weight_decay=0.)\n\n train_bgn_time = time.time()\n\n # Train on mini batches\n for (iteration, (batch_x, batch_y)) in enumerate(generator.generate_train()):\n\n # Evaluate\n if iteration % 100 == 0:\n\n train_fin_time = time.time()\n\n (tr_acc, tr_loss, tr_acc_adv, tr_loss_adv) = evaluate(model_attacker=model_attacker,\n model_target=model_target,\n generator=generator,\n data_type='train',\n devices=devices,\n max_iteration=None,\n cuda=cuda)\n\n logging.info('tr_acc: {:.3f}, tr_loss: {:.3f}, tr_acc_adv: {:.3f}, tr_loss_adv: {:.3f}'.format(\n tr_acc, tr_loss, tr_acc_adv, tr_loss_adv))\n\n (va_acc, va_loss, va_acc_adv, va_loss_adv) = evaluate(model_attacker=model_attacker,\n model_target=model_target,\n generator=generator,\n data_type='validate',\n devices=devices,\n max_iteration=None,\n cuda=cuda)\n\n logging.info('va_acc: {:.3f}, va_loss: {:.3f}, va_acc_adv: {:.3f}, va_loss_adv: {:.3f}'.format(\n va_acc, va_loss, va_acc_adv, va_loss_adv))\n\n train_time = train_fin_time - train_bgn_time\n validate_time = time.time() - train_fin_time\n\n logging.info('iteration: {}, train time: {:.3f} s, validate time: {:.3f} s'\n ''.format(iteration, train_time, validate_time))\n\n logging.info('------------------------------------')\n\n train_bgn_time = time.time()\n\n # Save model\n if model_num == 0:\n ite_save = ite_base\n else:\n ite_save = 1000\n if iteration % ite_save == 0 and iteration > 0:\n save_out_dict = {'iteration': iteration,\n 'state_dict': model_attacker.state_dict(),\n 'optimizer': optimizer_attacker.state_dict()\n }\n save_out_path = os.path.join(\n models_attacker_dir, 'md_{}_iters.tar'.format(ite_base*(model_num+1)))\n torch.save(save_out_dict, save_out_path)\n logging.info('Model saved to {}'.format(save_out_path))\n\n # Reduce learning rate\n if iteration % 1000 == 0 > 0:\n for param_group in optimizer_attacker.param_groups:\n param_group['lr'] *= 0.9\n\n # Train\n batch_x = move_data_to_gpu(batch_x, cuda)\n batch_y = move_data_to_gpu(batch_y, cuda)\n\n # attacker -- generator\n optimizer_attacker.zero_grad()\n model_attacker.train()\n perturbation = model_attacker(batch_x)\n batch_x_adv = batch_x + perturbation\n loss_a_rec = F.mse_loss(batch_x_adv, batch_x)\n\n model_target.eval()\n batch_output_adv = model_target(batch_x_adv)\n\n # C&W loss\n onehot_labels = torch.eye(classes_num)\n onehot_labels = move_data_to_gpu(onehot_labels, cuda)\n onehot_labels = onehot_labels[batch_y]\n\n prob_real = torch.sum(onehot_labels * batch_output_adv, dim=1)\n prob_other, _ = torch.max(\n (1 - onehot_labels) * batch_output_adv - onehot_labels * 10000, dim=1)\n zeros = torch.zeros_like(prob_other)\n loss_a_cla = torch.max(prob_real - prob_other, zeros)\n loss_a_cla = torch.sum(loss_a_cla)\n\n loss_a = 0.02 * loss_a_cla + 0.98*loss_a_rec\n if iteration % 100 == 0 and iteration > 0:\n print(str(loss_a_cla) + '\\t' + str(loss_a_rec))\n\n if not model_num == 0:\n lamda = 10000000 # 1000 10000 100000 1000000 10000000\n loss_ewc = ewc.penalty(model_attacker)\n loss_a = loss_a + lamda * loss_ewc\n\n if iteration % 100 == 0 and iteration > 0:\n print(str(loss_ewc))\n\n # Backward\n loss_a.backward()\n optimizer_attacker.step()\n\n # Stop learning\n if model_num == 0:\n if iteration == ite_base:\n break\n else:\n if iteration == 1000:\n break\n\n\ndef inference_validation_data(args):\n # Arugments & parameters\n dataset_dir = args.dataset_dir\n subdir = args.subdir\n workspace = args.workspace\n feature_type = args.feature_type\n holdout_fold = args.holdout_fold\n iteration = args.iteration\n filename = args.filename\n cuda = args.cuda\n validation = args.validation\n\n labels = config.labels\n\n if 'mobile' in subdir:\n devices = ['a', 'b', 'c']\n else:\n devices = ['a']\n\n classes_num = len(labels)\n\n # Paths\n # hdf5_path = os.path.join(workspace, 'features', subdir, '{}.h5'.format(feature_type))\n hdf5_path = os.path.join(workspace, 'features',\n feature_type, 'development.h5')\n\n for model_num in range(0, Model_num):\n for target_num in range(0, Model_num):\n Model_target = Model_target_list[target_num]\n Model_target_folder = Model_target_folder_list[target_num]\n logging.info('model_num: {}\\ttarget_num: {}'.format(\n model_num, target_num))\n\n if validation:\n\n dev_train_csv = os.path.join(\n dataset_dir, subdir, 'evaluation_setup', 'fold{}_train.txt'.format(holdout_fold))\n\n dev_validate_csv = os.path.join(\n dataset_dir, subdir, 'evaluation_setup', 'fold{}_devel.txt'.format(holdout_fold))\n\n model_target_path = os.path.join(workspace, 'models', Model_target_folder, subdir, filename,\n 'holdout_fold={}'.format(holdout_fold), 'md_10000_iters.tar')\n\n model_attacker_path = os.path.join(workspace, 'models', Model_attacker_folder, subdir, filename,\n 'holdout_fold={}'.format(\n holdout_fold),\n 'md_{}_iters.tar'.format(iteration*(model_num+1)))\n\n else:\n # dev_train_csv = os.path.join(dataset_dir, subdir, 'evaluation_setup',\n # 'fold{}_traindevel.txt'.format(holdout_fold))\n dev_train_csv = \"/home/nwang/emotion/train_dataset.csv\"\n # dev_validate_csv = os.path.join(dataset_dir, subdir, 'evaluation_setup',\n # 'fold{}_test.txt'.format(holdout_fold))\n dev_validate_csv = \"/home/nwang/emotion/dev_dataset.csv\"\n # models_target_path = os.path.join(workspace, 'models', Model_target_folder, subdir, filename,\n # 'full_train', 'md_10000_iters.tar')\n model_target_path = os.path.join(workspace, 'models', Model_target_folder, subdir, filename,\n 'full_train', 'md_10000_iters.tar')\n\n # dev_train_csv = os.path.join(\n # dataset_dir, subdir, 'evaluation_setup', 'fold{}_traindevel.txt'.format(holdout_fold))\n\n # dev_validate_csv = os.path.join(\n # dataset_dir, subdir, 'evaluation_setup', 'fold{}_test.txt'.format(holdout_fold))\n\n # model_target_path = os.path.join(workspace, 'models', Model_target_folder, subdir, filename,\n # 'full_train', 'md_10000_iters.tar')\n\n model_attacker_path = os.path.join(workspace, 'models', Model_attacker_folder, subdir, filename,\n 'full_train',\n 'md_{}_iters.tar'.format(iteration*(model_num+1)))\n\n # Load model\n model_attacker = Model_attacker()\n model_target = Model_target(classes_num)\n\n checkpoint = torch.load(model_attacker_path)\n model_attacker.load_state_dict(checkpoint['state_dict'])\n del checkpoint\n checkpoint = torch.load(model_target_path)\n model_target.load_state_dict(checkpoint['state_dict'])\n del checkpoint\n\n if cuda:\n model_attacker.cuda()\n model_target.cuda()\n\n # Predict & evaluate\n for device in devices:\n\n print('Device: {}'.format(device))\n\n # Data generator\n generator = DataGenerator(hdf5_path=hdf5_path,\n batch_size=batch_size,\n dev_train_csv=dev_train_csv,\n dev_validate_csv=dev_validate_csv)\n\n generate_func = generator.generate_validate(data_type='validate',\n devices=device,\n shuffle=False)\n\n # Inference\n dict = forward_test(model_attacker=model_attacker,\n model_target=model_target,\n generate_func=generate_func,\n cuda=cuda,\n return_target=True)\n\n outputs = dict['output'] # (audios_num, classes_num)\n targets = dict['target'] # (audios_num, classes_num)\n outputs_adv = dict['output_adv'] # (audios_num, classes_num)\n inputs_heatmap = dict['inputs_heatmap']\n outputs_heatmap = dict['outputs_heatmap']\n noise_heatmap = dict['noise_heatmap']\n audio_names = dict['audio_name']\n\n predictions = np.argmax(outputs, axis=-1)\n predictions_adv = np.argmax(outputs_adv, axis=-1)\n\n classes_num = outputs.shape[-1]\n\n # Evaluate\n confusion_matrix = calculate_confusion_matrix(\n targets, predictions, classes_num)\n\n class_wise_accuracy = calculate_accuracy(\n targets, predictions, classes_num)\n\n confusion_matrix_adv = calculate_confusion_matrix(\n targets, predictions_adv, classes_num)\n\n class_wise_accuracy_adv = calculate_accuracy(\n targets, predictions_adv, classes_num)\n\n # Print\n print_accuracy(class_wise_accuracy, labels)\n print('confusion_matrix: \\n', confusion_matrix)\n\n print_accuracy(class_wise_accuracy_adv, labels)\n print('confusion_matrix: \\n', confusion_matrix_adv)\n\n mseloss = dict['mseloss']\n print('mseloss: ', mseloss)\n\n ##########################################################################\n heatmaps_input = []\n heatmaps_output = []\n heatmaps_noise = []\n heatmaps_info = []\n for i in range(0, len(predictions)):\n pred_num = predictions[i]\n pred_num_adv = predictions_adv[i]\n if pred_num == targets[i] and pred_num_adv != targets[i]:\n heatmaps_input.append(inputs_heatmap[i])\n heatmaps_output.append(outputs_heatmap[i])\n heatmaps_noise.append(noise_heatmap[i])\n heatmaps_info.append(\n [audio_names[i], pred_num, pred_num_adv, outputs[i][pred_num], outputs_adv[i][pred_num_adv]])\n\n # print 'final heatmaps number: ' + str(len(heatmaps))\n\n # save\n if validation:\n file_name = 'devel'\n else:\n file_name = 'test'\n\n folder_name = 'heatmap' # output path folder#####\n if not os.path.exists(os.path.join(workspace, 'models', folder_name)):\n create_folder(os.path.join(\n workspace, 'models', folder_name))\n\n np.save(os.path.join(workspace, 'models', folder_name, \"model_num\"+str(model_num) +\n \"target_num\"+str(target_num)+\"-\"+file_name+\"-heatmap.npy\"), heatmaps_input)\n np.save(os.path.join(workspace, 'models', folder_name, \"model_num\"+str(model_num) +\n \"target_num\"+str(target_num)+\"-\"+file_name+\"-heatmap_adv.npy\"), heatmaps_output)\n np.save(os.path.join(workspace, 'models', folder_name, \"model_num\"+str(model_num) +\n \"target_num\"+str(target_num)+\"-\"+file_name+\"-heatmap_noise.npy\"), heatmaps_noise)\n np.save(os.path.join(workspace, 'models', folder_name, \"model_num\"+str(model_num) +\n \"target_num\"+str(target_num)+\"-\"+file_name+\"-info.npy\"), heatmaps_info)\n ###########################################################################\n\n # Plot confusion matrix\n# \tplot_confusion_matrix(\n# \tconfusion_matrix,\n# \ttitle='Device {}'.format(device.upper()),\n# \tlabels=labels,\n# \tvalues=class_wise_accuracy,\n# \tpath=os.path.join(workspace, 'logs', 'main_pytorch', 'fig-confmat-device-'+device+'.pdf'))\n\n\nif __name__ == '__main__':\n '''\n ######################################################################\n DATASET_DIR = \"/home/zhao/NAS/data_work/Zhao/wav_DEMoS/zhao_code\"\n WORKSPACE = \"/home/zhao/NAS/data_work/Zhao/wav_DEMoS/zhao_code/pub_demos_cnn\"\n DEV_SUBTASK_A_DIR = \"demos_data\"\n\n parser_train = argparse.ArgumentParser(description='Example of parser. ')\n\n parser_train.add_argument('--mode', type=str, default='train')\n parser_train.add_argument('--dataset_dir', type=str, default=DATASET_DIR)\n parser_train.add_argument('--subdir', type=str, default=DEV_SUBTASK_A_DIR)\n parser_train.add_argument('--workspace', type=str, default=WORKSPACE)\n parser_train.add_argument('--feature_type', type=str, default='logmel')\n# parser_train.add_argument('--iteration', type=str, default=2800)\n parser_train.add_argument('--holdout_fold', type=str, default=1)\n parser_train.add_argument('--validation', action='store_true', default=True)\n parser_train.add_argument('--cuda', action='store_true', default=True)\n parser_train.add_argument('--mini_data', action='store_true', default=False) # what is this?\n\n args = parser_train.parse_args()\n\n args.filename = get_filename(__file__)\n\n # Create log\n logs_dir = os.path.join(args.workspace, 'logs', args.filename)\n create_logging(logs_dir, filemode='w')\n logging.info(args)\n\n if args.mode == 'train':\n train(args)\n elif args.mode == 'inference_validation':\n inference_validation(args)\n #######################################################################\n\n '''\n parser = argparse.ArgumentParser(description='Example of parser. ')\n subparsers = parser.add_subparsers(dest='mode')\n\n parser_train = subparsers.add_parser('train')\n parser_train.add_argument('--dataset_dir', type=str, required=True)\n parser_train.add_argument('--subdir', type=str, required=True)\n parser_train.add_argument('--workspace', type=str, required=True)\n parser_train.add_argument('--feature_type', type=str, default='logmel')\n parser_train.add_argument('--validation', action='store_true', default=False)\n parser_train.add_argument('--holdout_fold', type=int)\n\n parser_train.add_argument('--cuda', action='store_true', default=False)\n parser_train.add_argument('--mini_data', action='store_true', default=False)\n\n parser_inference_validation_data = subparsers.add_parser('inference_validation_data')\n parser_inference_validation_data.add_argument('--dataset_dir', type=str, required=True)\n parser_inference_validation_data.add_argument('--subdir', type=str, required=True)\n parser_inference_validation_data.add_argument('--workspace', type=str, required=True)\n parser_inference_validation_data.add_argument('--feature_type', type=str, default='logmel')\n parser_inference_validation_data.add_argument('--validation', action='store_true', default=False)\n parser_inference_validation_data.add_argument('--holdout_fold', type=int, required=True)\n\n parser_inference_validation_data.add_argument('--iteration', type=int, required=True)\n parser_inference_validation_data.add_argument('--cuda', action='store_true', default=False)\n\n parser_inference_validation_heatmap = subparsers.add_parser('inference_validation_heatmap')\n parser_inference_validation_heatmap.add_argument('--dataset_dir', type=str, required=True)\n parser_inference_validation_heatmap.add_argument('--subdir', type=str, required=True)\n parser_inference_validation_heatmap.add_argument('--workspace', type=str, required=True)\n parser_inference_validation_heatmap.add_argument('--feature_type', type=str, default='logmel')\n parser_inference_validation_heatmap.add_argument('--validation', action='store_true', default=False)\n parser_inference_validation_heatmap.add_argument('--holdout_fold', type=int, required=True)\n parser_inference_validation_heatmap.add_argument('--iteration', type=int, required=True)\n parser_inference_validation_heatmap.add_argument('--cuda', action='store_true', default=False)\n\n args = parser.parse_args()\n\n args.filename = get_filename(__file__)\n\n # Create log\n logs_dir = os.path.join(args.workspace, 'logs', args.filename)\n create_logging(logs_dir, filemode='w')\n logging.info(args)\n\n if args.mode == 'train':\n train(args)\n\n elif args.mode == 'inference_validation_data':\n inference_validation_data(args)\n\n elif args.mode == 'inference_validation_heatmap':\n inference_validation_heatmap(args)\n\n else:\n raise Exception('Error argument!')\n"
] |
[
[
"torch.LongTensor",
"torch.max",
"torch.Tensor",
"torch.load",
"torch.eye",
"torch.sum",
"torch.zeros_like",
"numpy.concatenate",
"torch.nn.functional.mse_loss",
"numpy.argmax",
"torch.save"
]
] |
arstropica/Real-Time-Voice-Cloning
|
[
"9d879877846a2d71366f6c436473fca22362b643"
] |
[
"synthesizer/synthesize.py"
] |
[
"import torch\nfrom torch.utils.data import DataLoader\nfrom synthesizer.hparams import hparams_debug_string\nfrom synthesizer.synthesizer_dataset import SynthesizerDataset, collate_synthesizer\nfrom synthesizer.models.tacotron import Tacotron\nfrom synthesizer.utils.text import text_to_sequence\nfrom synthesizer.utils.symbols import symbols\nimport numpy as np\nfrom pathlib import Path\nfrom tqdm import tqdm\nimport traceback\nfrom fast_dataloader.dataloader import FastDataLoader\n\n\ndef run_synthesis(in_dir, out_dir, model_dir, hparams):\n # This generates ground truth-aligned mels for vocoder training\n synth_dir = Path(out_dir).joinpath(\"mels_gta\")\n synth_dir.mkdir(exist_ok=True)\n print(hparams_debug_string(hparams))\n\n # Check for GPU\n if torch.cuda.is_available():\n device = torch.device(\"cuda\")\n if hparams.synthesis_batch_size % torch.cuda.device_count() != 0:\n raise ValueError(\"`hparams.synthesis_batch_size` must be evenly divisible by n_gpus!\")\n else:\n device = torch.device(\"cpu\")\n print(\"Synthesizer using device:\", device)\n\n # Instantiate Tacotron model\n model = Tacotron(embed_dims=hparams.tts_embed_dims,\n num_chars=len(symbols),\n encoder_dims=hparams.tts_encoder_dims,\n decoder_dims=hparams.tts_decoder_dims,\n n_mels=hparams.num_mels,\n fft_bins=hparams.num_mels,\n postnet_dims=hparams.tts_postnet_dims,\n encoder_K=hparams.tts_encoder_K,\n lstm_dims=hparams.tts_lstm_dims,\n postnet_K=hparams.tts_postnet_K,\n num_highways=hparams.tts_num_highways,\n dropout=0., # Use zero dropout for gta mels\n stop_threshold=hparams.tts_stop_threshold,\n speaker_embedding_size=hparams.speaker_embedding_size).to(device)\n\n # Load the weights\n model_dir = Path(model_dir)\n model_fpath = model_dir.joinpath(model_dir.stem).with_suffix(\".pt\")\n print(\"\\nLoading weights at %s\" % model_fpath)\n model.load(model_fpath)\n print(\"Tacotron weights loaded from step %d\" % model.step)\n\n # Synthesize using same reduction factor as the model is currently trained\n r = np.int32(model.r)\n\n # Set model to eval mode (disable gradient and zoneout)\n model.eval()\n\n # Initialize the dataset\n in_dir = Path(in_dir)\n metadata_fpath = in_dir.joinpath(\"train.txt\")\n mel_dir = in_dir.joinpath(\"mels\")\n embed_dir = in_dir.joinpath(\"embeds\")\n\n dataset = SynthesizerDataset(metadata_fpath, mel_dir, embed_dir, hparams)\n data_loader = FastDataLoader(dataset,\n collate_fn=lambda batch: collate_synthesizer(batch, r, hparams),\n batch_size=hparams.synthesis_batch_size,\n #num_workers=2,\n shuffle=False,\n pin_memory=True)\n\n # Generate GTA mels\n meta_out_fpath = Path(out_dir).joinpath(\"synthesized.txt\")\n with open(meta_out_fpath, \"w\") as file:\n for i, (texts, mels, embeds, idx) in tqdm(enumerate(data_loader), total=len(data_loader)):\n texts = texts.to(device)\n mels = mels.to(device)\n embeds = embeds.to(device)\n\n print(\"\\nTorch Cuda Device Count: \" + str(torch.cuda.device_count()))\n # Parallelize model onto GPUS using workaround due to python bug\n try:\n if device.type == \"cuda\" and torch.cuda.device_count() > 1:\n mels_out, _, _, _ = data_parallel_workaround(model, texts, mels, embeds)\n else:\n mels_out, _, _, _ = model(texts, mels, embeds)\n except ValueError as e:\n err = traceback.format_exc()\n print(err)\n quit()\n\n for j, k in enumerate(idx):\n # Note: outputs mel-spectrogram files and target ones have same names, just different folders\n mel_filename = Path(synth_dir).joinpath(dataset.metadata[k][1])\n mel_out = mels_out[j].detach().cpu().numpy().T\n\n # Use the length of the ground truth mel to remove padding from the generated mels\n mel_out = mel_out[:int(dataset.metadata[k][4])]\n\n # Write the spectrogram to disk\n np.save(mel_filename, mel_out, allow_pickle=False)\n\n # Write metadata into the synthesized file\n file.write(\"|\".join(dataset.metadata[k]))\n"
] |
[
[
"numpy.int32",
"numpy.save",
"torch.cuda.is_available",
"torch.device",
"torch.cuda.device_count"
]
] |
scienceopen/cvhst
|
[
"0613fdcc11cd086cdd375aae05677b33bfbbcfd0"
] |
[
"ionosphereAI/getpassivefm.py"
] |
[
"#!/usr/bin/env python\nimport h5py\nfrom datetime import datetime as DT\nfrom numpy import log10, absolute, median, ascontiguousarray\nfrom pytz import UTC\n\"\"\"\nMichael Hirsch\nRead Haystack Passive FM radar frame, one frame per file\n\"\"\"\n\n\ndef getfmradarframe(fn):\n with h5py.File(fn, 'r') as f:\n # transpose makes it Fortran order, which cv2.cv.fromarray doesn't like\n ambiguity = ascontiguousarray(f['/ambiguity/ambiguity'][:].T)\n range_km = f['/ambiguity/range_axis'][:]/1e3\n velocity_mps = f['/ambiguity/velocity_axis'][:]\n dtime = DT.utcfromtimestamp(f['/ambiguity'].attrs.get('utc_second')).replace(tzinfo=UTC) # replace is required for tzaware\n integration_time = f['/ambiguity'].attrs.get('integration_time')\n\n logamb = log10(absolute(ambiguity))\n SCRdb = 10*log10(absolute(ambiguity/median(ambiguity)))\n\n return range_km, velocity_mps, SCRdb, dtime, integration_time, logamb\n"
] |
[
[
"numpy.ascontiguousarray",
"numpy.median",
"numpy.absolute"
]
] |
mburaksayici/tsfresh
|
[
"de5cc5f800ad7ab19995e5beb31638cab55fd4e7"
] |
[
"tsfresh/feature_extraction/feature_calculators.py"
] |
[
"# -*- coding: utf-8 -*-\n# This file as well as the whole tsfresh package are licenced under the MIT licence (see the LICENCE.txt)\n# Maximilian Christ (maximilianchrist.com), Blue Yonder Gmbh, 2016\n\"\"\"\nThis module contains the feature calculators that take time series as input and calculate the values of the feature.\nThere are two types of features:\n\n1. feature calculators which calculate a single number (simple)\n2. feature calculators which calculate a bunch of features for a list of parameters at once,\n to use e.g. cached results (combiner). They return a list of (key, value) pairs for each input parameter.\n\nThey are specified using the \"fctype\" parameter of each feature calculator, which is added using the\nset_property function. Only functions in this python module, which have a parameter called \"fctype\" are\nseen by tsfresh as a feature calculator. Others will not be calculated.\n\nFeature calculators of type combiner should return the concatenated parameters sorted\nalphabetically ascending.\n\"\"\"\n\nimport itertools\nimport functools\nimport warnings\nfrom tsfresh.utilities.string_manipulation import convert_to_output_format\nfrom builtins import range\nfrom collections import defaultdict\n\nimport numpy as np\nimport pandas as pd\nfrom numpy.linalg import LinAlgError\nfrom scipy.signal import cwt, find_peaks_cwt, ricker, welch\nfrom scipy.stats import linregress\nfrom statsmodels.tools.sm_exceptions import MissingDataError\nfrom matrixprofile.exceptions import NoSolutionPossible\nimport matrixprofile as mp\nimport stumpy\n\nwith warnings.catch_warnings():\n # Ignore warnings of the patsy package\n warnings.simplefilter(\"ignore\", DeprecationWarning)\n\n from statsmodels.tsa.ar_model import AR\nfrom statsmodels.tsa.stattools import acf, adfuller, pacf\n\n# todo: make sure '_' works in parameter names in all cases, add a warning if not\n\n\ndef _roll(a, shift):\n \"\"\"\n Roll 1D array elements. Improves the performance of numpy.roll() by reducing the overhead introduced from the\n flexibility of the numpy.roll() method such as the support for rolling over multiple dimensions.\n\n Elements that roll beyond the last position are re-introduced at the beginning. Similarly, elements that roll\n back beyond the first position are re-introduced at the end (with negative shift).\n\n Examples\n --------\n >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n >>> _roll(x, shift=2)\n >>> array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])\n\n >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n >>> _roll(x, shift=-2)\n >>> array([2, 3, 4, 5, 6, 7, 8, 9, 0, 1])\n\n >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n >>> _roll(x, shift=12)\n >>> array([8, 9, 0, 1, 2, 3, 4, 5, 6, 7])\n\n Benchmark\n ---------\n >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n >>> %timeit _roll(x, shift=2)\n >>> 1.89 µs ± 341 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n >>> x = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])\n >>> %timeit np.roll(x, shift=2)\n >>> 11.4 µs ± 776 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)\n\n :param a: the input array\n :type a: array_like\n :param shift: the number of places by which elements are shifted\n :type shift: int\n\n :return: shifted array with the same shape as a\n :return type: ndarray\n \"\"\"\n if not isinstance(a, np.ndarray):\n a = np.asarray(a)\n idx = shift % len(a)\n return np.concatenate([a[-idx:], a[:-idx]])\n\n\ndef _get_length_sequences_where(x):\n \"\"\"\n This method calculates the length of all sub-sequences where the array x is either True or 1.\n\n Examples\n --------\n >>> x = [0,1,0,0,1,1,1,0,0,1,0,1,1]\n >>> _get_length_sequences_where(x)\n >>> [1, 3, 1, 2]\n\n >>> x = [0,True,0,0,True,True,True,0,0,True,0,True,True]\n >>> _get_length_sequences_where(x)\n >>> [1, 3, 1, 2]\n\n >>> x = [0,True,0,0,1,True,1,0,0,True,0,1,True]\n >>> _get_length_sequences_where(x)\n >>> [1, 3, 1, 2]\n\n :param x: An iterable containing only 1, True, 0 and False values\n :return: A list with the length of all sub-sequences where the array is either True or False. If no ones or Trues\n contained, the list [0] is returned.\n \"\"\"\n if len(x) == 0:\n return [0]\n else:\n res = [len(list(group)) for value, group in itertools.groupby(x) if value == 1]\n return res if len(res) > 0 else [0]\n\n\ndef _estimate_friedrich_coefficients(x, m, r):\n \"\"\"\n Coefficients of polynomial :math:`h(x)`, which has been fitted to\n the deterministic dynamics of Langevin model\n .. math::\n \\\\dot{x}(t) = h(x(t)) + \\\\mathcal{N}(0,R)\n\n As described by\n\n Friedrich et al. (2000): Physics Letters A 271, p. 217-222\n *Extracting model equations from experimental data*\n\n For short time-series this method is highly dependent on the parameters.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param m: order of polynomial to fit for estimating fixed points of dynamics\n :type m: int\n :param r: number of quantiles to use for averaging\n :type r: float\n\n :return: coefficients of polynomial of deterministic dynamics\n :return type: ndarray\n \"\"\"\n assert m > 0, \"Order of polynomial need to be positive integer, found {}\".format(m)\n\n df = pd.DataFrame({'signal': x[:-1], 'delta': np.diff(x)})\n try:\n df['quantiles'] = pd.qcut(df.signal, r)\n except ValueError:\n return [np.NaN] * (m + 1)\n\n quantiles = df.groupby('quantiles')\n\n result = pd.DataFrame({'x_mean': quantiles.signal.mean(), 'y_mean': quantiles.delta.mean()})\n result.dropna(inplace=True)\n\n try:\n return np.polyfit(result.x_mean, result.y_mean, deg=m)\n except (np.linalg.LinAlgError, ValueError):\n return [np.NaN] * (m + 1)\n\n\ndef _aggregate_on_chunks(x, f_agg, chunk_len):\n \"\"\"\n Takes the time series x and constructs a lower sampled version of it by applying the aggregation function f_agg on\n consecutive chunks of length chunk_len\n\n :param x: the time series to calculate the aggregation of\n :type x: numpy.ndarray\n :param f_agg: The name of the aggregation function that should be an attribute of the pandas.Series\n :type f_agg: str\n :param chunk_len: The size of the chunks where to aggregate the time series\n :type chunk_len: int\n :return: A list of the aggregation function over the chunks\n :return type: list\n \"\"\"\n return [getattr(x[i * chunk_len: (i + 1) * chunk_len], f_agg)() for i in range(int(np.ceil(len(x) / chunk_len)))]\n\n\ndef _into_subchunks(x, subchunk_length, every_n=1):\n \"\"\"\n Split the time series x into subwindows of length \"subchunk_length\", starting every \"every_n\".\n\n For example, the input data if [0, 1, 2, 3, 4, 5, 6] will be turned into a matrix\n\n 0 2 4\n 1 3 5\n 2 4 6\n\n with the settings subchunk_length = 3 and every_n = 2\n \"\"\"\n len_x = len(x)\n\n assert subchunk_length > 1\n assert every_n > 0\n\n # how often can we shift a window of size subchunk_length over the input?\n num_shifts = (len_x - subchunk_length) // every_n + 1\n shift_starts = every_n * np.arange(num_shifts)\n indices = np.arange(subchunk_length)\n\n indexer = np.expand_dims(indices, axis=0) + np.expand_dims(shift_starts, axis=1)\n return np.asarray(x)[indexer]\n\n\ndef set_property(key, value):\n \"\"\"\n This method returns a decorator that sets the property key of the function to value\n \"\"\"\n def decorate_func(func):\n setattr(func, key, value)\n if func.__doc__ and key == \"fctype\":\n func.__doc__ = func.__doc__ + \"\\n\\n *This function is of type: \" + value + \"*\\n\"\n return func\n return decorate_func\n\n\n@set_property(\"fctype\", \"simple\")\ndef variance_larger_than_standard_deviation(x):\n \"\"\"\n Is variance higher than the standard deviation?\n\n Boolean variable denoting if the variance of x is greater than its standard deviation. Is equal to variance of x\n being larger than 1\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: bool\n \"\"\"\n y = np.var(x)\n return y > np.sqrt(y)\n\n\n@set_property(\"fctype\", \"simple\")\ndef ratio_beyond_r_sigma(x, r):\n \"\"\"\n Ratio of values that are more than r * std(x) (so r times sigma) away from the mean of x.\n\n :param x: the time series to calculate the feature of\n :type x: iterable\n :param r: the ratio to compare with\n :type r: float\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.sum(np.abs(x - np.mean(x)) > r * np.std(x)) / x.size\n\n\n@set_property(\"fctype\", \"simple\")\ndef large_standard_deviation(x, r):\n \"\"\"\n Does time series have *large* standard deviation?\n\n Boolean variable denoting if the standard dev of x is higher than 'r' times the range = difference between max and\n min of x. Hence it checks if\n\n .. math::\n\n std(x) > r * (max(X)-min(X))\n\n According to a rule of the thumb, the standard deviation should be a forth of the range of the values.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param r: the percentage of the range to compare with\n :type r: float\n :return: the value of this feature\n :return type: bool\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.std(x) > (r * (np.max(x) - np.min(x)))\n\n\n@set_property(\"fctype\", \"combiner\")\ndef symmetry_looking(x, param):\n \"\"\"\n Boolean variable denoting if the distribution of x *looks symmetric*. This is the case if\n\n .. math::\n\n | mean(X)-median(X)| < r * (max(X)-min(X))\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"r\": x} with x (float) is the percentage of the range to compare with\n :type param: list\n :return: the value of this feature\n :return type: bool\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n mean_median_difference = np.abs(np.mean(x) - np.median(x))\n max_min_difference = np.max(x) - np.min(x)\n return [(\"r_{}\".format(r[\"r\"]), mean_median_difference < (r[\"r\"] * max_min_difference))\n for r in param]\n\n\n@set_property(\"fctype\", \"simple\")\ndef has_duplicate_max(x):\n \"\"\"\n Checks if the maximum value of x is observed more than once\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: bool\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.sum(x == np.max(x)) >= 2\n\n\n@set_property(\"fctype\", \"simple\")\ndef has_duplicate_min(x):\n \"\"\"\n Checks if the minimal value of x is observed more than once\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: bool\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.sum(x == np.min(x)) >= 2\n\n\n@set_property(\"fctype\", \"simple\")\ndef has_duplicate(x):\n \"\"\"\n Checks if any value in x occurs more than once\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: bool\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return x.size != np.unique(x).size\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef sum_values(x):\n \"\"\"\n Calculates the sum over the time series values\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if len(x) == 0:\n return 0\n\n return np.sum(x)\n\n\n@set_property(\"fctype\", \"combiner\")\ndef agg_autocorrelation(x, param):\n \"\"\"\n Descriptive statistics on the autocorrelation of the time series.\n\n Calculates the value of an aggregation function :math:`f_{agg}` (e.g. the variance or the mean) over the\n autocorrelation :math:`R(l)` for different lags. The autocorrelation :math:`R(l)` for lag :math:`l` is defined as\n\n .. math::\n\n R(l) = \\\\frac{1}{(n-l)\\\\sigma^2} \\\\sum_{t=1}^{n-l}(X_{t}-\\\\mu )(X_{t+l}-\\\\mu)\n\n where :math:`X_i` are the values of the time series, :math:`n` its length. Finally, :math:`\\\\sigma^2` and\n :math:`\\\\mu` are estimators for its variance and mean\n (See `Estimation of the Autocorrelation function <http://en.wikipedia.org/wiki/Autocorrelation#Estimation>`_).\n\n The :math:`R(l)` for different lags :math:`l` form a vector. This feature calculator applies the aggregation\n function :math:`f_{agg}` to this vector and returns\n\n .. math::\n\n f_{agg} \\\\left( R(1), \\\\ldots, R(m)\\\\right) \\\\quad \\\\text{for} \\\\quad m = max(n, maxlag).\n\n Here :math:`maxlag` is the second parameter passed to this function.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"f_agg\": x, \"maxlag\", n} with x str, the name of a numpy function\n (e.g. \"mean\", \"var\", \"std\", \"median\"), its the name of the aggregator function that is applied to the\n autocorrelations. Further, n is an int and the maximal number of lags to consider.\n :type param: list\n :return: the value of this feature\n :return type: float\n \"\"\"\n # if the time series is longer than the following threshold, we use fft to calculate the acf\n THRESHOLD_TO_USE_FFT = 1250\n var = np.var(x)\n n = len(x)\n max_maxlag = max([config[\"maxlag\"] for config in param])\n\n if np.abs(var) < 10**-10 or n == 1:\n a = [0] * len(x)\n else:\n a = acf(x, unbiased=True, fft=n > THRESHOLD_TO_USE_FFT, nlags=max_maxlag)[1:]\n return [(\"f_agg_\\\"{}\\\"__maxlag_{}\".format(config[\"f_agg\"], config[\"maxlag\"]),\n getattr(np, config[\"f_agg\"])(a[:int(config[\"maxlag\"])])) for config in param]\n\n\n@set_property(\"fctype\", \"combiner\")\ndef partial_autocorrelation(x, param):\n \"\"\"\n Calculates the value of the partial autocorrelation function at the given lag.\n\n The lag `k` partial autocorrelation of a time series :math:`\\\\lbrace x_t, t = 1 \\\\ldots T \\\\rbrace` equals the\n partial correlation of :math:`x_t` and :math:`x_{t-k}`, adjusted for the intermediate variables\n :math:`\\\\lbrace x_{t-1}, \\\\ldots, x_{t-k+1} \\\\rbrace` ([1]).\n\n Following [2], it can be defined as\n\n .. math::\n\n \\\\alpha_k = \\\\frac{ Cov(x_t, x_{t-k} | x_{t-1}, \\\\ldots, x_{t-k+1})}\n {\\\\sqrt{ Var(x_t | x_{t-1}, \\\\ldots, x_{t-k+1}) Var(x_{t-k} | x_{t-1}, \\\\ldots, x_{t-k+1} )}}\n\n with (a) :math:`x_t = f(x_{t-1}, \\\\ldots, x_{t-k+1})` and (b) :math:`x_{t-k} = f(x_{t-1}, \\\\ldots, x_{t-k+1})`\n being AR(k-1) models that can be fitted by OLS. Be aware that in (a), the regression is done on past values to\n predict :math:`x_t` whereas in (b), future values are used to calculate the past value :math:`x_{t-k}`.\n It is said in [1] that \"for an AR(p), the partial autocorrelations [ :math:`\\\\alpha_k` ] will be nonzero for `k<=p`\n and zero for `k>p`.\"\n With this property, it is used to determine the lag of an AR-Process.\n\n .. rubric:: References\n\n | [1] Box, G. E., Jenkins, G. M., Reinsel, G. C., & Ljung, G. M. (2015).\n | Time series analysis: forecasting and control. John Wiley & Sons.\n | [2] https://onlinecourses.science.psu.edu/stat510/node/62\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"lag\": val} with int val indicating the lag to be returned\n :type param: list\n :return: the value of this feature\n :return type: float\n \"\"\"\n # Check the difference between demanded lags by param and possible lags to calculate (depends on len(x))\n max_demanded_lag = max([lag[\"lag\"] for lag in param])\n n = len(x)\n\n # Check if list is too short to make calculations\n if n <= 1:\n pacf_coeffs = [np.nan] * (max_demanded_lag + 1)\n else:\n # https://github.com/statsmodels/statsmodels/pull/6846\n # PACF limits lag length to 50% of sample size.\n if max_demanded_lag >= n // 2:\n max_lag = n // 2 - 1\n else:\n max_lag = max_demanded_lag\n if max_lag > 0:\n pacf_coeffs = list(pacf(x, method=\"ld\", nlags=max_lag))\n pacf_coeffs = pacf_coeffs + [np.nan] * max(0, (max_demanded_lag - max_lag))\n else:\n pacf_coeffs = [np.nan] * (max_demanded_lag + 1)\n\n return [(\"lag_{}\".format(lag[\"lag\"]), pacf_coeffs[lag[\"lag\"]]) for lag in param]\n\n\n@set_property(\"fctype\", \"combiner\")\ndef augmented_dickey_fuller(x, param):\n \"\"\"\n Does the time series have a unit root?\n\n The Augmented Dickey-Fuller test is a hypothesis test which checks whether a unit root is present in a time\n series sample. This feature calculator returns the value of the respective test statistic.\n\n See the statsmodels implementation for references and more details.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"attr\": x, \"autolag\": y} with x str, either \"teststat\", \"pvalue\" or \"usedlag\"\n and with y str, either of \"AIC\", \"BIC\", \"t-stats\" or None (See the documentation of adfuller() in\n statsmodels).\n :type param: list\n :return: the value of this feature\n :return type: float\n \"\"\"\n\n @functools.lru_cache()\n def compute_adf(autolag):\n try:\n return adfuller(x, autolag=autolag)\n except LinAlgError:\n return np.NaN, np.NaN, np.NaN\n except ValueError: # occurs if sample size is too small\n return np.NaN, np.NaN, np.NaN\n except MissingDataError: # is thrown for e.g. inf or nan in the data\n return np.NaN, np.NaN, np.NaN\n\n res = []\n for config in param:\n autolag = config.get(\"autolag\", \"AIC\")\n\n adf = compute_adf(autolag)\n index = 'attr_\"{}\"__autolag_\"{}\"'.format(config[\"attr\"], autolag)\n\n if config[\"attr\"] == \"teststat\":\n res.append((index, adf[0]))\n elif config[\"attr\"] == \"pvalue\":\n res.append((index, adf[1]))\n elif config[\"attr\"] == \"usedlag\":\n res.append((index, adf[2]))\n else:\n res.append((index, np.NaN))\n return res\n\n\n@set_property(\"fctype\", \"simple\")\ndef abs_energy(x):\n \"\"\"\n Returns the absolute energy of the time series which is the sum over the squared values\n\n .. math::\n\n E = \\\\sum_{i=1,\\\\ldots, n} x_i^2\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.dot(x, x)\n\n\n@set_property(\"fctype\", \"simple\")\ndef cid_ce(x, normalize):\n \"\"\"\n This function calculator is an estimate for a time series complexity [1] (A more complex time series has more peaks,\n valleys etc.). It calculates the value of\n\n .. math::\n\n \\\\sqrt{ \\\\sum_{i=1}^{n-1} ( x_{i} - x_{i-1})^2 }\n\n .. rubric:: References\n\n | [1] Batista, Gustavo EAPA, et al (2014).\n | CID: an efficient complexity-invariant distance for time series.\n | Data Mining and Knowledge Discovery 28.3 (2014): 634-669.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param normalize: should the time series be z-transformed?\n :type normalize: bool\n\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n if normalize:\n s = np.std(x)\n if s != 0:\n x = (x - np.mean(x)) / s\n else:\n return 0.0\n\n x = np.diff(x)\n return np.sqrt(np.dot(x, x))\n\n\n@set_property(\"fctype\", \"simple\")\ndef mean_abs_change(x):\n \"\"\"\n Average over first differences.\n\n Returns the mean over the absolute differences between subsequent time series values which is\n\n .. math::\n\n \\\\frac{1}{n} \\\\sum_{i=1,\\\\ldots, n-1} | x_{i+1} - x_{i}|\n\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.mean(np.abs(np.diff(x)))\n\n\n@set_property(\"fctype\", \"simple\")\ndef mean_change(x):\n \"\"\"\n Average over time series differences.\n\n Returns the mean over the differences between subsequent time series values which is\n\n .. math::\n\n \\\\frac{1}{n-1} \\\\sum_{i=1,\\\\ldots, n-1} x_{i+1} - x_{i} = \\\\frac{1}{n-1} (x_{n} - x_{1})\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n x = np.asarray(x)\n return (x[-1] - x[0]) / (len(x) - 1) if len(x) > 1 else np.NaN\n\n\n@set_property(\"fctype\", \"simple\")\ndef mean_second_derivative_central(x):\n \"\"\"\n Returns the mean value of a central approximation of the second derivative\n\n .. math::\n\n \\\\frac{1}{2(n-2)} \\\\sum_{i=1,\\\\ldots, n-1} \\\\frac{1}{2} (x_{i+2} - 2 \\\\cdot x_{i+1} + x_i)\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n x = np.asarray(x)\n return (x[-1] - x[-2] - x[1] + x[0]) / (2 * (len(x) - 2)) if len(x) > 2 else np.NaN\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef median(x):\n \"\"\"\n Returns the median of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.median(x)\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef mean(x):\n \"\"\"\n Returns the mean of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.mean(x)\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef length(x):\n \"\"\"\n Returns the length of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: int\n \"\"\"\n return len(x)\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef standard_deviation(x):\n \"\"\"\n Returns the standard deviation of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.std(x)\n\n\n@set_property(\"fctype\", \"simple\")\ndef variation_coefficient(x):\n \"\"\"\n Returns the variation coefficient (standard error / mean, give relative value of variation around mean) of x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n mean = np.mean(x)\n if mean != 0:\n return np.std(x) / mean\n else:\n return np.nan\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef variance(x):\n \"\"\"\n Returns the variance of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.var(x)\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"input\", \"pd.Series\")\ndef skewness(x):\n \"\"\"\n Returns the sample skewness of x (calculated with the adjusted Fisher-Pearson standardized\n moment coefficient G1).\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, pd.Series):\n x = pd.Series(x)\n return pd.Series.skew(x)\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"input\", \"pd.Series\")\ndef kurtosis(x):\n \"\"\"\n Returns the kurtosis of x (calculated with the adjusted Fisher-Pearson standardized\n moment coefficient G2).\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, pd.Series):\n x = pd.Series(x)\n return pd.Series.kurtosis(x)\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef root_mean_square(x):\n \"\"\"\n Returns the root mean square (rms) of the time series.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.sqrt(np.mean(np.square(x))) if len(x) > 0 else np.NaN\n\n\n@set_property(\"fctype\", \"simple\")\ndef absolute_sum_of_changes(x):\n \"\"\"\n Returns the sum over the absolute value of consecutive changes in the series x\n\n .. math::\n\n \\\\sum_{i=1, \\\\ldots, n-1} \\\\mid x_{i+1}- x_i \\\\mid\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.sum(np.abs(np.diff(x)))\n\n\n@set_property(\"fctype\", \"simple\")\ndef longest_strike_below_mean(x):\n \"\"\"\n Returns the length of the longest consecutive subsequence in x that is smaller than the mean of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.max(_get_length_sequences_where(x < np.mean(x))) if x.size > 0 else 0\n\n\n@set_property(\"fctype\", \"simple\")\ndef longest_strike_above_mean(x):\n \"\"\"\n Returns the length of the longest consecutive subsequence in x that is bigger than the mean of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.max(_get_length_sequences_where(x > np.mean(x))) if x.size > 0 else 0\n\n\n@set_property(\"fctype\", \"simple\")\ndef count_above_mean(x):\n \"\"\"\n Returns the number of values in x that are higher than the mean of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n m = np.mean(x)\n return np.where(x > m)[0].size\n\n\n@set_property(\"fctype\", \"simple\")\ndef count_below_mean(x):\n \"\"\"\n Returns the number of values in x that are lower than the mean of x\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n m = np.mean(x)\n return np.where(x < m)[0].size\n\n\n@set_property(\"fctype\", \"simple\")\ndef last_location_of_maximum(x):\n \"\"\"\n Returns the relative last location of the maximum value of x.\n The position is calculated relatively to the length of x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n x = np.asarray(x)\n return 1.0 - np.argmax(x[::-1]) / len(x) if len(x) > 0 else np.NaN\n\n\n@set_property(\"fctype\", \"simple\")\ndef first_location_of_maximum(x):\n \"\"\"\n Returns the first location of the maximum value of x.\n The position is calculated relatively to the length of x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.argmax(x) / len(x) if len(x) > 0 else np.NaN\n\n\n@set_property(\"fctype\", \"simple\")\ndef last_location_of_minimum(x):\n \"\"\"\n Returns the last location of the minimal value of x.\n The position is calculated relatively to the length of x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n x = np.asarray(x)\n return 1.0 - np.argmin(x[::-1]) / len(x) if len(x) > 0 else np.NaN\n\n\n@set_property(\"fctype\", \"simple\")\ndef first_location_of_minimum(x):\n \"\"\"\n Returns the first location of the minimal value of x.\n The position is calculated relatively to the length of x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n return np.argmin(x) / len(x) if len(x) > 0 else np.NaN\n\n\n@set_property(\"fctype\", \"simple\")\ndef percentage_of_reoccurring_values_to_all_values(x):\n \"\"\"\n Returns the percentage of values that are present in the time series\n more than once.\n\n len(different values occurring more than once) / len(different values)\n\n This means the percentage is normalized to the number of unique values,\n in contrast to the percentage_of_reoccurring_datapoints_to_all_datapoints.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if len(x) == 0:\n return np.nan\n\n unique, counts = np.unique(x, return_counts=True)\n\n if counts.shape[0] == 0:\n return 0\n\n return np.sum(counts > 1) / float(counts.shape[0])\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"input\", \"pd.Series\")\ndef percentage_of_reoccurring_datapoints_to_all_datapoints(x):\n \"\"\"\n Returns the percentage of non-unique data points. Non-unique means that they are\n contained another time in the time series again.\n\n # of data points occurring more than once / # of all data points\n\n This means the ratio is normalized to the number of data points in the time series,\n in contrast to the percentage_of_reoccurring_values_to_all_values.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if len(x) == 0:\n return np.nan\n\n if not isinstance(x, pd.Series):\n x = pd.Series(x)\n\n value_counts = x.value_counts()\n reoccuring_values = value_counts[value_counts > 1].sum()\n\n if np.isnan(reoccuring_values):\n return 0\n\n return reoccuring_values / x.size\n\n\n@set_property(\"fctype\", \"simple\")\ndef sum_of_reoccurring_values(x):\n \"\"\"\n Returns the sum of all values, that are present in the time series\n more than once.\n\n For example\n\n sum_of_reoccurring_values([2, 2, 2, 2, 1]) = 2\n\n as 2 is a reoccurring value, so it is summed up with all\n other reoccuring values (there is none), so the result is 2.\n\n This is in contrast to ``sum_of_reoccurring_data_points``,\n where each reoccuring value is only counted as often as\n it is present in the data.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n unique, counts = np.unique(x, return_counts=True)\n counts[counts < 2] = 0\n counts[counts > 1] = 1\n return np.sum(counts * unique)\n\n\n@set_property(\"fctype\", \"simple\")\ndef sum_of_reoccurring_data_points(x):\n \"\"\"\n Returns the sum of all data points, that are present in the time series\n more than once.\n\n For example\n\n sum_of_reoccurring_data_points([2, 2, 2, 2, 1]) = 8\n\n as 2 is a reoccurring value, so all 2's are summed up.\n\n This is in contrast to ``sum_of_reoccurring_values``,\n where each reoccuring value is only counted once.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n unique, counts = np.unique(x, return_counts=True)\n counts[counts < 2] = 0\n return np.sum(counts * unique)\n\n\n@set_property(\"fctype\", \"simple\")\ndef ratio_value_number_to_time_series_length(x):\n \"\"\"\n Returns a factor which is 1 if all values in the time series occur only once,\n and below one if this is not the case.\n In principle, it just returns\n\n # unique values / # values\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n if x.size == 0:\n return np.nan\n\n return np.unique(x).size / x.size\n\n\n@set_property(\"fctype\", \"combiner\")\ndef fft_coefficient(x, param):\n \"\"\"\n Calculates the fourier coefficients of the one-dimensional discrete Fourier Transform for real input by fast\n fourier transformation algorithm\n\n .. math::\n A_k = \\\\sum_{m=0}^{n-1} a_m \\\\exp \\\\left \\\\{ -2 \\\\pi i \\\\frac{m k}{n} \\\\right \\\\}, \\\\qquad k = 0,\n \\\\ldots , n-1.\n\n The resulting coefficients will be complex, this feature calculator can return the real part (attr==\"real\"),\n the imaginary part (attr==\"imag), the absolute value (attr=\"\"abs) and the angle in degrees (attr==\"angle).\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"coeff\": x, \"attr\": s} with x int and x >= 0, s str and in [\"real\", \"imag\",\n \"abs\", \"angle\"]\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n\n assert min([config[\"coeff\"] for config in param]) >= 0, \"Coefficients must be positive or zero.\"\n assert {config[\"attr\"] for config in param} <= {\"imag\", \"real\", \"abs\", \"angle\"}, \\\n 'Attribute must be \"real\", \"imag\", \"angle\" or \"abs\"'\n\n fft = np.fft.rfft(x)\n\n def complex_agg(x, agg):\n if agg == \"real\":\n return x.real\n elif agg == \"imag\":\n return x.imag\n elif agg == \"abs\":\n return np.abs(x)\n elif agg == \"angle\":\n return np.angle(x, deg=True)\n\n res = [complex_agg(fft[config[\"coeff\"]], config[\"attr\"]) if config[\"coeff\"] < len(fft)\n else np.NaN for config in param]\n index = ['attr_\"{}\"__coeff_{}'.format(config[\"attr\"], config[\"coeff\"]) for config in param]\n return zip(index, res)\n\n\n@set_property(\"fctype\", \"combiner\")\ndef fft_aggregated(x, param):\n \"\"\"\n Returns the spectral centroid (mean), variance, skew, and kurtosis of the absolute fourier transform spectrum.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"aggtype\": s} where s str and in [\"centroid\", \"variance\",\n \"skew\", \"kurtosis\"]\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n\n assert {config[\"aggtype\"] for config in param} <= {\"centroid\", \"variance\", \"skew\", \"kurtosis\"}, \\\n 'Attribute must be \"centroid\", \"variance\", \"skew\", \"kurtosis\"'\n\n def get_moment(y, moment):\n \"\"\"\n Returns the (non centered) moment of the distribution y:\n E[y**moment] = \\\\sum_i[index(y_i)^moment * y_i] / \\\\sum_i[y_i]\n\n :param y: the discrete distribution from which one wants to calculate the moment\n :type y: pandas.Series or np.array\n :param moment: the moment one wants to calcalate (choose 1,2,3, ... )\n :type moment: int\n :return: the moment requested\n :return type: float\n \"\"\"\n return y.dot(np.arange(len(y), dtype=float)**moment) / y.sum()\n\n def get_centroid(y):\n \"\"\"\n :param y: the discrete distribution from which one wants to calculate the centroid\n :type y: pandas.Series or np.array\n :return: the centroid of distribution y (aka distribution mean, first moment)\n :return type: float\n \"\"\"\n return get_moment(y, 1)\n\n def get_variance(y):\n \"\"\"\n :param y: the discrete distribution from which one wants to calculate the variance\n :type y: pandas.Series or np.array\n :return: the variance of distribution y\n :return type: float\n \"\"\"\n return get_moment(y, 2) - get_centroid(y) ** 2\n\n def get_skew(y):\n \"\"\"\n Calculates the skew as the third standardized moment.\n Ref: https://en.wikipedia.org/wiki/Skewness#Definition\n\n :param y: the discrete distribution from which one wants to calculate the skew\n :type y: pandas.Series or np.array\n :return: the skew of distribution y\n :return type: float\n \"\"\"\n\n variance = get_variance(y)\n # In the limit of a dirac delta, skew should be 0 and variance 0. However, in the discrete limit,\n # the skew blows up as variance --> 0, hence return nan when variance is smaller than a resolution of 0.5:\n if variance < 0.5:\n return np.nan\n else:\n return (\n get_moment(y, 3) - 3 * get_centroid(y) * variance - get_centroid(y)**3\n ) / get_variance(y)**(1.5)\n\n def get_kurtosis(y):\n \"\"\"\n Calculates the kurtosis as the fourth standardized moment.\n Ref: https://en.wikipedia.org/wiki/Kurtosis#Pearson_moments\n\n :param y: the discrete distribution from which one wants to calculate the kurtosis\n :type y: pandas.Series or np.array\n :return: the kurtosis of distribution y\n :return type: float\n \"\"\"\n\n variance = get_variance(y)\n # In the limit of a dirac delta, kurtosis should be 3 and variance 0. However, in the discrete limit,\n # the kurtosis blows up as variance --> 0, hence return nan when variance is smaller than a resolution of 0.5:\n if variance < 0.5:\n return np.nan\n else:\n return (\n get_moment(y, 4) - 4 * get_centroid(y) * get_moment(y, 3)\n + 6 * get_moment(y, 2) * get_centroid(y)**2 - 3 * get_centroid(y)\n ) / get_variance(y)**2\n\n calculation = dict(\n centroid=get_centroid,\n variance=get_variance,\n skew=get_skew,\n kurtosis=get_kurtosis\n )\n\n fft_abs = np.abs(np.fft.rfft(x))\n\n res = [calculation[config[\"aggtype\"]](fft_abs) for config in param]\n index = ['aggtype_\"{}\"'.format(config[\"aggtype\"]) for config in param]\n return zip(index, res)\n\n\n@set_property(\"fctype\", \"simple\")\ndef number_peaks(x, n):\n \"\"\"\n Calculates the number of peaks of at least support n in the time series x. A peak of support n is defined as a\n subsequence of x where a value occurs, which is bigger than its n neighbours to the left and to the right.\n\n Hence in the sequence\n\n >>> x = [3, 0, 0, 4, 0, 0, 13]\n\n 4 is a peak of support 1 and 2 because in the subsequences\n\n >>> [0, 4, 0]\n >>> [0, 0, 4, 0, 0]\n\n 4 is still the highest value. Here, 4 is not a peak of support 3 because 13 is the 3th neighbour to the right of 4\n and its bigger than 4.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param n: the support of the peak\n :type n: int\n :return: the value of this feature\n :return type: float\n \"\"\"\n x_reduced = x[n:-n]\n\n res = None\n for i in range(1, n + 1):\n result_first = (x_reduced > _roll(x, i)[n:-n])\n\n if res is None:\n res = result_first\n else:\n res &= result_first\n\n res &= (x_reduced > _roll(x, -i)[n:-n])\n return np.sum(res)\n\n\n@set_property(\"fctype\", \"combiner\")\ndef index_mass_quantile(x, param):\n \"\"\"\n Those apply features calculate the relative index i where q% of the mass of the time series x lie left of i.\n For example for q = 50% this feature calculator will return the mass center of the time series\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"q\": x} with x float\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n\n x = np.asarray(x)\n abs_x = np.abs(x)\n s = np.sum(abs_x)\n\n if s == 0:\n # all values in x are zero or it has length 0\n return [(\"q_{}\".format(config[\"q\"]), np.NaN) for config in param]\n else:\n # at least one value is not zero\n mass_centralized = np.cumsum(abs_x) / s\n return [(\"q_{}\".format(config[\"q\"]),\n (np.argmax(mass_centralized >= config[\"q\"]) + 1) / len(x)) for config in param]\n\n\n@set_property(\"fctype\", \"simple\")\ndef number_cwt_peaks(x, n):\n \"\"\"\n Number of different peaks in x.\n\n To estimamte the numbers of peaks, x is smoothed by a ricker wavelet for widths ranging from 1 to n. This feature\n calculator returns the number of peaks that occur at enough width scales and with sufficiently high\n Signal-to-Noise-Ratio (SNR)\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param n: maximum width to consider\n :type n: int\n :return: the value of this feature\n :return type: int\n \"\"\"\n return len(find_peaks_cwt(vector=x, widths=np.array(list(range(1, n + 1))), wavelet=ricker))\n\n\n@set_property(\"fctype\", \"combiner\")\ndef linear_trend(x, param):\n \"\"\"\n Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to\n length of the time series minus one.\n This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model.\n The parameters control which of the characteristics are returned.\n\n Possible extracted attributes are \"pvalue\", \"rvalue\", \"intercept\", \"slope\", \"stderr\", see the documentation of\n linregress for more information.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"attr\": x} with x an string, the attribute name of the regression model\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n # todo: we could use the index of the DataFrame here\n linReg = linregress(range(len(x)), x)\n\n return [(\"attr_\\\"{}\\\"\".format(config[\"attr\"]), getattr(linReg, config[\"attr\"]))\n for config in param]\n\n\n@set_property(\"fctype\", \"combiner\")\ndef cwt_coefficients(x, param):\n \"\"\"\n Calculates a Continuous wavelet transform for the Ricker wavelet, also known as the \"Mexican hat wavelet\" which is\n defined by\n\n .. math::\n \\\\frac{2}{\\\\sqrt{3a} \\\\pi^{\\\\frac{1}{4}}} (1 - \\\\frac{x^2}{a^2}) exp(-\\\\frac{x^2}{2a^2})\n\n where :math:`a` is the width parameter of the wavelet function.\n\n This feature calculator takes three different parameter: widths, coeff and w. The feature calculator takes all the\n different widths arrays and then calculates the cwt one time for each different width array. Then the values for the\n different coefficient for coeff and width w are returned. (For each dic in param one feature is returned)\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"widths\":x, \"coeff\": y, \"w\": z} with x array of int and y,z int\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n\n calculated_cwt = {}\n res = []\n indices = []\n\n for parameter_combination in param:\n widths = tuple(parameter_combination[\"widths\"])\n w = parameter_combination[\"w\"]\n coeff = parameter_combination[\"coeff\"]\n\n if widths not in calculated_cwt:\n calculated_cwt[widths] = cwt(x, ricker, widths)\n\n calculated_cwt_for_widths = calculated_cwt[widths]\n\n indices += [\"coeff_{}__w_{}__widths_{}\".format(coeff, w, widths)]\n\n i = widths.index(w)\n if calculated_cwt_for_widths.shape[1] <= coeff:\n res += [np.NaN]\n else:\n res += [calculated_cwt_for_widths[i, coeff]]\n\n return zip(indices, res)\n\n\n@set_property(\"fctype\", \"combiner\")\ndef spkt_welch_density(x, param):\n \"\"\"\n This feature calculator estimates the cross power spectral density of the time series x at different frequencies.\n To do so, the time series is first shifted from the time domain to the frequency domain.\n\n The feature calculators returns the power spectrum of the different frequencies.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"coeff\": x} with x int\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n\n freq, pxx = welch(x, nperseg=min(len(x), 256))\n coeff = [config[\"coeff\"] for config in param]\n indices = [\"coeff_{}\".format(i) for i in coeff]\n\n if len(pxx) <= np.max(coeff): # There are fewer data points in the time series than requested coefficients\n\n # filter coefficients that are not contained in pxx\n reduced_coeff = [coefficient for coefficient in coeff if len(pxx) > coefficient]\n not_calculated_coefficients = [coefficient for coefficient in coeff\n if coefficient not in reduced_coeff]\n\n # Fill up the rest of the requested coefficients with np.NaNs\n return zip(indices, list(pxx[reduced_coeff]) + [np.NaN] * len(not_calculated_coefficients))\n else:\n return zip(indices, pxx[coeff])\n\n\n@set_property(\"fctype\", \"combiner\")\ndef ar_coefficient(x, param):\n \"\"\"\n This feature calculator fits the unconditional maximum likelihood\n of an autoregressive AR(k) process.\n The k parameter is the maximum lag of the process\n\n .. math::\n\n X_{t}=\\\\varphi_0 +\\\\sum _{{i=1}}^{k}\\\\varphi_{i}X_{{t-i}}+\\\\varepsilon_{t}\n\n For the configurations from param which should contain the maxlag \"k\" and such an AR process is calculated. Then\n the coefficients :math:`\\\\varphi_{i}` whose index :math:`i` contained from \"coeff\" are returned.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"coeff\": x, \"k\": y} with x,y int\n :type param: list\n :return x: the different feature values\n :return type: pandas.Series\n \"\"\"\n calculated_ar_params = {}\n\n x_as_list = list(x)\n\n res = {}\n\n for parameter_combination in param:\n k = parameter_combination[\"k\"]\n p = parameter_combination[\"coeff\"]\n\n column_name = \"coeff_{}__k_{}\".format(p, k)\n\n if k not in calculated_ar_params:\n try:\n calculated_AR = AR(x_as_list)\n calculated_ar_params[k] = calculated_AR.fit(maxlag=k, solver=\"mle\").params\n except (LinAlgError, ValueError):\n calculated_ar_params[k] = [np.NaN] * k\n\n mod = calculated_ar_params[k]\n\n if p <= k:\n try:\n res[column_name] = mod[p]\n except IndexError:\n res[column_name] = 0\n else:\n res[column_name] = np.NaN\n\n return [(key, value) for key, value in res.items()]\n\n\n@set_property(\"fctype\", \"simple\")\ndef change_quantiles(x, ql, qh, isabs, f_agg):\n \"\"\"\n First fixes a corridor given by the quantiles ql and qh of the distribution of x.\n Then calculates the average, absolute value of consecutive changes of the series x inside this corridor.\n\n Think about selecting a corridor on the\n y-Axis and only calculating the mean of the absolute change of the time series inside this corridor.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param ql: the lower quantile of the corridor\n :type ql: float\n :param qh: the higher quantile of the corridor\n :type qh: float\n :param isabs: should the absolute differences be taken?\n :type isabs: bool\n :param f_agg: the aggregator function that is applied to the differences in the bin\n :type f_agg: str, name of a numpy function (e.g. mean, var, std, median)\n\n :return: the value of this feature\n :return type: float\n \"\"\"\n if ql >= qh:\n return 0\n\n div = np.diff(x)\n if isabs:\n div = np.abs(div)\n # All values that originate from the corridor between the quantiles ql and qh will have the category 0,\n # other will be np.NaN\n try:\n bin_cat = pd.qcut(x, [ql, qh], labels=False)\n bin_cat_0 = bin_cat == 0\n except ValueError: # Occurs when ql are qh effectively equal, e.g. x is not long enough or is too categorical\n return 0\n # We only count changes that start and end inside the corridor\n ind = (bin_cat_0 & _roll(bin_cat_0, 1))[1:]\n if np.sum(ind) == 0:\n return 0\n else:\n ind_inside_corridor = np.where(ind == 1)\n aggregator = getattr(np, f_agg)\n return aggregator(div[ind_inside_corridor])\n\n\n@set_property(\"fctype\", \"simple\")\ndef time_reversal_asymmetry_statistic(x, lag):\n \"\"\"\n Returns the time reversal asymmetry statistic.\n\n This function calculates the value of\n\n .. math::\n\n \\\\frac{1}{n-2lag} \\\\sum_{i=1}^{n-2lag} x_{i + 2 \\\\cdot lag}^2 \\\\cdot x_{i + lag} - x_{i + lag} \\\\cdot x_{i}^2\n\n which is\n\n .. math::\n\n \\\\mathbb{E}[L^2(X)^2 \\\\cdot L(X) - L(X) \\\\cdot X^2]\n\n where :math:`\\\\mathbb{E}` is the mean and :math:`L` is the lag operator. It was proposed in [1] as a\n promising feature to extract from time series.\n\n .. rubric:: References\n\n | [1] Fulcher, B.D., Jones, N.S. (2014).\n | Highly comparative feature-based time-series classification.\n | Knowledge and Data Engineering, IEEE Transactions on 26, 3026–3037.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param lag: the lag that should be used in the calculation of the feature\n :type lag: int\n :return: the value of this feature\n :return type: float\n \"\"\"\n n = len(x)\n x = np.asarray(x)\n if 2 * lag >= n:\n return 0\n else:\n one_lag = _roll(x, -lag)\n two_lag = _roll(x, 2 * -lag)\n return np.mean((two_lag * two_lag * one_lag - one_lag * x * x)[0:(n - 2 * lag)])\n\n\n@set_property(\"fctype\", \"simple\")\ndef c3(x, lag):\n \"\"\"\n Uses c3 statistics to measure non linearity in the time series\n\n This function calculates the value of\n\n .. math::\n\n \\\\frac{1}{n-2lag} \\\\sum_{i=1}^{n-2lag} x_{i + 2 \\\\cdot lag} \\\\cdot x_{i + lag} \\\\cdot x_{i}\n\n which is\n\n .. math::\n\n \\\\mathbb{E}[L^2(X) \\\\cdot L(X) \\\\cdot X]\n\n where :math:`\\\\mathbb{E}` is the mean and :math:`L` is the lag operator. It was proposed in [1] as a measure of\n non linearity in the time series.\n\n .. rubric:: References\n\n | [1] Schreiber, T. and Schmitz, A. (1997).\n | Discrimination power of measures for nonlinearity in a time series\n | PHYSICAL REVIEW E, VOLUME 55, NUMBER 5\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param lag: the lag that should be used in the calculation of the feature\n :type lag: int\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n n = x.size\n if 2 * lag >= n:\n return 0\n else:\n return np.mean((_roll(x, 2 * -lag) * _roll(x, -lag) * x)[0:(n - 2 * lag)])\n\n\n@set_property(\"fctype\", \"simple\")\ndef binned_entropy(x, max_bins):\n \"\"\"\n First bins the values of x into max_bins equidistant bins.\n Then calculates the value of\n\n .. math::\n\n - \\\\sum_{k=0}^{min(max\\\\_bins, len(x))} p_k log(p_k) \\\\cdot \\\\mathbf{1}_{(p_k > 0)}\n\n where :math:`p_k` is the percentage of samples in bin :math:`k`.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param max_bins: the maximal number of bins\n :type max_bins: int\n :return: the value of this feature\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n\n # nan makes no sense here\n if np.isnan(x).any():\n return np.nan\n\n hist, bin_edges = np.histogram(x, bins=max_bins)\n probs = hist / x.size\n probs[probs == 0] = 1.0\n return - np.sum(probs * np.log(probs))\n\n\n# todo - include latex formula\n# todo - check if vectorizable\n@set_property(\"high_comp_cost\", True)\n@set_property(\"fctype\", \"simple\")\ndef sample_entropy(x):\n \"\"\"\n Calculate and return sample entropy of x.\n\n .. rubric:: References\n\n | [1] http://en.wikipedia.org/wiki/Sample_Entropy\n | [2] https://www.ncbi.nlm.nih.gov/pubmed/10843903?dopt=Abstract\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n\n :return: the value of this feature\n :return type: float\n \"\"\"\n x = np.array(x)\n\n # if one of the values is NaN, we can not compute anything meaningful\n if np.isnan(x).any():\n return np.nan\n\n m = 2 # common value for m, according to wikipedia...\n tolerance = 0.2 * np.std(x) # 0.2 is a common value for r, according to wikipedia...\n\n # Split time series and save all templates of length m\n # Basically we turn [1, 2, 3, 4] into [1, 2], [2, 3], [3, 4]\n xm = _into_subchunks(x, m)\n\n # Now calculate the maximum distance between each of those pairs\n # np.abs(xmi - xm).max(axis=1)\n # and check how many are below the tolerance.\n # For speed reasons, we are not doing this in a nested for loop,\n # but with numpy magic.\n # Example:\n # if x = [1, 2, 3]\n # then xm = [[1, 2], [2, 3]]\n # so we will substract xm from [1, 2] => [[0, 0], [-1, -1]]\n # and from [2, 3] => [[1, 1], [0, 0]]\n # taking the abs and max gives us:\n # [0, 1] and [1, 0]\n # as the diagonal elements are always 0, we substract 1.\n B = np.sum([np.sum(np.abs(xmi - xm).max(axis=1) <= tolerance) - 1 for xmi in xm])\n\n # Similar for computing A\n xmp1 = _into_subchunks(x, m + 1)\n\n A = np.sum([np.sum(np.abs(xmi - xmp1).max(axis=1) <= tolerance) - 1 for xmi in xmp1])\n\n # Return SampEn\n return -np.log(A / B)\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"high_comp_cost\", True)\ndef approximate_entropy(x, m, r):\n \"\"\"\n Implements a vectorized Approximate entropy algorithm.\n\n https://en.wikipedia.org/wiki/Approximate_entropy\n\n For short time-series this method is highly dependent on the parameters,\n but should be stable for N > 2000, see:\n\n Yentes et al. (2012) -\n *The Appropriate Use of Approximate Entropy and Sample Entropy with Short Data Sets*\n\n\n Other shortcomings and alternatives discussed in:\n\n Richman & Moorman (2000) -\n *Physiological time-series analysis using approximate entropy and sample entropy*\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param m: Length of compared run of data\n :type m: int\n :param r: Filtering level, must be positive\n :type r: float\n\n :return: Approximate entropy\n :return type: float\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n\n N = x.size\n r *= np.std(x)\n if r < 0:\n raise ValueError(\"Parameter r must be positive.\")\n if N <= m + 1:\n return 0\n\n def _phi(m):\n x_re = np.array([x[i:i + m] for i in range(N - m + 1)])\n C = np.sum(np.max(np.abs(x_re[:, np.newaxis] - x_re[np.newaxis, :]),\n axis=2) <= r, axis=0) / (N - m + 1)\n return np.sum(np.log(C)) / (N - m + 1.0)\n\n return np.abs(_phi(m) - _phi(m + 1))\n\n\n@set_property(\"fctype\", \"simple\")\ndef fourier_entropy(x, bins):\n \"\"\"\n Calculate the binned entropy of the power spectral density of the time series\n (using the welch method).\n\n Ref: https://hackaday.io/project/707-complexity-of-a-time-series/details\n Ref: https://docs.scipy.org/doc/scipy-0.14.0/reference/generated/scipy.signal.welch.html\n\n \"\"\"\n _, pxx = welch(x, nperseg=min(len(x), 256))\n return binned_entropy(pxx / np.max(pxx), bins)\n\n\n@set_property(\"fctype\", \"simple\")\ndef lempel_ziv_complexity(x, bins):\n \"\"\"\n Calculate a complexity estimate based on the Lempel-Ziv compression\n algorithm.\n\n The complexity is defined as the number of dictionary entries (or sub-words) needed\n to encode the time series when viewed from left to right.\n For this, the time series is first binned into the given number of bins.\n Then it is converted into sub-words with different prefixes.\n The number of sub-words needed for this divided by the length of the time\n series is the complexity estimate.\n\n For example, if the time series (after binning in only 2 bins) would look like \"100111\",\n the different sub-words would be 1, 0, 01 and 11 and therefore the result is 4/6 = 0.66.\n\n Ref: https://github.com/Naereen/Lempel-Ziv_Complexity/blob/master/src/lempel_ziv_complexity.py\n\n \"\"\"\n x = np.asarray(x)\n\n bins = np.linspace(np.min(x), np.max(x), bins + 1)[1:]\n sequence = np.searchsorted(bins, x, side='left')\n\n sub_strings = set()\n n = len(sequence)\n\n ind = 0\n inc = 1\n while ind + inc <= n:\n # convert to tuple in order to make it hashable\n sub_str = tuple(sequence[ind:ind + inc])\n if sub_str in sub_strings:\n inc += 1\n else:\n sub_strings.add(sub_str)\n ind += inc\n inc = 1\n return len(sub_strings) / n\n\n\n@set_property(\"fctype\", \"simple\")\ndef permutation_entropy(x, tau, dimension):\n \"\"\"\n Calculate the permutation entropy.\n\n Three steps are needed for this:\n\n 1. chunk the data into sub-windows of length D starting every tau.\n Following the example from the reference, a vector\n\n x = [4, 7, 9, 10, 6, 11, 3\n\n with D = 3 and tau = 1 is turned into\n\n [[ 4, 7, 9],\n [ 7, 9, 10],\n [ 9, 10, 6],\n [10, 6, 11],\n [ 6, 11, 3]]\n\n 2. replace each D-window by the permutation, that\n captures the ordinal ranking of the data.\n That gives\n\n [[0, 1, 2],\n [0, 1, 2],\n [1, 2, 0],\n [1, 0, 2],\n [1, 2, 0]]\n\n 3. Now we just need to count the frequencies of every permutation\n and return their entropy (we use log_e and not log_2).\n\n Ref: https://www.aptech.com/blog/permutation-entropy/\n Bandt, Christoph and Bernd Pompe.\n “Permutation entropy: a natural complexity measure for time series.”\n Physical review letters 88 17 (2002): 174102 .\n \"\"\"\n\n X = _into_subchunks(x, dimension, tau)\n if len(X) == 0:\n return np.nan\n # Now that is clearly black, magic, but see here:\n # https://stackoverflow.com/questions/54459554/numpy-find-index-in-sorted-array-in-an-efficient-way\n permutations = np.argsort(np.argsort(X))\n # Count the number of occurences\n _, counts = np.unique(permutations, axis=0, return_counts=True)\n # turn them into frequencies\n probs = counts / len(permutations)\n # and return their entropy\n return -np.sum(probs * np.log(probs))\n\n\n@set_property(\"fctype\", \"simple\")\ndef autocorrelation(x, lag):\n \"\"\"\n Calculates the autocorrelation of the specified lag, according to the formula [1]\n\n .. math::\n\n \\\\frac{1}{(n-l)\\\\sigma^{2}} \\\\sum_{t=1}^{n-l}(X_{t}-\\\\mu )(X_{t+l}-\\\\mu)\n\n where :math:`n` is the length of the time series :math:`X_i`, :math:`\\\\sigma^2` its variance and :math:`\\\\mu` its\n mean. `l` denotes the lag.\n\n .. rubric:: References\n\n [1] https://en.wikipedia.org/wiki/Autocorrelation#Estimation\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param lag: the lag\n :type lag: int\n :return: the value of this feature\n :return type: float\n \"\"\"\n # This is important: If a series is passed, the product below is calculated\n # based on the index, which corresponds to squaring the series.\n if isinstance(x, pd.Series):\n x = x.values\n if len(x) < lag:\n return np.nan\n # Slice the relevant subseries based on the lag\n y1 = x[:(len(x) - lag)]\n y2 = x[lag:]\n # Subtract the mean of the whole series x\n x_mean = np.mean(x)\n # The result is sometimes referred to as \"covariation\"\n sum_product = np.sum((y1 - x_mean) * (y2 - x_mean))\n # Return the normalized unbiased covariance\n v = np.var(x)\n if np.isclose(v, 0):\n return np.NaN\n else:\n return sum_product / ((len(x) - lag) * v)\n\n\n@set_property(\"fctype\", \"simple\")\ndef quantile(x, q):\n \"\"\"\n Calculates the q quantile of x. This is the value of x greater than q% of the ordered values from x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param q: the quantile to calculate\n :type q: float\n :return: the value of this feature\n :return type: float\n \"\"\"\n if len(x) == 0:\n return np.NaN\n return np.quantile(x, q)\n\n\n@set_property(\"fctype\", \"simple\")\ndef number_crossing_m(x, m):\n \"\"\"\n Calculates the number of crossings of x on m. A crossing is defined as two sequential values where the first value\n is lower than m and the next is greater, or vice-versa. If you set m to zero, you will get the number of zero\n crossings.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param m: the threshold for the crossing\n :type m: float\n :return: the value of this feature\n :return type: int\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n # From https://stackoverflow.com/questions/3843017/efficiently-detect-sign-changes-in-python\n # However, we are not going with the fastest version as it breaks with pandas\n positive = x > m\n return np.where(np.diff(positive))[0].size\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef maximum(x):\n \"\"\"\n Calculates the highest value of the time series x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.max(x)\n\n\n@set_property(\"fctype\", \"simple\")\n@set_property(\"minimal\", True)\ndef minimum(x):\n \"\"\"\n Calculates the lowest value of the time series x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.min(x)\n\n\n@set_property(\"fctype\", \"simple\")\ndef value_count(x, value):\n \"\"\"\n Count occurrences of `value` in time series x.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param value: the value to be counted\n :type value: int or float\n :return: the count\n :rtype: int\n \"\"\"\n if not isinstance(x, (np.ndarray, pd.Series)):\n x = np.asarray(x)\n\n if np.isnan(value):\n return np.isnan(x).sum()\n else:\n return x[x == value].size\n\n\n@set_property(\"fctype\", \"simple\")\ndef range_count(x, min, max):\n \"\"\"\n Count observed values within the interval [min, max).\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param min: the inclusive lower bound of the range\n :type min: int or float\n :param max: the exclusive upper bound of the range\n :type max: int or float\n :return: the count of values within the range\n :rtype: int\n \"\"\"\n return np.sum((x >= min) & (x < max))\n\n\n@set_property(\"fctype\", \"combiner\")\ndef friedrich_coefficients(x, param):\n \"\"\"\n Coefficients of polynomial :math:`h(x)`, which has been fitted to\n the deterministic dynamics of Langevin model\n\n .. math::\n \\\\dot{x}(t) = h(x(t)) + \\\\mathcal{N}(0,R)\n\n as described by [1].\n\n For short time-series this method is highly dependent on the parameters.\n\n .. rubric:: References\n\n | [1] Friedrich et al. (2000): Physics Letters A 271, p. 217-222\n | *Extracting model equations from experimental data*\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"m\": x, \"r\": y, \"coeff\": z} with x being positive integer,\n the order of polynomial to fit for estimating fixed points of\n dynamics, y positive float, the number of quantiles to use for averaging and finally z,\n a positive integer corresponding to the returned coefficient\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n # calculated is dictionary storing the calculated coefficients {m: {r: friedrich_coefficients}}\n calculated = defaultdict(dict)\n # res is a dictionary containing the results {\"m_10__r_2__coeff_3\": 15.43}\n res = {}\n\n for parameter_combination in param:\n m = parameter_combination['m']\n r = parameter_combination['r']\n coeff = parameter_combination[\"coeff\"]\n\n assert coeff >= 0, \"Coefficients must be positive or zero. Found {}\".format(coeff)\n\n # calculate the current friedrich coefficients if they do not exist yet\n if m not in calculated or r not in calculated[m]:\n calculated[m][r] = _estimate_friedrich_coefficients(x, m, r)\n\n try:\n res[\"coeff_{}__m_{}__r_{}\".format(coeff, m, r)] = calculated[m][r][coeff]\n except IndexError:\n res[\"coeff_{}__m_{}__r_{}\".format(coeff, m, r)] = np.NaN\n return [(key, value) for key, value in res.items()]\n\n\n@set_property(\"fctype\", \"simple\")\ndef max_langevin_fixed_point(x, r, m):\n \"\"\"\n Largest fixed point of dynamics :math:argmax_x {h(x)=0}` estimated from polynomial :math:`h(x)`,\n which has been fitted to the deterministic dynamics of Langevin model\n\n .. math::\n \\\\dot(x)(t) = h(x(t)) + R \\\\mathcal(N)(0,1)\n\n as described by\n\n Friedrich et al. (2000): Physics Letters A 271, p. 217-222\n *Extracting model equations from experimental data*\n\n For short time-series this method is highly dependent on the parameters.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param m: order of polynomial to fit for estimating fixed points of dynamics\n :type m: int\n :param r: number of quantiles to use for averaging\n :type r: float\n\n :return: Largest fixed point of deterministic dynamics\n :return type: float\n \"\"\"\n\n coeff = _estimate_friedrich_coefficients(x, m, r)\n\n try:\n max_fixed_point = np.max(np.real(np.roots(coeff)))\n except (np.linalg.LinAlgError, ValueError):\n return np.nan\n\n return max_fixed_point\n\n\n@set_property(\"fctype\", \"combiner\")\ndef agg_linear_trend(x, param):\n \"\"\"\n Calculates a linear least-squares regression for values of the time series that were aggregated over chunks versus\n the sequence from 0 up to the number of chunks minus one.\n\n This feature assumes the signal to be uniformly sampled. It will not use the time stamps to fit the model.\n\n The parameters attr controls which of the characteristics are returned. Possible extracted attributes are \"pvalue\",\n \"rvalue\", \"intercept\", \"slope\", \"stderr\", see the documentation of linregress for more information.\n\n The chunksize is regulated by \"chunk_len\". It specifies how many time series values are in each chunk.\n\n Further, the aggregation function is controlled by \"f_agg\", which can use \"max\", \"min\" or , \"mean\", \"median\"\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"attr\": x, \"chunk_len\": l, \"f_agg\": f} with x, f an string and l an int\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n # todo: we could use the index of the DataFrame here\n\n calculated_agg = defaultdict(dict)\n res_data = []\n res_index = []\n\n for parameter_combination in param:\n\n chunk_len = parameter_combination[\"chunk_len\"]\n f_agg = parameter_combination[\"f_agg\"]\n\n if f_agg not in calculated_agg or chunk_len not in calculated_agg[f_agg]:\n if chunk_len >= len(x):\n calculated_agg[f_agg][chunk_len] = np.NaN\n else:\n aggregate_result = _aggregate_on_chunks(x, f_agg, chunk_len)\n lin_reg_result = linregress(range(len(aggregate_result)), aggregate_result)\n calculated_agg[f_agg][chunk_len] = lin_reg_result\n\n attr = parameter_combination[\"attr\"]\n\n if chunk_len >= len(x):\n res_data.append(np.NaN)\n else:\n res_data.append(getattr(calculated_agg[f_agg][chunk_len], attr))\n\n res_index.append(\"attr_\\\"{}\\\"__chunk_len_{}__f_agg_\\\"{}\\\"\".format(attr, chunk_len, f_agg))\n\n return zip(res_index, res_data)\n\n\n@set_property(\"fctype\", \"combiner\")\ndef energy_ratio_by_chunks(x, param):\n \"\"\"\n Calculates the sum of squares of chunk i out of N chunks expressed as a ratio with the sum of squares over the whole\n series.\n\n Takes as input parameters the number num_segments of segments to divide the series into and segment_focus\n which is the segment number (starting at zero) to return a feature on.\n\n If the length of the time series is not a multiple of the number of segments, the remaining data points are\n distributed on the bins starting from the first. For example, if your time series consists of 8 entries, the\n first two bins will contain 3 and the last two values, e.g. `[ 0., 1., 2.], [ 3., 4., 5.]` and `[ 6., 7.]`.\n\n Note that the answer for `num_segments = 1` is a trivial \"1\" but we handle this scenario\n in case somebody calls it. Sum of the ratios should be 1.0.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"num_segments\": N, \"segment_focus\": i} with N, i both ints\n :return: the feature values\n :return type: list of tuples (index, data)\n \"\"\"\n res_data = []\n res_index = []\n full_series_energy = np.sum(x ** 2)\n\n for parameter_combination in param:\n num_segments = parameter_combination[\"num_segments\"]\n segment_focus = parameter_combination[\"segment_focus\"]\n assert segment_focus < num_segments\n assert num_segments > 0\n\n if full_series_energy == 0:\n res_data.append(np.NaN)\n else:\n res_data.append(np.sum(np.array_split(x, num_segments)[segment_focus] ** 2.0) / full_series_energy)\n\n res_index.append(\"num_segments_{}__segment_focus_{}\".format(num_segments, segment_focus))\n\n # Materialize as list for Python 3 compatibility with name handling\n return list(zip(res_index, res_data))\n\n\n@set_property(\"fctype\", \"combiner\")\n@set_property(\"input\", \"pd.Series\")\n@set_property(\"index_type\", pd.DatetimeIndex)\ndef linear_trend_timewise(x, param):\n \"\"\"\n Calculate a linear least-squares regression for the values of the time series versus the sequence from 0 to\n length of the time series minus one.\n This feature uses the index of the time series to fit the model, which must be of a datetime\n dtype.\n The parameters control which of the characteristics are returned.\n\n Possible extracted attributes are \"pvalue\", \"rvalue\", \"intercept\", \"slope\", \"stderr\", see the documentation of\n linregress for more information.\n\n :param x: the time series to calculate the feature of. The index must be datetime.\n :type x: pandas.Series\n :param param: contains dictionaries {\"attr\": x} with x an string, the attribute name of the regression model\n :type param: list\n :return: the different feature values\n :return type: list\n \"\"\"\n ix = x.index\n\n # Get differences between each timestamp and the first timestamp in seconds.\n # Then convert to hours and reshape for linear regression\n times_seconds = (ix - ix[0]).total_seconds()\n times_hours = np.asarray(times_seconds / float(3600))\n\n linReg = linregress(times_hours, x.values)\n\n return [(\"attr_\\\"{}\\\"\".format(config[\"attr\"]), getattr(linReg, config[\"attr\"]))\n for config in param]\n\n\n@set_property(\"fctype\", \"simple\")\ndef count_above(x, t):\n \"\"\"\n Returns the percentage of values in x that are higher than t\n\n :param x: the time series to calculate the feature of\n :type x: pandas.Series\n :param t: value used as threshold\n :type t: float\n\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.sum(x >= t)/len(x)\n\n\n@set_property(\"fctype\", \"simple\")\ndef count_below(x, t):\n \"\"\"\n Returns the percentage of values in x that are lower than t\n\n :param x: the time series to calculate the feature of\n :type x: pandas.Series\n :param t: value used as threshold\n :type t: float\n\n :return: the value of this feature\n :return type: float\n \"\"\"\n return np.sum(x <= t)/len(x)\n\n\n@set_property(\"fctype\", \"simple\")\ndef benford_correlation(x):\n \"\"\"\n Useful for anomaly detection applications [1][2]. Returns the correlation from first digit distribution when\n compared to the Newcomb-Benford's Law distribution [3][4].\n\n .. math::\n\n P(d)=\\\\log_{10}\\\\left(1+\\\\frac{1}{d}\\\\right)\n\n where :math:`P(d)` is the Newcomb-Benford distribution for :math:`d` that is the leading digit of the number\n {1, 2, 3, 4, 5, 6, 7, 8, 9}.\n\n .. rubric:: References\n\n | [1] A Statistical Derivation of the Significant-Digit Law, Theodore P. Hill, Statistical Science, 1995\n | [2] The significant-digit phenomenon, Theodore P. Hill, The American Mathematical Monthly, 1995\n | [3] The law of anomalous numbers, Frank Benford, Proceedings of the American philosophical society, 1938\n | [4] Note on the frequency of use of the different digits in natural numbers, Simon Newcomb, American Journal of\n | mathematics, 1881\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :return: the value of this feature\n :return type: float\n \"\"\"\n x = np.asarray(x)\n\n # retrieve first digit from data\n x = np.array([int(str(np.format_float_scientific(i))[:1]) for i in np.abs(np.nan_to_num(x))])\n\n # benford distribution\n benford_distribution = np.array([np.log10(1 + 1/n) for n in range(1, 10)])\n\n data_distribution = np.array([(x == n).mean() for n in range(1, 10)])\n\n # np.corrcoef outputs the normalized covariance (correlation) between benford_distribution and data_distribution.\n # In this case returns a 2x2 matrix, the [0, 1] and [1, 1] are the values between the two arrays\n return np.corrcoef(benford_distribution, data_distribution)[0, 1]\n\n\n@set_property(\"fctype\", \"combiner\")\ndef matrix_profile(x, param):\n \"\"\"\n Calculates the 1-D Matrix Profile[1] and returns Tukey's Five Number Set plus the mean of that Matrix Profile.\n\n .. rubric:: References\n\n | [1] Yeh et.al (2016), IEEE ICDM\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries {\"sample_pct\": x, \"threshold\": y, \"feature\": z}\n with sample_pct and threshold being parameters of the matrixprofile\n package https://matrixprofile.docs.matrixprofile.org/api.html#matrixprofile-compute\n and feature being one of \"min\", \"max\", \"mean\", \"median\", \"25\", \"75\"\n and decides which feature of the matrix profile to extract\n :type param: list\n :return: the different feature values\n :return type: pandas.Series\n \"\"\"\n\n x = np.asarray(x)\n\n def _calculate_mp(**kwargs):\n \"\"\"Calculate the matrix profile using the specified window, or the max subsequence if no window is specified\"\"\"\n try:\n if \"windows\" in kwargs:\n m_p = mp.compute(x, **kwargs)['mp']\n\n else:\n m_p = mp.algorithms.maximum_subsequence(x, include_pmp=True, **kwargs)['pmp'][-1]\n\n return m_p\n\n except NoSolutionPossible:\n return [np.nan]\n\n # The already calculated matrix profiles\n matrix_profiles = {}\n\n # The results\n res = {}\n\n for kwargs in param:\n kwargs = kwargs.copy()\n key = convert_to_output_format(kwargs)\n feature = kwargs.pop('feature')\n\n featureless_key = convert_to_output_format(kwargs)\n if featureless_key not in matrix_profiles:\n matrix_profiles[featureless_key] = _calculate_mp(**kwargs)\n\n m_p = matrix_profiles[featureless_key]\n\n # Set all features to nan if Matrix Profile is nan (cannot be computed)\n if len(m_p) == 1:\n res[key] = np.nan\n\n # Handle all other Matrix Profile instances\n else:\n\n finite_indices = np.isfinite(m_p)\n\n if feature == \"min\":\n res[key] = np.min(m_p[finite_indices])\n elif feature == \"max\":\n res[key] = np.max(m_p[finite_indices])\n elif feature == \"mean\":\n res[key] = np.mean(m_p[finite_indices])\n elif feature == \"median\":\n res[key] = np.median(m_p[finite_indices])\n elif feature == \"25\":\n res[key] = np.percentile(m_p[finite_indices], 25)\n elif feature == \"75\":\n res[key] = np.percentile(m_p[finite_indices], 75)\n else:\n raise ValueError(f\"Unknown feature {feature} for the matrix profile\")\n\n return [(key, value) for key, value in res.items()]\n\n\n@set_property(\"fctype\", \"combiner\")\ndef query_similarity_count(x, param):\n \"\"\"\n This feature calculator accepts an input query subsequence parameter,\n compares the query (under z-normalized Euclidean distance) to all\n subsequences within the time series, and returns a count of the number\n of times the query was found in the time series (within some predefined\n maximum distance threshold). Note that this feature will always return\n `np.nan` when no query subsequence is provided and so users will need\n to enable this feature themselves.\n\n :param x: the time series to calculate the feature of\n :type x: numpy.ndarray\n :param param: contains dictionaries\n {\"query\": Q, \"threshold\": thr, \"normalize\": norm}\n with `Q` (numpy.ndarray), the query subsequence to compare the\n time series against. If `Q` is omitted then a value of zero\n is returned. Additionally, `thr` (float), the maximum\n z-normalized Euclidean distance threshold for which to\n increment the query similarity count. If `thr` is omitted\n then a default threshold of `thr=0.0` is used, which\n corresponds to finding exact matches to `Q`. Finally, for\n non-normalized (i.e., without z-normalization) Euclidean set\n `norm` (bool) to `False.\n :type param: list\n :return x: the different feature values\n :return type: int\n \"\"\"\n res = {}\n T = np.asarray(x).astype(float)\n\n for i, kwargs in enumerate(param):\n key = convert_to_output_format(kwargs)\n normalize = kwargs.get(\"normalize\", True)\n threshold = kwargs.get('threshold', 0.0)\n Q = kwargs.get('query', None)\n Q = np.asarray(Q).astype(float)\n count = np.nan\n if Q is not None and Q.size >= 3:\n if normalize:\n distance_profile = stumpy.core.mass(Q, T)\n else:\n distance_profile = stumpy.core.mass_absolute(Q, T)\n count = np.sum(distance_profile <= threshold)\n\n res[key] = count\n\n return [(key, value) for key, value in res.items()]\n"
] |
[
[
"numpy.dot",
"numpy.polyfit",
"numpy.expand_dims",
"numpy.sqrt",
"pandas.Series",
"numpy.asarray",
"numpy.cumsum",
"numpy.nan_to_num",
"numpy.concatenate",
"numpy.max",
"numpy.mean",
"numpy.argmin",
"numpy.searchsorted",
"numpy.var",
"numpy.histogram",
"numpy.where",
"numpy.square",
"numpy.unique",
"numpy.arange",
"scipy.signal.cwt",
"numpy.roots",
"numpy.std",
"numpy.argmax",
"numpy.diff",
"numpy.format_float_scientific",
"numpy.isclose",
"numpy.log",
"pandas.Series.skew",
"numpy.min",
"numpy.isnan",
"numpy.median",
"numpy.quantile",
"scipy.stats.linregress",
"numpy.log10",
"pandas.Series.kurtosis",
"numpy.corrcoef",
"numpy.argsort",
"numpy.array",
"numpy.sum",
"numpy.abs",
"numpy.fft.rfft",
"numpy.isfinite",
"numpy.percentile",
"numpy.angle",
"numpy.array_split",
"pandas.qcut"
]
] |
justincohler/evictions-learn
|
[
"d9d07c2e9bfc6d78978936d732f0309b1c2157fa"
] |
[
"src/analysis/helpers/outlier_table.py"
] |
[
"import psycopg2\nimport os\nimport json\nimport pandas as pd\nimport sys\nsys.path.insert(0, '/Users/alenastern/Documents/Spring2018/Machine_Learning/evictions-learn/src/')\nfrom db_init import db_connect\ndef outlier_table(cur = db_connect()[0]):\n cols = [\"population\", \"poverty_rate\", \"pct_renter_occupied\", \"median_gross_rent\", \"median_household_income\",\n \"median_property_value\", \"rent_burden\", \"pct_white\", \"pct_af_am\", \"pct_hispanic\", \"pct_am_ind\",\n \"pct_asian\", \"pct_nh_pi\", \"pct_multiple\", \"pct_other\", \"renter_occupied_households\", \"eviction_filings\",\n \"evictions\", \"eviction_rate\", \"eviction_filing_rate\"]\n\n table = []\n for col in cols:\n cur.execute(\"ROLLBACK;\")\n #drop temp table if it exists already\n try:\n cur.execute(\"DROP TABLE tmp;\")\n except:\n pass\n\n #create tmp table for vairable\n tmp = '''CREATE TEMP TABLE tmp as SELECT avg({}) as mean, stddev({})*3 as out_there \n FROM evictions.blockgroup;'''.format(col, col)\n\n #identify count and average of high and low outliers\n query_high = \"SELECT count({}), avg({}) FROM evictions.blockgroup WHERE {} > (select mean + out_there from tmp);\".format(col, col, col)\n query_low = \"SELECT count({}), avg({}) FROM evictions.blockgroup WHERE {} < (select mean - out_there from tmp);\".format(col, col, col)\n \n #execute queries and build output table\n cur.execute(tmp)\n cur.execute(query_high)\n row = [col] + list(cur.fetchone())\n cur.execute(query_low)\n row += list(cur.fetchone())\n table.append(row)\n\n df = pd.DataFrame(table)\n df.columns = [\"variable\", \"count high\", \"avg high\", \"count low\", \"avg low\"]\n df.to_csv(\"outlier_table.csv\")\n\n return df\n\n"
] |
[
[
"pandas.DataFrame"
]
] |
dberardi2020/MovieSorter
|
[
"451b9c1004758a20f179cf39a5ab676b274a970e"
] |
[
"Classes/Statistics.py"
] |
[
"from os import path\n\nimport pandas as pd\n\nfrom definitions import const, helpers\n\n\nclass _Statistics:\n def __init__(self, name):\n self.pickle = path.join(const.data_dir, f\"{name}.pkl\")\n\n def _create_pickle(self):\n pd.DataFrame([]).to_pickle(self.pickle)\n\n def _get_dataframe(self) -> pd.DataFrame:\n if not path.exists(self.pickle):\n self._create_pickle()\n\n return pd.read_pickle(self.pickle)\n\n def add_stat(self, size: int, time: int):\n dataframe = self._get_dataframe().append([[size, round(time)]])\n dataframe.to_pickle(self.pickle)\n\n def print_stat(self):\n if self._get_dataframe().empty:\n print(\"Insufficient Data\")\n return\n\n size_total = int(self._get_dataframe()[0].sum())\n time_total = int(self._get_dataframe()[1].sum())\n average = round(time_total / size_total)\n\n print(self._get_dataframe())\n print(f\"Total Size: {size_total}\")\n print(f\"Total Length: {time_total}\")\n print(f\"Average: {average} s/GB\")\n\n def estimate(self, size: int):\n if self._get_dataframe().empty:\n return \"Insufficient Data\"\n\n size_total = int(self._get_dataframe()[0].sum())\n time_total = int(self._get_dataframe()[1].sum())\n average = round(time_total / size_total)\n return helpers.format_time(size * average)\n\n\ncompression = _Statistics(\"compression\")\nupload = _Statistics(\"upload\")\n"
] |
[
[
"pandas.read_pickle",
"pandas.DataFrame"
]
] |
JSeam2/IsoGraph
|
[
"96faf0b61ff9bf7f725cda055e89b26261338376"
] |
[
"genetic/genetic_algo.py"
] |
[
"\"\"\"\nImplementation referenced from\nhttps://github.com/handcraftsman/GeneticAlgorithmsWithPython/blob/master/ch02/genetic.py\n\"\"\"\n\nimport random\nfrom qutip import *\nimport numpy as np\nimport pandas as pd\nfrom functools import reduce\nimport datetime\nimport time\nimport pickle\nimport copy\n\n\n# QUTIP NOTES\n# hadamard = \"SNOT\"\n# CZ = \"CSIGN\"\n# RZ = \"RZ\"\n\ndef make_circuit(theta_val, save_image = False):\n \"\"\"\n Input theta values to create quantum circuit\n [layer 1], [layer 2]. so on\n the length of each layer should equal length of\n input state\n\n The theta list will act as our genome\n\n theta_val: 2D numpy array\n\n return 2D numpy array of matrices\n \"\"\"\n qc = QubitCircuit(N = len(theta_val[0]))\n\n for i in range(len(theta_val)):\n # ADD H gates\n qc.add_1q_gate(\"SNOT\", start = 0, end = qc.N)\n\n # add RZ theta gates\n for k in range(len(theta_val[0])):\n qc.add_1q_gate(\"RZ\", start = k, end = k + 1,\n arg_value = theta_val[i][k],\n arg_label = theta_val[i][k])\n\n for k in range(len(theta_val[0]) - 1):\n qc.add_gate(\"CSIGN\",\n targets = [k],\n controls = [k+1])\n\n # add a hadamard at the end\n qc.add_1q_gate(\"SNOT\", start = 0, end = qc.N)\n\n # produce image\n if save_image:\n qc.png\n\n return reduce(lambda x, y: x * y, qc.propagators())\n\n\ndef generate_initial_population(N, data, population_size = 20, depth = 5):\n \"\"\"\n population size is the number of individuals in the population\n N refers to the number of nodes\n depth refers to then number of layers\n\n population_size: int\n N: int\n \"\"\"\n genes = []\n while len(genes) < population_size:\n # we add a +1 to the circuit as use a |0> qubit for measurement\n genes.append(np.random.uniform(-np.pi, np.pi, [depth, N*2 + 1]))\n\n fitness, acc = get_fitness(genes, data)\n\n return PopulationPool(genes, fitness, acc)\n\n\ndef generate_children(parent, data, take_best,\n population_size = 20,\n mutation_rate = 0.05):\n \"\"\"\n produce children with mutations\n\n parent: PopulationPool class\n mutation_rate: float probability that value will be mutated\n crossover_rate: float probability that genes will cross with another gene\n \"\"\"\n child_genes = []\n\n best_parent_genes = parent.genes[:take_best]\n while len(child_genes) < population_size:\n # randomly pick a parent\n parentA_gene = random.choice(best_parent_genes)\n\n # randomly pick another parent\n parentB_gene = random.choice(best_parent_genes)\n\n # crossover the gene at a random point\n rand_point = random.randint(0, parentA_gene.shape[0])\n\n if random.random() <= mutation_rate:\n # Crossover\n if parentB_gene.shape[0] < rand_point:\n child_gene = np.vstack((parentA_gene[0:rand_point],\n parentB_gene[rand_point, parentB_gene.shape[0]]))\n\n else :\n child_gene = parentA_gene\n\n # randomly change values in the array\n mask = np.random.randint(0,2,size=child_gene.shape).astype(np.bool)\n r = np.random.uniform(-np.pi, np.pi, size = child_gene.shape)\n child_gene[mask] = r[mask]\n\n else:\n child_gene = parentA_gene\n\n child_genes.append(child_gene)\n\n fitness, acc = get_fitness(child_genes, data)\n\n return PopulationPool(child_genes, fitness, acc)\n\n\ndef evaluate(input_str, circuit):\n \"\"\"\n Evaluate input sequence of bits\n Include an additional ancilla qubit in input\n for measurement\n \"\"\"\n pass\n\n\ndef get_fitness(genes, data):\n \"\"\"\n Pass in gene and run through the various isomorphic graphs\n\n gene: list of np array\n data: panda dataframe from pkl file\n\n returns list of fitness\n \"\"\"\n # total number of samples\n num_sample = data.shape[0]\n\n # select upper diagonal ignoring zeros in the middle\n size = data[\"G1\"][0].shape[0]\n upper = np.triu_indices(size, 1)\n\n # create projector we project to 0 standard basis\n projector = basis(2,0) * basis(2,0).dag()\n\n for i in range(size * 2):\n projector = tensor(projector, identity(2))\n\n fitness_list = []\n acc_list = []\n\n for gene in genes:\n loss = 0\n correct = 0\n\n # make circuit using the genes\n circuit = make_circuit(gene, False)\n\n for index, row in data.iterrows():\n #if index % 2500 == 0:\n # print(\"running {}\".format(index))\n\n # add a |0> to the last qubit as we will use\n # it for measurements\n combined = row[\"G1\"][upper].tolist()[0] + \\\n row[\"G2\"][upper].tolist()[0]\n\n combined.append(\"0\")\n\n int_comb = [int(i) for i in combined]\n inputval = bra(int_comb)\n result = inputval * circuit\n density = result.dag() * result\n\n # We will use the logisitc regression loss function\n # as we are dealing with a classification problem\n # compare this expectation with result \n # expectation here refers to the likelihood of getting 0\n expectation = expect(projector, density)\n actual = row[\"is_iso\"]\n\n loss += -1 * actual * np.log(1 - expectation) \\\n - (1 - actual) * np.log(expectation)\n\n if expectation <= 0.50:\n # this is 1\n prediction = 1\n\n else:\n prediction = 0\n\n if prediction == actual:\n correct += 1\n\n\n ave_loss = loss/num_sample\n fitness_list.append(ave_loss)\n\n accuracy = correct/num_sample\n acc_list.append(accuracy)\n\n return fitness_list, acc_list\n\n\ndef get_best(N, data, num_epoch = 10,\n population_size = 20,\n take_best = 5,\n depth = 5,\n mutation_rate = 0.05):\n\n \"\"\"\n N refers to the number of nodes\n Population size refers to the number of individuals in the population\n Take_best refers to the number of top individuals we take\n depth refers to how deep the quantum circuit should go\n mutation_rate refers to the probability of children mutating\n \"\"\"\n assert take_best >= 2\n assert population_size >= 2\n assert take_best <= population_size\n\n def display(pool):\n print(\"Time: {} \\t Best Score: {} \\t Best Acc: {}\".format(datetime.datetime.now(),\n pool.fitness[0],\n pool.accuracy[0]))\n\n parent = generate_initial_population(N, data, population_size, depth)\n parent.sort()\n print(\"Seed Population\")\n display(parent)\n\n # take best\n\n for i in range(num_epoch):\n child = generate_children(parent, data, take_best, population_size,\n mutation_rate)\n child.sort()\n print()\n print(\"Child\")\n print(\"Epoch {}\".format(i))\n display(child)\n\n # if the parent best fitness is greater than child.fitness get the\n # let the child be the parent to get next generation\n if parent.fitness[0] > child.fitness[0]:\n parent = copy.deepcopy(child)\n print(\"Parent is now the child, New Parent:\")\n display(parent)\n\n else:\n print(\"Parent retained, Current Parent:\")\n display(parent)\n\n return parent.genes\n\n\nclass PopulationPool:\n def __init__(self, genes, fitness, accuracy):\n \"\"\"\n genes : list of genes\n fitness : list of fitness\n accuracy : list of accuracy\n \"\"\"\n self.genes = genes\n self.fitness = fitness\n self.accuracy = accuracy\n\n def sort(self):\n \"\"\"\n returns list of genes sorted by fitness in increasing order\n\n \"\"\"\n self.genes = [x for _,x in sorted(zip(self.fitness, self.genes))]\n self.accuracy = [x for _,x in sorted(zip(self.fitness, self.accuracy))]\n\n\nif __name__ == \"__main__\":\n print(\"Start Program\")\n df = pd.read_pickle(\"3_node_10000.pkl\")\n\n print(\"Depth = 10\")\n out_genes = get_best(N=3,\n data = df,\n num_epoch = 50,\n population_size = 20,\n take_best = 5,\n depth = 10,\n mutation_rate = 0.05)\n\n with open(\"save1.pkl\", \"wb\") as f:\n pickle.dump(out_genes,f)\n\n print(\"==========================\")\n print(\"Depth = 15\")\n out_genes = get_best(N=3,\n data = df,\n num_epoch = 50,\n population_size = 20,\n take_best = 5,\n depth = 15,\n mutation_rate = 0.05)\n\n with open(\"save2.pkl\", \"wb\") as f:\n pickle.dump(out_genes,f)\n\n print(\"==========================\")\n print(\"Depth = 20\")\n\n out_genes = get_best(N=3,\n data = df,\n num_epoch = 50,\n population_size = 20,\n take_best = 5,\n depth = 20,\n mutation_rate = 0.05)\n\n with open(\"save3.pkl\", \"wb\") as f:\n pickle.dump(out_genes,f)\n\n print(\"==========================\")\n print(\"Depth = 25\")\n\n out_genes = get_best(N=3,\n data = df,\n num_epoch = 50,\n population_size = 20,\n take_best = 5,\n depth = 25,\n mutation_rate = 0.05)\n\n with open(\"save4.pkl\", \"wb\") as f:\n pickle.dump(out_genes,f)\n\n print(\"==========================\")\n print(\"Depth = 30\")\n\n out_genes = get_best(N=3,\n data = df,\n num_epoch = 50,\n population_size = 20,\n take_best = 5,\n depth = 30,\n mutation_rate = 0.05)\n\n with open(\"save5.pkl\", \"wb\") as f:\n pickle.dump(out_genes,f)\n\n # to open \n #with open(\"save.pkl\", \"rb\") as f:\n # save_genes = pickle.load(f)\n\n # total number of samples\n #num_sample = df.shape[0]\n\n ## select upper diagonal ignoring zeros in the middle\n #size = df[\"G1\"][0].shape[0]\n #upper = np.triu_indices(size, 1)\n\n ## create projector we project to 0 standard basis\n #projector = basis(2,0) * basis(2,0).dag()\n\n #for i in range((size * 2) - 1):\n # projector = tensor(projector, identity(2))\n\n #fitness_list = []\n #acc_list = []\n\n #parent = generate_initial_population(3, df, 2, 3)\n\n #for gene in parent:\n # loss = 0\n # correct = 0\n\n # # make circuit using the genes\n # circuit = make_circuit(gene, True)\n # break\n"
] |
[
[
"numpy.log",
"numpy.triu_indices",
"numpy.random.uniform",
"pandas.read_pickle",
"numpy.vstack",
"numpy.random.randint"
]
] |
vsvarunsharma10/pqai
|
[
"3ef1351fbc39671916517917de9074a62b092eef",
"3ef1351fbc39671916517917de9074a62b092eef"
] |
[
"core/indexer.py",
"core/indexes.py"
] |
[
"import annoy\nimport faiss\nimport numpy as np\nfrom psutil import virtual_memory\nfrom math import ceil\nfrom os import path\nimport json\n\n#from config.config import INDEX_DIR\n\n\nclass Indexer():\n\n \"\"\"\n Loads and caches vector indexes of various types (Annoy, FAISS).\n \"\"\"\n \n class __impl:\n\n \"\"\"\n A singleton class to make sure that only one copy of this\n class exists in the memory. This is important because its\n instances caches data in memory and multiple copies may lead to\n caching of redundant data leading to increased memory\n consumption.\n \"\"\"\n def __init__(self):\n \"\"\"Initialize an Indexer class.\n \"\"\"\n\n # directory where indexes are stored\n self._dir = INDEX_DIR\n\n # enabling this will speed up the search but will consume\n # more momory\n self._cache_enabled = True\n\n self._cache = {}\n self._default_index_type = 'faiss'\n\n def __getitem__(self, index_id):\n \"\"\"Get an index with given name.\n \n Args:\n index_id (str): The index's name.\n \n Returns:\n Index: The Index object corresponding to the requested\n `index_id`.\n \"\"\"\n return self.get_index(index_id)\n \n def get_index(self, index_id, index_type=None):\n \"\"\"Get the index with the given name and type.\n \n Args:\n index_id (str): The index's name.\n index_type (str, optional): The index's type, e.g.,\n 'annoy' or 'faiss'.\n \n Returns:\n Index: The Index object corresponding to the given\n name and index type.\n \"\"\"\n index_type = self._default_index_type\n if self._in_cache(index_id, index_type):\n return self._get_index_from_cache(index_id, index_type)\n else:\n index = self._get_index_from_disk(index_id, index_type)\n return index\n\n def _in_cache(self, index_id, index_type):\n \"\"\"Check whether an index is cached in the memory.\n \n Args:\n index_id (str): The index's name.\n index_type (str): The index's type.\n \n Returns:\n bool: True if the index is available in the cache, False\n otherwise.\n \"\"\"\n key = (index_id, index_type)\n return key in self._cache\n\n def _get_index_from_cache(self, index_id, index_type):\n \"\"\"Return the specified Index object from the cache.\n\n Args:\n index_id (str): The index's name.\n index_type (str): The index's type.\n \n Returns:\n Index: The Index object corresponding to the given\n name and index type.\n \"\"\"\n key = (index_id, index_type)\n cached = self._cache.get(key)\n return cached\n\n def _add_index_to_cache(self, index_id, index_type, index):\n \"\"\"Add the index to in-memory cache.\n \n Args:\n index_id (str): The Index's name.\n index_type (str): The Index's type.\n index (Index): An object of the class Index.\n \n Returns:\n bool: True if caching successful, False otherwise.\n \"\"\"\n key = (index_id, index_type)\n self._cache[key] = index\n return key in self._cache\n\n def _get_index_from_disk(self, index_id, index_type):\n \"\"\"Return the specified Index object by loading it from the\n disk.\n\n Args:\n index_id (str): The index's name.\n index_type (str): The index's type.\n \n Returns:\n Index: The Index object corresponding to the given\n name and index type.\n \"\"\"\n if index_type == 'faiss':\n index = IndexFaiss(index_id, self._dir)\n elif index_type == 'annoy':\n index = IndexAnnoy(index_id, self._dir)\n else:\n raise Exception('Invalid index type.')\n\n # Cache for later use\n if self._cache_enabled:\n self._add_to_cache(index_id, index_type, index)\n\n return index\n\n #__instance = __impl(distilbert_model_path)\n\n def __getattr__(self, attr):\n return getattr(self.__instance, attr)\n\n def __setattr__(self, attr, value):\n return setattr(self.__instance, attr, value)\n\n def __getitem__(self, key):\n return self.__instance.__getitem__(key)\n\nclass IndexAnnoy():\n\n def __init__(self, index_id, folder):\n self.index_id = index_id\n self.folder = folder\n self.index_file_path = f\"{self.folder}/{self.index_id}.ann\"\n self.labels_file_path = f\"{self.index_file_path}.items.json\"\n self.dims = None\n self.ndims = 256\n\n def __getitem__(self, index_id):\n pass\n\n def create(self, vectors, labels=None):\n \"\"\"Create Annoy index file for user.\n\n Args:\n vectors(nd array): vectors to create index.\n labels (list): labels list if already exists.\n\n Returns:\n True if Annoy index is created.\n \"\"\"\n self.nvecs = vectors.shape[0]\n index = self._build_index(vectors)\n labels = self._create_labels(labels)\n return True\n\n def _build_index(self, vectors):\n \"\"\"Build Annoy index with the given vectors.\n\n Args: \n vectors(nd array): vectors to create index.\n\n Returns:\n index: The index created and saved.\n \"\"\"\n index = annoy.AnnoyIndex(self.ndims, 'angular')\n for i in range(self.nvecs):\n index.add_item(i, vectors[i])\n ntrees = 20\n index.build(ntrees)\n index.save(self.index_file_path)\n return index\n\n def _create_labels(self, labels):\n \"\"\"Creates labels for the index.\n\n Args:\n labels (list): labels list if already exists.\n\n Returns:\n labels (list): New created labels list.\n \"\"\"\n if labels is None:\n labels = list(range(self.nvecs))\n with open(self.labels_file_path, 'w+') as f:\n f.write(json.dumps(labels))\n return labels\n\n def get_vectors(self):\n \"\"\"Exract vectors from Annoy index file.\n\n Returns:\n vectors(nd array): All vectors in index file. \n \"\"\"\n index = annoy.AnnoyIndex(self.ndims, 'angular')\n index.load(self.index_file_path)\n vectors = np.empty((index.get_n_items(), self.ndims), 'float32')\n for j in range(index.get_n_items()):\n vectors[j] = index.get_item_vector(j)\n return vectors\n\n def get_labels(self):\n \"\"\"Exract labels from Annoy index file.\n\n Returns:\n vectors(nd array): All labels in index file. \n \"\"\"\n with open(self.labels_file_path) as f:\n data = json.load(f)\n labels = np.array(data)\n return labels\n\n def find_similar(self, query_vectors, n):\n \"\"\"Search n nearest neighbours from the index file.\n\n Args:\n query_vectors(nd array): vectors to be searched.\n n (int): number of nearest neighbours.\n\n Returns:\n indices (nd array): indices of search result vectors. \n \"\"\"\n index = annoy.AnnoyIndex(self.ndims, 'angular')\n index.load(self.index_file_path)\n nearest_neighbours = n\n indices = index.get_nns_by_vector(\n query_vectors, nearest_neighbours, include_distances=False)\n return indices\n\n def find_similar_with_dist(self, query_vectors, n):\n \"\"\"Provide distance of n nearest neighbours from query vector.\n\n Args:\n query_vectors(nd array): vectors to be searched.\n n (int): number of nearest neighbours.\n\n Returns:\n distances (nd array): distances of each search result from query vectors. \n \"\"\"\n index = annoy.AnnoyIndex(self.ndims, 'angular')\n index.load(self.index_file_path)\n nearest_neighbours = n\n distances = index.get_nns_by_vector(\n query_vectors, nearest_neighbours, include_distances=True)[1]\n return distances\n\n def get_n_items(self):\n \"\"\"Returns the number of items in the index.\n \"\"\"\n index = annoy.AnnoyIndex(self.ndims, 'angular')\n index.load(self.index_file_path)\n return index.get_n_items()\n\nclass IndexFaiss():\n\n def __init__(self, index_id, folder):\n \"\"\"Initialize\n \n Args:\n index_id (str): Name of index\n folder (str): Filesystem path where index is (or will be)\n stored\n \"\"\"\n self._n_clusters = 20\n self._index_id = index_id\n self._folder = folder[:-1] if folder.endswith('/') else folder\n self._index_file = f'{self._folder}/{self._index_id}.index'\n self._labels_file = f'{self._folder}/{self._index_id}.labels.json'\n self._div_factor_file = f'{self._folder}/{self._index_id}.divf.txt'\n self._metric = faiss.METRIC_INNER_PRODUCT\n self._labels = None\n self._index = None\n\n def __getitem__(self, item_label):\n pass\n\n def create(self, vectors, labels=None):\n \"\"\"Create a new index with the given id and vectors.\n \n Args:\n vectors (nd array): vectors to create index\n labels (None, optional): Labels for the vectors\n \"\"\"\n self._n_dims = vectors[0].shape[0]\n if len(labels)!=0:\n self._labels = list(range(len(vectors)))\n\n self._build_index(vectors)\n self._write_labels_file()\n self._write_index_file()\n\n def _build_index(self, vectors):\n \"\"\"Build index structure.\n\n Args:\n vectors (nd array): vectors to create index\n \"\"\"\n faiss.normalize_L2(vectors)\n quantiser = faiss.IndexFlatIP(self._n_dims)\n self._index = faiss.IndexIVFFlat(\n quantiser, self._n_dims, self._n_clusters, self._metric)\n self._index.train(vectors)\n\n def _write_index_file(self):\n \"\"\"Write index to disk.\n \"\"\"\n faiss.write_index(self._index, f'{self._folder}/{self._index_id}.Original.index')\n\n def _write_labels_file(self):\n \"\"\"Write labels to disk.\n \"\"\"\n with open(self._labels_file, 'w') as file:\n file.write(json.dumps(self._labels))\n\n def add_vectors(self, vectors, labels=None):\n \"\"\"Add vectors to existing index.\n\n Args: \n vectors (nd array): vectors to create index\n labels (None, optional): Labels for the vectors\n\n Returns:\n True if vectors are added\n \"\"\"\n self._n_vecs = len(vectors)\n self._n_dims = vectors[0].shape[0]\n ivf = self._distribute_vectors(vectors)\n self._merge_index(ivf)\n return True\n\n def _distribute_vectors(self, vectors):\n \"\"\"Distribute vectors into smaller parts\n\n Args:\n vectors (nd array): vectors to create index\n\n Returns:\n ivf (object): Inverted index\n \"\"\"\n prev_div_factor = self._calculate_prev_div_factor()\n div_factor = self._calculate_div_factor(prev_div_factor)\n self._create_branch_index(div_factor, vectors)\n return self._create_ivf()\n\n def _calculate_prev_div_factor(self):\n \"\"\"Extract previous division factor.\n\n Returns:\n prev_div_factor (int): previous division factor\n \"\"\"\n prev_div_factor = 0\n if (path.isfile(self._div_factor_file)):\n with open(self._div_factor_file, 'r') as file:\n prev_div_factor = int(file.read().strip().splitlines()[0])\n return prev_div_factor\n\n def _calculate_div_factor(self, prev_div_factor):\n \"\"\"Extract current division factor.\n\n Returns:\n div_factor (int): current division factor\n \"\"\"\n mem = virtual_memory()\n div_factor = ceil(self._n_vecs*self._n_dims*4/mem.total)\n self._div_factor = prev_div_factor + div_factor\n with open(self._div_factor_file, 'w+') as file:\n file.write(f'{self._div_factor}')\n return div_factor \n\n def _create_branch_index(self, div_factor, vectors):\n \"\"\"Creating indices of smaller size.\n\n Args:\n div_factor (int): current division factor\n \"\"\"\n for i in range(div_factor):\n index = faiss.read_index(f'{self._folder}/{self._index_id}.Original.index')\n llim = int(i*(self._n_vecs/div_factor))\n ulim = int((i+1)*(self._n_vecs/div_factor))\n ids = np.arange(llim, ulim)\n index.add_with_ids(vectors[llim:ulim], ids)\n faiss.write_index(index, f'{self._folder}/{self._index_id}{self._div_factor-div_factor+i+1}.index')\n\n def _create_ivf(self):\n \"\"\"Creating inverted list for all smaller indices.\n\n Return:\n ivf (list): inverted list\n \"\"\"\n ivf = []\n for i in range(self._div_factor):\n index = faiss.read_index(f'{self._folder}/{self._index_id}{i+1}.index', faiss.IO_FLAG_MMAP)\n ivf.append(index.invlists)\n index.own_invlists = False # to stop deallocation.\n return ivf\n\n def _merge_index(self, ivf):\n \"\"\"Merging all indices created in smaller size.\n\n Args:\n ivf (list): inverted list\n \"\"\"\n self._index = faiss.read_index(f'{self._folder}/{self._index_id}.Original.index')\n invlists = faiss.OnDiskInvertedLists(\n self._n_clusters, self._index.code_size, f\"{self._folder}/{self._index_id}.merged_index.ivfdata\")\n ivf_vector = self._create_ivf_vector(ivf)\n ntotal = invlists.merge_from(ivf_vector.data(), ivf_vector.size())\n self._index.ntotal = ntotal\n self._index.replace_invlists(invlists)\n faiss.write_index(self._index, self._index_file)\n\n def _create_ivf_vector(self, ivf):\n \"\"\"Creating inverted list vector.\n\n Args:\n ivf (list): inverted list\n\n Returns:\n ivf_vector (vector): inverted list vector\n \"\"\"\n ivf_vector = faiss.InvertedListsPtrVector()\n for invlists in ivf:\n ivf_vector.push_back(invlists)\n return ivf_vector\n\n def get_labels(self):\n \"\"\"Provide labels for vectors in index.\n\n Returns:\n labels (nd array): labels of vectors\n \"\"\"\n with open(self._labels_file) as f:\n data = json.load(f)\n labels = np.array(data)\n return labels\n\n def find_similar(self, query_vectors, n):\n \"\"\"Searching n nearest neighbours from query vector.\n\n Args:\n query_vectors(nd array): vectors to be searched.\n n (int): number of nearest neighbours.\n\n Returns:\n indices (nd array): indices of search result vectors. \n \"\"\"\n index = faiss.read_index(self._index_file, faiss.IO_FLAG_MMAP)\n nearest_neighbours = n\n indices = index.search(query_vectors, nearest_neighbours)[1]\n return indices\n\n def find_similar_with_dist(self, query_vectors, n):\n \"\"\"Provide distance of n nearest neighbours from query vector.\n\n Args:\n query_vectors(nd array): vectors to be searched.\n n (int): number of nearest neighbours.\n\n Returns:\n distances (nd array): distances of each search result from query vectors. \n \"\"\"\n index = faiss.read_index(self._index_file, faiss.IO_FLAG_MMAP)\n nearest_neighbours = n\n distances = index.search(query_vectors, nearest_neighbours)[0]\n return distances",
"import numpy as np\nimport annoy\nimport json\nimport os\nimport faiss\n\nfrom config.config import indexes_dir\nfrom config import config\n\nclass Index():\n\n def __init__(self):\n self._search_fn = None\n self._type = 'Index'\n\n def search(self, query, n):\n return self._search_fn(query, n)\n\n @property\n def type(self):\n return self._type\n \n\nclass VectorIndex(Index):\n \n def __init__(self):\n self._type = 'VectorIndex'\n\n\nclass AnnoyIndexReader():\n\n def __init__(self, dims, metric):\n self._dims = dims\n self._metric = metric\n\n def read_from_files(self, ann_file, json_file, name=None):\n index = self._read_ann(ann_file)\n items = self._get_items_from_json(json_file)\n item_resolver = items.__getitem__\n return AnnoyIndex(index, item_resolver, name)\n\n def _read_ann(self, ann_file):\n index = annoy.AnnoyIndex(self._dims, self._metric)\n index.load(ann_file)\n return index\n\n def _get_items_from_json(self, json_file):\n with open(json_file) as file:\n items = json.load(file)\n return items\n\n\nclass AnnoyIndex(VectorIndex):\n\n def __init__(self, index, resolver_fn, name=None):\n self._index = index\n self._index2item = resolver_fn\n self._name = name\n self._search_depth = 1000\n\n def _search_fn(self, qvec, n):\n ids, dists = self._get_similar(qvec, n)\n items = [self._index2item(i) for i in ids]\n return list(zip(items, dists))\n\n def _get_similar(self, qvec, n):\n d = self._search_depth\n return self._index.get_nns_by_vector(qvec, n, d, True)\n\n def set_search_depth(self, d):\n self._search_depth = d\n\n def count(self):\n return self._index.get_n_items()\n\n def dims(self):\n v0 = self._index.get_item_vector(0)\n return len(v0)\n\n def __repr__(self):\n idx_type = 'AnnoyIndex '\n idx_name = 'Unnamed' if self._name is None else self._name\n idx_info = f' [{self.count()} vectors, {self.dims()} dimensions]'\n separator = ' '\n return separator.join([idx_type, idx_name, idx_info])\n\n @property\n def name(self):\n return self._name\n\n\nclass FaissIndexReader():\n\n def read_from_files(self, index_file, json_file, name=None):\n index = faiss.read_index(index_file)\n items = self._get_items_from_json(json_file)\n item_resolver = items.__getitem__\n return FaissIndex(index, item_resolver, name)\n\n def _get_items_from_json(self, json_file):\n with open(json_file) as fp:\n items = json.load(fp)\n return items\n\n\nclass FaissIndex(VectorIndex):\n\n def __init__(self, index=None, resolver_fn=None, name=None):\n self._id = name\n self._index = index\n self._index2label = resolver_fn\n self._labels = None\n self._dims = None\n\n def _search_fn(self, qvec, n):\n Q = self._preprocess([qvec])\n ds, ns = self._index.search(Q, n)\n items = [self._index2label(i) for i in ns[0]]\n dists = [float(d) for d in ds[0]]\n return list(zip(items, dists))\n\n # TODO: Move this to indexer\n def add_vectors(self, vectors, labels):\n if len(vectors) != len(labels):\n raise ValueError('Vector must map one-to-one with labels.')\n X = self._preprocess(vectors)\n if self._index is None:\n self._init(X)\n self._index.add(X)\n self._labels += labels\n self._save()\n\n def _init(self, X):\n self._dims = X.shape[1]\n self._labels = []\n self._index = faiss.index_factory(self._dims, \"OPQ16_64,HNSW32\")\n self._index.train(X)\n\n def _preprocess(self, vectors):\n X = np.array(vectors).astype('float32')\n faiss.normalize_L2(X)\n return X\n\n def _save(self):\n index_file = f'{self._index_dir}/{self._id}.faiss'\n labels_file = f'{self._index_dir}/{self._id}.labels.json'\n faiss.write_index(self._index, index_file)\n with open(labels_file, 'w') as fp:\n json.dump(self._labels, fp)\n\n @property\n def name(self):\n return self._id\n\n\nclass IndexesDirectory():\n\n cache = {}\n dims = 768\n metric = 'angular'\n use_faiss_indexes = config.use_faiss_indexes\n use_annoy_indexes = config.use_annoy_indexes\n\n def __init__(self, folder):\n self._folder = folder\n self._available = self._discover_indexes()\n\n def _discover_indexes(self):\n files = os.scandir(self._folder)\n index_files = []\n if self.use_faiss_indexes:\n index_files += [f for f in files if f.name.endswith('.faiss')]\n if self.use_annoy_indexes:\n index_files += [f for f in files if f.name.endswith('.ann')]\n index_ids = ['.'.join(f.name.split('.')[:-1]) for f in index_files]\n return set(index_ids)\n\n def get(self, index_id):\n index_ids = filter(lambda x: x.startswith(index_id), self.available())\n indexes = [self._get_one_index(idx) for idx in index_ids]\n return indexes\n\n def _get_one_index(self, index_id):\n if index_id in self.cache:\n return self.cache.get(index_id)\n return self._get_from_disk(index_id)\n\n def _get_from_disk(self, index_id):\n index_file = self._get_index_file_path(index_id)\n json_file = f'{self._folder}/{index_id}.items.json'\n if index_file.endswith('faiss'):\n reader = FaissIndexReader()\n else:\n reader = AnnoyIndexReader(self.dims, self.metric)\n index = reader.read_from_files(index_file, json_file, name=index_id)\n self._cache_index(index_id, index)\n return index\n\n def _get_index_file_path(self, index_id):\n ann_file = f'{self._folder}/{index_id}.ann'\n faiss_file = f'{self._folder}/{index_id}.faiss'\n return faiss_file if (os.path.exists(faiss_file)) else ann_file\n\n def _cache_index(self, index_id, index):\n self.cache[index_id] = index\n\n def available(self):\n return self._available\n"
] |
[
[
"numpy.arange",
"numpy.array"
],
[
"numpy.array"
]
] |
edmundus/tikzplotlib
|
[
"34a984069c5ec3222b239f2252a7e013993a63d1"
] |
[
"tikzplotlib/axes.py"
] |
[
"import matplotlib as mpl\nimport numpy\nfrom matplotlib.backends import backend_pgf as mpl_backend_pgf\n\nfrom . import color\n\n\nclass Axes:\n def __init__(self, data, obj):\n \"\"\"Returns the PGFPlots code for an axis environment.\n \"\"\"\n self.content = []\n\n # Are we dealing with an axis that hosts a colorbar? Skip then, those are\n # treated implicitily by the associated axis.\n self.is_colorbar = _is_colorbar_heuristic(obj)\n if self.is_colorbar:\n return\n\n # instantiation\n self.nsubplots = 1\n self.subplot_index = 0\n self.is_subplot = False\n\n if isinstance(obj, mpl.axes.Subplot):\n self._subplot(obj, data)\n\n self.axis_options = []\n\n # check if axes need to be displayed at all\n if not obj.axison:\n self.axis_options.append(\"hide x axis\")\n self.axis_options.append(\"hide y axis\")\n\n # get plot title\n title = obj.get_title()\n data[\"current axis title\"] = title\n if title:\n self.axis_options.append(u\"title={{{}}}\".format(title))\n\n # get axes titles\n xlabel = obj.get_xlabel()\n xrotation = obj.xaxis.get_label().get_rotation()\n if xlabel:\n xlabel = mpl_backend_pgf.common_texification(xlabel)\n self.axis_options.append(u\"xlabel={{{}}}\".format(xlabel))\n if xrotation != 0:\n self.axis_options.append(\n u\"xlabel style={{rotate={}}}\".format(xrotation - 90)\n )\n ylabel = obj.get_ylabel()\n yrotation = obj.yaxis.get_label().get_rotation()\n if ylabel:\n ylabel = mpl_backend_pgf.common_texification(ylabel)\n self.axis_options.append(u\"ylabel={{{}}}\".format(ylabel))\n if yrotation != 90:\n self.axis_options.append(\n u\"ylabel style={{rotate={}}}\".format(yrotation - 90)\n )\n\n # Axes limits.\n # Sort the limits so make sure that the smaller of the two is actually *min.\n ff = data[\"float format\"]\n xlim = sorted(list(obj.get_xlim()))\n self.axis_options.append((\"xmin=\" + ff + \", xmax=\" + ff).format(*xlim))\n ylim = sorted(list(obj.get_ylim()))\n self.axis_options.append((\"ymin=\" + ff + \", ymax=\" + ff).format(*ylim))\n\n # axes scaling\n if obj.get_xscale() == \"log\":\n self.axis_options.append(\"xmode=log\")\n self.axis_options.append(\n \"log basis x={{{}}}\".format(_try_f2i(obj.xaxis._scale.base))\n )\n if obj.get_yscale() == \"log\":\n self.axis_options.append(\"ymode=log\")\n self.axis_options.append(\n \"log basis y={{{}}}\".format(_try_f2i(obj.yaxis._scale.base))\n )\n\n # Possible values for get_axisbelow():\n # True (zorder = 0.5): Ticks and gridlines are below all Artists.\n # 'line' (zorder = 1.5): Ticks and gridlines are above patches (e.g.\n # rectangles) but still below lines / markers.\n # False (zorder = 2.5): Ticks and gridlines are above patches and lines /\n # markers.\n if not obj.get_axisbelow():\n self.axis_options.append(\"axis on top\")\n\n # aspect ratio, plot width/height\n aspect = obj.get_aspect()\n if aspect in [\"auto\", \"normal\"]:\n aspect_num = None # just take the given width/height values\n elif aspect == \"equal\":\n aspect_num = 1.0\n else:\n aspect_num = float(aspect)\n\n self._set_axis_dimensions(data, aspect_num, xlim, ylim)\n\n # axis positions\n xaxis_pos = obj.get_xaxis().label_position\n if xaxis_pos == \"top\":\n # default: \"bottom\"\n self.axis_options.append(\"axis x line=top\")\n\n yaxis_pos = obj.get_yaxis().label_position\n if yaxis_pos == \"right\":\n # default: \"left\"\n self.axis_options.append(\"axis y line=right\")\n\n self._ticks(data, obj)\n\n self._grid(obj, data)\n\n # axis line styles\n # Assume that the bottom edge color is the color of the entire box.\n axcol = obj.spines[\"bottom\"].get_edgecolor()\n data, col, _ = color.mpl_color2xcolor(data, axcol)\n if col != \"black\":\n self.axis_options.append(\"axis line style={{{}}}\".format(col))\n\n # background color\n bgcolor = obj.get_facecolor()\n\n data, col, _ = color.mpl_color2xcolor(data, bgcolor)\n if col != \"white\":\n self.axis_options.append(\"axis background/.style={{fill={}}}\".format(col))\n\n # find color bar\n colorbar = _find_associated_colorbar(obj)\n if colorbar:\n self._colorbar(colorbar, data)\n\n if self.is_subplot:\n self.content.append(\"\\n\\\\nextgroupplot\")\n else:\n self.content.append(\"\\\\begin{axis}\")\n\n return\n\n def get_begin_code(self):\n content = self.content\n if self.axis_options:\n # Put axis_options in a deterministic order to avoid diff churn.\n self.axis_options.sort()\n content.append(\"[\\n\" + \",\\n\".join(self.axis_options) + \"\\n]\\n\")\n return content\n\n def get_end_code(self, data):\n if not self.is_subplot:\n return \"\\\\end{axis}\\n\\n\"\n elif self.is_subplot and self.nsubplots == self.subplot_index:\n data[\"is_in_groupplot_env\"] = False\n return \"\\\\end{groupplot}\\n\\n\"\n\n return \"\"\n\n def _set_axis_dimensions(self, data, aspect_num, xlim, ylim):\n if data[\"fwidth\"] and data[\"fheight\"]:\n # width and height overwrite aspect ratio\n self.axis_options.append(\"width=\" + data[\"fwidth\"])\n self.axis_options.append(\"height=\" + data[\"fheight\"])\n elif data[\"fwidth\"]:\n # only data['fwidth'] given. calculate height by the aspect ratio\n self.axis_options.append(\"width=\" + data[\"fwidth\"])\n if aspect_num:\n alpha = aspect_num * (ylim[1] - ylim[0]) / (xlim[1] - xlim[0])\n if alpha == 1.0:\n data[\"fheight\"] = data[\"fwidth\"]\n else:\n # Concatenate the literals, as data['fwidth'] could as well\n # be a LaTeX length variable such as \\figurewidth.\n data[\"fheight\"] = str(alpha) + \"*\" + data[\"fwidth\"]\n self.axis_options.append(\"height=\" + data[\"fheight\"])\n elif data[\"fheight\"]:\n # only data['fheight'] given. calculate width by the aspect ratio\n self.axis_options.append(\"height=\" + data[\"fheight\"])\n if aspect_num:\n alpha = aspect_num * (ylim[1] - ylim[0]) / (xlim[1] - xlim[0])\n if alpha == 1.0:\n data[\"fwidth\"] = data[\"fheight\"]\n else:\n # Concatenate the literals, as data['fheight'] could as\n # well be a LaTeX length variable such as \\figureheight.\n data[\"fwidth\"] = str(1.0 / alpha) + \"*\" + data[\"fheight\"]\n self.axis_options.append(\"width=\" + data[\"fwidth\"])\n else:\n # TODO keep an eye on https://tex.stackexchange.com/q/480058/13262\n pass\n return\n\n def _ticks(self, data, obj):\n # get ticks\n self.axis_options.extend(\n _get_ticks(data, \"x\", obj.get_xticks(), obj.get_xticklabels())\n )\n self.axis_options.extend(\n _get_ticks(data, \"y\", obj.get_yticks(), obj.get_yticklabels())\n )\n self.axis_options.extend(\n _get_ticks(\n data, \"minor x\", obj.get_xticks(\"minor\"), obj.get_xticklabels(\"minor\")\n )\n )\n self.axis_options.extend(\n _get_ticks(\n data, \"minor y\", obj.get_yticks(\"minor\"), obj.get_yticklabels(\"minor\")\n )\n )\n\n try:\n l0 = obj.get_xticklines()[0]\n except IndexError:\n pass\n else:\n c0 = l0.get_color()\n data, xtickcolor, _ = color.mpl_color2xcolor(data, c0)\n self.axis_options.append(\"xtick style={{color={}}}\".format(xtickcolor))\n\n try:\n l0 = obj.get_yticklines()[0]\n except IndexError:\n pass\n else:\n c0 = l0.get_color()\n data, ytickcolor, _ = color.mpl_color2xcolor(data, c0)\n self.axis_options.append(\"ytick style={{color={}}}\".format(ytickcolor))\n\n # Find tick direction\n # For new matplotlib versions, we could replace the direction getter by\n # `get_ticks_direction()`, see\n # <https://github.com/matplotlib/matplotlib/pull/5290>. Unfortunately, _tickdir\n # doesn't seem to be quite accurate. See\n # <https://github.com/matplotlib/matplotlib/issues/5311>. For now, just take\n # the first tick direction of each of the axes.\n x_tick_dirs = [tick._tickdir for tick in obj.xaxis.get_major_ticks()]\n y_tick_dirs = [tick._tickdir for tick in obj.yaxis.get_major_ticks()]\n if x_tick_dirs or y_tick_dirs:\n if x_tick_dirs and y_tick_dirs:\n direction = x_tick_dirs[0] if x_tick_dirs[0] == y_tick_dirs[0] else None\n elif x_tick_dirs:\n direction = x_tick_dirs[0]\n else:\n # y_tick_dirs must be present\n direction = y_tick_dirs[0]\n\n if direction:\n if direction == \"in\":\n # 'tick align=inside' is the PGFPlots default\n pass\n elif direction == \"out\":\n self.axis_options.append(\"tick align=outside\")\n else:\n assert direction == \"inout\"\n self.axis_options.append(\"tick align=center\")\n\n # Set each rotation for every label\n x_tick_rotation_and_horizontal_alignment = self._get_label_rotation_and_horizontal_alignment(\n obj, data, \"x\"\n )\n if x_tick_rotation_and_horizontal_alignment:\n self.axis_options.append(x_tick_rotation_and_horizontal_alignment)\n\n y_tick_rotation_and_horizontal_alignment = self._get_label_rotation_and_horizontal_alignment(\n obj, data, \"y\"\n )\n if y_tick_rotation_and_horizontal_alignment:\n self.axis_options.append(y_tick_rotation_and_horizontal_alignment)\n\n # Set tick position\n x_tick_position_string, x_tick_position = _get_tick_position(obj, \"x\")\n y_tick_position_string, y_tick_position = _get_tick_position(obj, \"y\")\n\n if x_tick_position == y_tick_position and x_tick_position is not None:\n self.axis_options.append(\"tick pos={}\".format(x_tick_position))\n else:\n self.axis_options.append(x_tick_position_string)\n self.axis_options.append(y_tick_position_string)\n\n return\n\n def _grid(self, obj, data):\n # Don't use get_{x,y}gridlines for gridlines; see discussion on\n # <http://sourceforge.net/p/matplotlib/mailman/message/25169234/> Coordinate of\n # the lines are entirely meaningless, but styles (colors,...) are respected.\n if obj.xaxis._gridOnMajor:\n self.axis_options.append(\"xmajorgrids\")\n if obj.xaxis._gridOnMinor:\n self.axis_options.append(\"xminorgrids\")\n\n xlines = obj.get_xgridlines()\n if xlines:\n xgridcolor = xlines[0].get_color()\n data, col, _ = color.mpl_color2xcolor(data, xgridcolor)\n if col != \"black\":\n self.axis_options.append(\"x grid style={{{}}}\".format(col))\n\n if obj.yaxis._gridOnMajor:\n self.axis_options.append(\"ymajorgrids\")\n if obj.yaxis._gridOnMinor:\n self.axis_options.append(\"yminorgrids\")\n\n ylines = obj.get_ygridlines()\n if ylines:\n ygridcolor = ylines[0].get_color()\n data, col, _ = color.mpl_color2xcolor(data, ygridcolor)\n if col != \"black\":\n self.axis_options.append(\"y grid style={{{}}}\".format(col))\n\n return\n\n def _colorbar(self, colorbar, data):\n colorbar_styles = []\n\n orientation = colorbar.orientation\n limits = colorbar.get_clim()\n if orientation == \"horizontal\":\n self.axis_options.append(\"colorbar horizontal\")\n\n colorbar_ticks = colorbar.ax.get_xticks()\n colorbar_ticks_minor = colorbar.ax.get_xticks(\"minor\")\n axis_limits = colorbar.ax.get_xlim()\n\n # In matplotlib, the colorbar color limits are determined by\n # get_clim(), and the tick positions are as usual with respect\n # to {x,y}lim. In PGFPlots, however, they are mixed together.\n # Hence, scale the tick positions just like {x,y}lim are scaled\n # to clim.\n colorbar_ticks = (colorbar_ticks - axis_limits[0]) / (\n axis_limits[1] - axis_limits[0]\n ) * (limits[1] - limits[0]) + limits[0]\n colorbar_ticks_minor = (colorbar_ticks_minor - axis_limits[0]) / (\n axis_limits[1] - axis_limits[0]\n ) * (limits[1] - limits[0]) + limits[0]\n # Getting the labels via get_* might not actually be suitable:\n # they might not reflect the current state.\n colorbar_ticklabels = colorbar.ax.get_xticklabels()\n colorbar_ticklabels_minor = colorbar.ax.get_xticklabels(\"minor\")\n\n colorbar_styles.extend(\n _get_ticks(data, \"x\", colorbar_ticks, colorbar_ticklabels)\n )\n colorbar_styles.extend(\n _get_ticks(\n data, \"minor x\", colorbar_ticks_minor, colorbar_ticklabels_minor\n )\n )\n\n else:\n assert orientation == \"vertical\"\n\n self.axis_options.append(\"colorbar\")\n colorbar_ticks = colorbar.ax.get_yticks()\n colorbar_ticks_minor = colorbar.ax.get_yticks(\"minor\")\n axis_limits = colorbar.ax.get_ylim()\n\n # In matplotlib, the colorbar color limits are determined by\n # get_clim(), and the tick positions are as usual with respect\n # to {x,y}lim. In PGFPlots, however, they are mixed together.\n # Hence, scale the tick positions just like {x,y}lim are scaled\n # to clim.\n colorbar_ticks = (colorbar_ticks - axis_limits[0]) / (\n axis_limits[1] - axis_limits[0]\n ) * (limits[1] - limits[0]) + limits[0]\n colorbar_ticks_minor = (colorbar_ticks_minor - axis_limits[0]) / (\n axis_limits[1] - axis_limits[0]\n ) * (limits[1] - limits[0]) + limits[0]\n\n # Getting the labels via get_* might not actually be suitable:\n # they might not reflect the current state.\n colorbar_ticklabels = colorbar.ax.get_yticklabels()\n colorbar_ylabel = colorbar.ax.get_ylabel()\n colorbar_ticklabels_minor = colorbar.ax.get_yticklabels(\"minor\")\n colorbar_styles.extend(\n _get_ticks(data, \"y\", colorbar_ticks, colorbar_ticklabels)\n )\n colorbar_styles.extend(\n _get_ticks(\n data, \"minor y\", colorbar_ticks_minor, colorbar_ticklabels_minor\n )\n )\n colorbar_styles.append(\"ylabel={\" + colorbar_ylabel + \"}\")\n\n mycolormap, is_custom_cmap = _mpl_cmap2pgf_cmap(colorbar.get_cmap(), data)\n if is_custom_cmap:\n self.axis_options.append(\"colormap=\" + mycolormap)\n else:\n self.axis_options.append(\"colormap/\" + mycolormap)\n\n ff = data[\"float format\"]\n self.axis_options.append((\"point meta min=\" + ff).format(limits[0]))\n self.axis_options.append((\"point meta max=\" + ff).format(limits[1]))\n\n if colorbar_styles:\n self.axis_options.append(\n \"colorbar style={{{}}}\".format(\",\".join(colorbar_styles))\n )\n\n return\n\n def _subplot(self, obj, data):\n # https://github.com/matplotlib/matplotlib/issues/7225#issuecomment-252173667\n geom = obj.get_subplotspec().get_topmost_subplotspec().get_geometry()\n\n self.nsubplots = geom[0] * geom[1]\n if self.nsubplots > 1:\n # Is this an axis-colorbar pair? No need for groupplot then.\n is_groupplot = self.nsubplots != 2 or not _find_associated_colorbar(obj)\n\n if is_groupplot:\n self.is_subplot = True\n # subplotspec geometry positioning is 0-based\n self.subplot_index = geom[2] + 1\n if \"is_in_groupplot_env\" not in data or not data[\"is_in_groupplot_env\"]:\n self.content.append(\n \"\\\\begin{{groupplot}}[group style=\"\n \"{{group size={} by {}}}]\".format(geom[1], geom[0])\n )\n data[\"is_in_groupplot_env\"] = True\n data[\"pgfplots libs\"].add(\"groupplots\")\n\n return\n\n def _get_label_rotation_and_horizontal_alignment(self, obj, data, x_or_y):\n tick_label_text_width = None\n tick_label_text_width_identifier = \"{} tick label text width\".format(x_or_y)\n if tick_label_text_width_identifier in self.axis_options:\n self.axis_options.remove(tick_label_text_width_identifier)\n\n label_style = \"\"\n\n major_tick_labels = (\n obj.xaxis.get_majorticklabels()\n if x_or_y == \"x\"\n else obj.yaxis.get_majorticklabels()\n )\n\n if not major_tick_labels:\n return None\n\n tick_labels_rotation = [label.get_rotation() for label in major_tick_labels]\n tick_labels_rotation_same_value = len(set(tick_labels_rotation)) == 1\n\n tick_labels_horizontal_alignment = [\n label.get_horizontalalignment() for label in major_tick_labels\n ]\n tick_labels_horizontal_alignment_same_value = (\n len(set(tick_labels_horizontal_alignment)) == 1\n )\n\n if (\n tick_labels_rotation_same_value\n and tick_labels_horizontal_alignment_same_value\n ):\n values = []\n\n if any(tick_labels_rotation) != 0:\n values.append(\"rotate={}\".format(tick_labels_rotation[0]))\n\n # Horizontal alignment will be ignored if no 'x/y tick label text width' has\n # been passed in the 'extra' parameter\n if tick_label_text_width:\n values.append(\"align={}\".format(tick_labels_horizontal_alignment[0]))\n values.append(\"text width={}\".format(tick_label_text_width))\n\n if values:\n label_style = \"{}ticklabel style = {{{}}}\".format(\n x_or_y, \",\".join(values)\n )\n else:\n values = []\n\n if tick_labels_rotation_same_value:\n values.append(\"rotate={}\".format(tick_labels_rotation[0]))\n else:\n values.append(\n \"rotate={{{},0}}[\\\\ticknum]\".format(\n \",\".join(str(x) for x in tick_labels_rotation)\n )\n )\n\n # Ignore horizontal alignment if no '{x,y} tick label text width' has\n # been passed in the 'extra' parameter\n if tick_label_text_width:\n if tick_labels_horizontal_alignment_same_value:\n values.append(\n \"align={}\".format(tick_labels_horizontal_alignment[0])\n )\n values.append(\"text width={}\".format(tick_label_text_width))\n else:\n for idx, x in enumerate(tick_labels_horizontal_alignment):\n label_style += \"{}_tick_label_ha_{}/.initial = {}\".format(\n x_or_y, idx, x\n )\n\n values.append(\n \"align=\\\\pgfkeysvalueof{{/pgfplots/{}_tick_label_ha_\\\\ticknum}}\".format(\n x_or_y\n )\n )\n values.append(\"text width={}\".format(tick_label_text_width))\n\n label_style = (\n \"every {} tick label/.style = {{\\n\"\n \"{}\\n\"\n \"}}\".format(x_or_y, \",\\n\".join(values))\n )\n\n return label_style\n\n\ndef _get_tick_position(obj, axes_obj):\n major_ticks = obj.xaxis.majorTicks if axes_obj == \"x\" else obj.yaxis.majorTicks\n\n major_ticks_bottom = [tick.tick1line.get_visible() for tick in major_ticks]\n major_ticks_top = [tick.tick2line.get_visible() for tick in major_ticks]\n\n major_ticks_bottom_show_all = False\n if len(set(major_ticks_bottom)) == 1 and major_ticks_bottom[0] is True:\n major_ticks_bottom_show_all = True\n\n major_ticks_top_show_all = False\n if len(set(major_ticks_top)) == 1 and major_ticks_top[0] is True:\n major_ticks_top_show_all = True\n\n major_ticks_position = None\n if not major_ticks_bottom_show_all and not major_ticks_top_show_all:\n position_string = \"{}majorticks=false\".format(axes_obj)\n elif major_ticks_bottom_show_all and major_ticks_top_show_all:\n major_ticks_position = \"both\"\n elif major_ticks_bottom_show_all:\n major_ticks_position = \"left\"\n elif major_ticks_top_show_all:\n major_ticks_position = \"right\"\n\n if major_ticks_position:\n position_string = \"{}tick pos={}\".format(axes_obj, major_ticks_position)\n\n return position_string, major_ticks_position\n\n\ndef _get_ticks(data, xy, ticks, ticklabels):\n \"\"\"Gets a {'x','y'}, a number of ticks and ticks labels, and returns the\n necessary axis options for the given configuration.\n \"\"\"\n axis_options = []\n pgfplots_ticks = []\n pgfplots_ticklabels = []\n is_label_required = False\n for tick, ticklabel in zip(ticks, ticklabels):\n pgfplots_ticks.append(tick)\n # store the label anyway\n label = ticklabel.get_text()\n if ticklabel.get_visible():\n label = mpl_backend_pgf.common_texification(label)\n pgfplots_ticklabels.append(label)\n else:\n is_label_required = True\n # Check if the label is necessary. If one of the labels is, then all of them\n # must appear in the TikZ plot.\n if label:\n try:\n label_float = float(label.replace(u\"\\N{MINUS SIGN}\", \"-\"))\n is_label_required = is_label_required or (label and label_float != tick)\n except ValueError:\n is_label_required = True\n\n # Leave the ticks to PGFPlots if not in STRICT mode and if there are no explicit\n # labels.\n if data[\"strict\"] or is_label_required:\n if pgfplots_ticks:\n ff = data[\"float format\"]\n axis_options.append(\n \"{}tick={{{}}}\".format(\n xy, \",\".join([ff.format(el) for el in pgfplots_ticks])\n )\n )\n else:\n val = \"{}\" if \"minor\" in xy else \"\\\\empty\"\n axis_options.append(\"{}tick={}\".format(xy, val))\n\n if is_label_required:\n axis_options.append(\n \"{}ticklabels={{{}}}\".format(xy, \",\".join(pgfplots_ticklabels))\n )\n return axis_options\n\n\ndef _is_colorbar_heuristic(obj):\n \"\"\"Find out if the object is in fact a color bar.\n \"\"\"\n # TODO come up with something more accurate here\n # Might help:\n # TODO Are the colorbars exactly the l.collections.PolyCollection's?\n try:\n aspect = float(obj.get_aspect())\n except ValueError:\n # e.g., aspect == 'equal'\n return False\n\n # Assume that something is a colorbar if and only if the ratio is above 5.0\n # and there are no ticks on the corresponding axis. This isn't always true,\n # though: The ratio of a color can be freely adjusted by the aspect\n # keyword, e.g.,\n #\n # plt.colorbar(im, aspect=5)\n #\n limit_ratio = 5.0\n\n return (aspect >= limit_ratio and len(obj.get_xticks()) == 0) or (\n aspect <= 1.0 / limit_ratio and len(obj.get_yticks()) == 0\n )\n\n\ndef _mpl_cmap2pgf_cmap(cmap, data):\n \"\"\"Converts a color map as given in matplotlib to a color map as\n represented in PGFPlots.\n \"\"\"\n if isinstance(cmap, mpl.colors.LinearSegmentedColormap):\n return _handle_linear_segmented_color_map(cmap, data)\n\n assert isinstance(\n cmap, mpl.colors.ListedColormap\n ), \"Only LinearSegmentedColormap and ListedColormap are supported\"\n return _handle_listed_color_map(cmap, data)\n\n\ndef _handle_linear_segmented_color_map(cmap, data):\n assert isinstance(cmap, mpl.colors.LinearSegmentedColormap)\n\n if cmap.is_gray():\n is_custom_colormap = False\n return (\"blackwhite\", is_custom_colormap)\n\n # For an explanation of what _segmentdata contains, see\n # http://matplotlib.org/mpl_examples/pylab_examples/custom_cmap.py\n # A key sentence:\n # If there are discontinuities, then it is a little more complicated. Label the 3\n # elements in each row in the cdict entry for a given color as (x, y0, y1). Then\n # for values of x between x[i] and x[i+1] the color value is interpolated between\n # y1[i] and y0[i+1].\n segdata = cmap._segmentdata\n red = segdata[\"red\"]\n green = segdata[\"green\"]\n blue = segdata[\"blue\"]\n\n # Loop over the data, stop at each spot where the linear interpolations is\n # interrupted, and set a color mark there.\n #\n # Set initial color.\n k_red = 0\n k_green = 0\n k_blue = 0\n x = 0.0\n colors = []\n X = []\n while True:\n # find next x\n x = min(red[k_red][0], green[k_green][0], blue[k_blue][0])\n\n if red[k_red][0] == x:\n red_comp = red[k_red][1]\n k_red += 1\n else:\n red_comp = _linear_interpolation(\n x,\n (red[k_red - 1][0], red[k_red][0]),\n (red[k_red - 1][2], red[k_red][1]),\n )\n\n if green[k_green][0] == x:\n green_comp = green[k_green][1]\n k_green += 1\n else:\n green_comp = _linear_interpolation(\n x,\n (green[k_green - 1][0], green[k_green][0]),\n (green[k_green - 1][2], green[k_green][1]),\n )\n\n if blue[k_blue][0] == x:\n blue_comp = blue[k_blue][1]\n k_blue += 1\n else:\n blue_comp = _linear_interpolation(\n x,\n (blue[k_blue - 1][0], blue[k_blue][0]),\n (blue[k_blue - 1][2], blue[k_blue][1]),\n )\n\n X.append(x)\n colors.append((red_comp, green_comp, blue_comp))\n\n if x >= 1.0:\n break\n\n # The PGFPlots color map has an actual physical scale, like (0cm,10cm), and the\n # points where the colors change is also given in those units. As of now\n # (2010-05-06) it is crucial for PGFPlots that the difference between two successive\n # points is an integer multiple of a given unity (parameter to the colormap; e.g.,\n # 1cm). At the same time, TeX suffers from significant round-off errors, so make\n # sure that this unit is not too small such that the round- off errors don't play\n # much of a role. A unit of 1pt, e.g., does most often not work.\n unit = \"pt\"\n\n # Scale to integer (too high integers will firstly be slow and secondly may produce\n # dimension errors or memory errors in latex)\n # 0-1000 is the internal granularity of PGFplots.\n # 16300 was the maximum value for pgfplots<=1.13\n X = _scale_to_int(numpy.array(X), 1000)\n\n color_changes = []\n ff = data[\"float format\"]\n for (k, x) in enumerate(X):\n color_changes.append(\n (\"rgb({}{})=(\" + ff + \",\" + ff + \",\" + ff + \")\").format(\n *((x, unit) + colors[k])\n )\n )\n\n colormap_string = \"{{mymap}}{{[1{}]\\n {}\\n}}\".format(\n unit, \";\\n \".join(color_changes)\n )\n is_custom_colormap = True\n return (colormap_string, is_custom_colormap)\n\n\ndef _handle_listed_color_map(cmap, data):\n assert isinstance(cmap, mpl.colors.ListedColormap)\n\n # check for predefined colormaps in both matplotlib and pgfplots\n from matplotlib import pyplot as plt\n\n cm_translate = {\n # All the rest are LinearSegmentedColorMaps. :/\n # 'autumn': 'autumn',\n # 'cool': 'cool',\n # 'copper': 'copper',\n # 'gray': 'blackwhite',\n # 'hot': 'hot2',\n # 'hsv': 'hsv',\n # 'jet': 'jet',\n # 'spring': 'spring',\n # 'summer': 'summer',\n \"viridis\": \"viridis\",\n # 'winter': 'winter',\n }\n for mpl_cm, pgf_cm in cm_translate.items():\n if cmap.colors == plt.get_cmap(mpl_cm).colors:\n is_custom_colormap = False\n return (pgf_cm, is_custom_colormap)\n\n unit = \"pt\"\n ff = data[\"float format\"]\n if cmap.N is None or cmap.N == len(cmap.colors):\n colors = [\n (\"rgb({}{})=(\" + ff + \",\" + ff + \",\" + ff + \")\").format(\n k, unit, rgb[0], rgb[1], rgb[2]\n )\n for (k, rgb) in enumerate(cmap.colors)\n ]\n else:\n reps = int(float(cmap.N) / len(cmap.colors) - 0.5) + 1\n repeated_cols = reps * cmap.colors\n colors = [\n (\"rgb({}{})=(\" + ff + \",\" + ff + \",\" + ff + \")\").format(\n k, unit, rgb[0], rgb[1], rgb[2]\n )\n for (k, rgb) in enumerate(repeated_cols[: cmap.N])\n ]\n\n colormap_string = \"{mymap}{[1{}]\\n {}\\n}\".format(unit, \";\\n \".join(colors))\n is_custom_colormap = True\n return (colormap_string, is_custom_colormap)\n\n\ndef _scale_to_int(X, max_val):\n \"\"\"Scales the array X such that it contains only integers.\n \"\"\"\n # if max_val is None:\n # X = X / _gcd_array(X)\n X = X / max(1 / max_val, _gcd_array(X))\n return [int(entry) for entry in X]\n\n\ndef _gcd_array(X):\n \"\"\"\n Return the largest real value h such that all elements in x are integer\n multiples of h.\n \"\"\"\n greatest_common_divisor = 0.0\n for x in X:\n greatest_common_divisor = _gcd(greatest_common_divisor, x)\n\n return greatest_common_divisor\n\n\ndef _gcd(a, b):\n \"\"\"Euclidean algorithm for calculating the GCD of two numbers a, b.\n This algoritm also works for real numbers:\n Find the greatest number h such that a and b are integer multiples of h.\n \"\"\"\n # Keep the tolerance somewhat significantly above machine precision as\n # otherwise round-off errors will be accounted for, returning 1.0e-10\n # instead of 1.0 for the values\n # [1.0, 2.0000000001, 3.0, 4.0].\n while a > 1.0e-5:\n a, b = b % a, a\n return b\n\n\ndef _linear_interpolation(x, X, Y):\n \"\"\"Given two data points [X,Y], linearly interpolate those at x.\n \"\"\"\n return (Y[1] * (x - X[0]) + Y[0] * (X[1] - x)) / (X[1] - X[0])\n\n\ndef _find_associated_colorbar(obj):\n \"\"\"A rather poor way of telling whether an axis has a colorbar associated:\n Check the next axis environment, and see if it is de facto a color bar;\n if yes, return the color bar object.\n \"\"\"\n for child in obj.get_children():\n try:\n cbar = child.colorbar\n except AttributeError:\n continue\n if cbar is not None: # really necessary?\n # if fetch was successful, cbar contains\n # (reference to colorbar,\n # reference to axis containing colorbar)\n return cbar\n return None\n\n\ndef _try_f2i(x):\n \"\"\"Convert losslessly float to int if possible.\n Used for log base: if not used, base for log scale can be \"10.0\" (and then\n printed as such by pgfplots).\n \"\"\"\n return int(x) if int(x) == x else x\n"
] |
[
[
"matplotlib.backends.backend_pgf.common_texification",
"numpy.array",
"matplotlib.pyplot.get_cmap"
]
] |
delldu/ImagePatch
|
[
"aaeadba9fe9f40e9bf900468f100a06bafc8231f"
] |
[
"train.py"
] |
[
"import os\nimport math\nimport argparse\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nimport torch.backends.cudnn as cudnn\nfrom PIL import Image\nfrom torch.autograd import Variable\nfrom torchvision.utils import save_image\nfrom torchvision import datasets\nfrom torch.utils.data import DataLoader\nfrom torchvision import utils\nfrom data.dataloader import GetData\nfrom loss.InpaintingLoss import InpaintingLossWithGAN\nfrom models.LBAMModel import LBAMModel, VGG16FeatureExtractor\n\nimport pdb\n\ntorch.set_num_threads(5)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--numOfWorkers', type=int, default=4,\n help='workers for dataloader')\nparser.add_argument('--modelsSavePath', type=str, default='',\n help='path for saving models')\nparser.add_argument('--logPath', type=str,\n default='')\nparser.add_argument('--batchSize', type=int, default=16)\nparser.add_argument('--loadSize', type=int, default=350,\n help='image loading size')\nparser.add_argument('--cropSize', type=int, default=256,\n help='image training size')\nparser.add_argument('--dataRoot', type=str,\n default='')\nparser.add_argument('--maskRoot', type=str,\n default='')\nparser.add_argument('--pretrained',type=str, default='', help='pretrained models for finetuning')\nparser.add_argument('--train_epochs', type=int, default=500, help='training epochs')\nargs = parser.parse_args()\n\npdb.set_trace()\n\ncuda = torch.cuda.is_available()\nif cuda:\n print('Cuda is available!')\n cudnn.enable = True\n cudnn.benchmark = True\n\n\nbatchSize = args.batchSize\nloadSize = (args.loadSize, args.loadSize)\ncropSize = (args.cropSize, args.cropSize)\n\nif not os.path.exists(args.modelsSavePath):\n os.makedirs(args.modelsSavePath)\n\ndataRoot = args.dataRoot\nmaskRoot = args.maskRoot\n\n\nimgData = GetData(dataRoot, maskRoot, loadSize, cropSize)\ndata_loader = DataLoader(imgData, batch_size=batchSize, \n shuffle=True, num_workers=args.numOfWorkers, drop_last=False, pin_memory=True)\n\nnum_epochs = args.train_epochs\n\n# pdb.set_trace()\n\nnetG = LBAMModel(4, 3)\nif args.pretrained != '':\n netG.load_state_dict(torch.load(args.pretrained))\n\n# pdb.set_trace()\n\n\nnumOfGPUs = torch.cuda.device_count()\n\nif cuda:\n netG = netG.cuda()\n if numOfGPUs > 1:\n netG = nn.DataParallel(netG, device_ids=range(numOfGPUs))\n\ncount = 1\n\n\nG_optimizer = optim.Adam(netG.parameters(), lr=0.0001, betas=(0.5, 0.9))\n\n\ncriterion = InpaintingLossWithGAN(lr=0.00001, betasInit=(0.0, 0.9))\n\n# pdb.set_trace()\n\n\nif cuda:\n criterion = criterion.cuda()\n\n if numOfGPUs > 1:\n criterion = nn.DataParallel(criterion, device_ids=range(numOfGPUs))\n\nprint('OK!')\n\n# pdb.set_trace()\n\nfor i in range(1, num_epochs + 1):\n netG.train()\n\n for inputImgs, GT, masks in (data_loader):\n\n if cuda:\n inputImgs = inputImgs.cuda()\n GT = GT.cuda()\n masks = masks.cuda()\n\n netG.zero_grad()\n\n fake_images = netG(inputImgs, masks)\n G_loss = criterion(inputImgs[:, 0:3, :, :], masks, fake_images, GT)\n G_loss = G_loss.sum()\n G_optimizer.zero_grad()\n G_loss.backward()\n G_optimizer.step()\n\n print('Generator Loss of epoch{} is {}'.format(i, G_loss.item()))\n\n count += 1\n\n \"\"\" if (count % 4000 == 0):\n torch.save(netG.module.state_dict(), args.modelsSavePath +\n '/Places_{}.pth'.format(i)) \"\"\"\n \n if ( i % 10 == 0):\n if numOfGPUs > 1 :\n torch.save(netG.module.state_dict(), args.modelsSavePath +\n '/LBAM_{}.pth'.format(i))\n else:\n torch.save(netG.state_dict(), args.modelsSavePath +\n '/LBAM_{}.pth'.format(i))\n"
] |
[
[
"torch.load",
"torch.utils.data.DataLoader",
"torch.set_num_threads",
"torch.cuda.is_available",
"torch.cuda.device_count"
]
] |
hooloong/aliyunProblems
|
[
"077d115535fe54e47e59a0d96676b3995bbda75e"
] |
[
"freshman01/taobao_finduser.py"
] |
[
"import os\nimport random\nimport tensorflow as tf\nimport pandas as pd\nimport numpy as np\nfrom sklearn.preprocessing import scale # 使用scikit-learn进行数据预处理\n\nuser_data_file = \"../../data/fresh_comp_offline/tianchi_fresh_comp_train_user.csv\"\ngoods_data_file = \"../../data/fresh_comp_offline/tianchi_fresh_comp_train_item.csv\"\n\nuser_data = pd.read_csv(user_data_file, header=0)\ngoods_data = pd.read_csv(goods_data_file, header=0)\ngoods_data.to_csv(\"./items.csv\",index=False,index_label=False, columns=[\"item_id\"],)\n# train_goods = scale(np.asarray(goods_data.ix[:, 2]))\n# train_user_data = scale(np.asarray(goods_data.ix[:, 2]))\n# print(train_user_data)"
] |
[
[
"pandas.read_csv"
]
] |
Jarvis73/SubKmeans-Python
|
[
"71c30c5722df9f043e4d90845bbaa30c6017403e"
] |
[
"src/utils/DataIO.py"
] |
[
"import numpy as np\nfrom pathlib import Path\n\n\ndef writeClusters(f: Path, data: np.ndarray, labels: np.ndarray, separator=\";\"):\n with f.open(\"w\") as fid:\n for dp, label in zip(data, labels):\n lineData = np.array2string(dp, separator=separator, max_line_width=0x80000000)[1:-1]\n fid.write(f\"{label}{separator}{lineData}\\n\")\n\n\ndef loadCsvWithIntLabelsAsSeq(f: Path, labelOnFirst=True, separator=\";\"):\n dpSeq = []\n labelSeq = []\n\n with f.open() as fid:\n for l in fid.readlines():\n if l.isspace():\n continue\n parts = l.strip().replace(\"\\n\", \"\").split(separator)\n if labelOnFirst:\n try:\n labelSeq.append(int(float(parts[0])))\n dpSeq.append([float(x) for x in parts[1:]])\n except ValueError:\n print(parts)\n else:\n labelSeq.append(int(parts[-1]))\n dpSeq.append([float(x) for x in parts[:-1]])\n\n return np.array(dpSeq), np.array(labelSeq)\n"
] |
[
[
"numpy.array2string",
"numpy.array"
]
] |
wyzks123/Udacity-P4-BehavioralCloning
|
[
"462494630ce4d4a4a9242c2b72e24f30f6d8fb2b"
] |
[
"model.py"
] |
[
"# CarND-Behavioral-Cloning-P3\nimport os\nimport csv\nimport math \n\n###read driving img paths and mearsurements\nsamples = []\nwith open('../data/driving_log.csv') as csvfile:\n reader = csv.reader(csvfile)\n next(reader)\n for line in reader:\n samples.append(line)\nprint('total number of samples',len(samples))\n### split the samples\nfrom sklearn.model_selection import train_test_split\ntrain_samples, validation_samples = train_test_split(samples, test_size=0.2)\n\nimport cv2\nimport numpy as np\nimport sklearn\nfrom sklearn.utils import shuffle\nimport random\n\n### Generate random brightness function, produce darker transformation \ndef random_brightness(image):\n #Convert 2 HSV colorspace from RGB colorspace\n hsv = cv2.cvtColor(image, cv2.COLOR_RGB2HSV)\n #Generate new random brightness\n rand = random.uniform(0.3,1.0)\n hsv[:,:,2] = rand*hsv[:,:,2]\n #Convert back to RGB colorspace\n new_img = cv2.cvtColor(hsv, cv2.COLOR_HSV2RGB)\n return new_img \n\n### Crop image to remove the sky and driving deck, resize to 64x64 dimension (tried a version without resizing but not good. not sure what's the reason)\ndef crop_resize(image):\n cropped = cv2.resize(image[60:140,:], (64,64))\n return cropped\n\n### use generator to save memory and create trainng and validation data\ndef generator(samples, batch_size=32,correction=0.3):\n num_samples = len(samples)\n while 1: # Loop forever so the generator never terminates\n shuffle(samples)\n for offset in range(0, num_samples, batch_size):\n batch_samples = samples[offset:offset+batch_size]\n \n images = []\n angles = []\n augmented_images, augmented_angles = [],[]\n for batch_sample in batch_samples:\n center_name = '../data/IMG/'+batch_sample[0].split('/')[-1]\n left_name = '../data/IMG/'+batch_sample[1].split('/')[-1]\n right_name = '../data/IMG/'+batch_sample[2].split('/')[-1]\n# print('center_name',center_name)\n ### augment, crop and resize the image inputs\n center_image = crop_resize(random_brightness(cv2.imread(center_name)))\n left_image = crop_resize(random_brightness(cv2.imread(left_name)))\n right_image = crop_resize(random_brightness(cv2.imread(right_name)))\n# center_image = cv2.imread(center_name)\n# left_image = cv2.imread(left_name)\n# right_image = cv2.imread(right_name)\n center_angle = float(batch_sample[3])\n left_angle = center_angle + correction\n right_angle = center_angle - correction \n \n \n images.append(center_image) \n images.append(left_image)\n images.append(right_image)\n angles.append(center_angle)\n angles.append(left_angle)\n angles.append(right_angle)\n\n ### flip the img on vertical axis \n for image,angle in zip(images,angles):\n augmented_images.append(image)\n augmented_angles.append(angle)\n augmented_images.append(cv2.flip(image,1))\n augmented_angles.append(angle*-1.0)\n\n X_train = np.array(augmented_images)\n y_train = np.array(augmented_angles)\n yield sklearn.utils.shuffle(X_train, y_train)\n\n\n# Set our batch size\nbatch_size=64\n\n# compile and train the model using the generator function\ntrain_generator = generator(train_samples, batch_size=batch_size)\nvalidation_generator = generator(validation_samples, batch_size=batch_size)\n\n\nfrom keras.models import Sequential, Model\nfrom keras.layers import Dense, Flatten, Lambda, Activation, MaxPooling2D, Dropout, Cropping2D\nfrom keras.layers import Convolution2D\nfrom keras.regularizers import l2\n\n#NVIDIA architecture\ninput_shape = (64,64,3)\n\nmodel = Sequential()\nmodel.add(Lambda(lambda x: x/172.5- 1, input_shape=input_shape)) #nomalize the data\nmodel.add(Convolution2D(24, 5, 5, border_mode='valid', subsample =(2,2), W_regularizer = l2(0.001)))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(36, 5, 5, border_mode='valid', subsample =(2,2), W_regularizer = l2(0.001)))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(48, 5, 5, border_mode='valid', subsample = (2,2), W_regularizer = l2(0.001)))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(64, 3, 3, border_mode='same', subsample = (2,2), W_regularizer = l2(0.001)))\nmodel.add(Activation('relu'))\nmodel.add(Convolution2D(64, 3, 3, border_mode='valid', subsample = (2,2), W_regularizer = l2(0.001)))\nmodel.add(Activation('relu'))\nmodel.add(Flatten())\nmodel.add(Dense(80, W_regularizer = l2(0.001)))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(40, W_regularizer = l2(0.001)))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(16, W_regularizer = l2(0.001)))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(10, W_regularizer = l2(0.001)))\nmodel.add(Dense(1, W_regularizer = l2(0.001)))\nmodel.summary()\n\n\nmodel.compile(loss='mse',optimizer='adam')\n# model.fit(X_train,y_train,validation_split=0.2,shuffle=True,nb_epoch=5)\nhistory_object = model.fit_generator(train_generator,\n steps_per_epoch=math.ceil(len(train_samples)/batch_size), \n validation_data=validation_generator, \n validation_steps=math.ceil(len(validation_samples)/batch_size), \n epochs=3, verbose=1)\n\nmodel.save('model.h5')\nprint('Congrats! Model saved')\n\n### print the keys contained in the history object\nprint(history_object.history.keys())\nimport matplotlib.pyplot as plt\n### plot the training and validation loss for each epoch\nplt.plot(history_object.history['loss'])\nplt.plot(history_object.history['val_loss'])\nplt.title('model mean squared error loss')\nplt.ylabel('mean squared error loss')\nplt.xlabel('epoch')\nplt.legend(['training set', 'validation set'], loc='upper right')\nplt.savefig('learning.png')\nexit()\n "
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.title",
"sklearn.utils.shuffle",
"sklearn.model_selection.train_test_split",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.ylabel"
]
] |
ZhaoJ9014/five-video-classification-methods
|
[
"1d5e2c5be9d8e80919dc5c0ae45ed2b35e0b87e6"
] |
[
"data.py"
] |
[
"\"\"\"\nClass for managing our data.\n\"\"\"\nimport csv\nimport numpy as np\nimport random\nimport glob\nimport os.path\nimport pandas as pd\nimport sys\nimport operator\nfrom processor import process_image\nfrom keras.utils import np_utils\n\nclass DataSet():\n\n def __init__(self, seq_length=40, class_limit=None, image_shape=(224, 224, 3)):\n \"\"\"Constructor.\n seq_length = (int) the number of frames to consider\n class_limit = (int) number of classes to limit the data to.\n None = no limit.\n \"\"\"\n self.seq_length = seq_length\n self.class_limit = class_limit\n self.sequence_path = './data/sequences/'\n self.max_frames = 300 # max number of frames a video can have for us to use it\n\n # Get the data.\n self.data = self.get_data()\n\n # Get the classes.\n self.classes = self.get_classes()\n\n # Now do some minor data cleaning.\n self.data = self.clean_data()\n\n self.image_shape = image_shape\n\n @staticmethod\n def get_data():\n \"\"\"Load our data from file.\"\"\"\n with open('./data/data_file.csv', 'r') as fin:\n reader = csv.reader(fin)\n data = list(reader)\n\n return data\n\n def clean_data(self):\n \"\"\"Limit samples to greater than the sequence length and fewer\n than N frames. Also limit it to classes we want to use.\"\"\"\n data_clean = []\n for item in self.data:\n if int(item[3]) >= self.seq_length and int(item[3]) <= self.max_frames \\\n and item[1] in self.classes:\n data_clean.append(item)\n\n return data_clean\n\n def get_classes(self):\n \"\"\"Extract the classes from our data. If we want to limit them,\n only return the classes we need.\"\"\"\n classes = []\n for item in self.data:\n if item[1] not in classes:\n classes.append(item[1])\n\n # Sort them.\n classes = sorted(classes)\n\n # Return.\n if self.class_limit is not None:\n return classes[:self.class_limit]\n else:\n return classes\n\n def get_class_one_hot(self, class_str):\n \"\"\"Given a class as a string, return its number in the classes\n list. This lets us encode and one-hot it for training.\"\"\"\n # Encode it first.\n label_encoded = self.classes.index(class_str)\n\n # Now one-hot it.\n label_hot = np_utils.to_categorical(label_encoded, len(self.classes))\n label_hot = label_hot[0] # just get a single row\n\n return label_hot\n\n def split_train_test(self):\n \"\"\"Split the data into train and test groups.\"\"\"\n train = []\n test = []\n for item in self.data:\n if item[0] == 'train':\n train.append(item)\n else:\n test.append(item)\n return train, test\n\n def get_all_sequences_in_memory(self, batch_Size, train_test, data_type, concat=False):\n \"\"\"\n This is a mirror of our generator, but attempts to load everything into\n memory so we can train way faster.\n \"\"\"\n # Get the right dataset.\n train, test = self.split_train_test()\n data = train if train_test == 'train' else test\n\n print(\"Getting %s data with %d samples.\" % (train_test, len(data)))\n\n X, y = [], []\n for row in data:\n\n sequence = self.get_extracted_sequence(data_type, row)\n\n if sequence is None:\n print(\"Can't find sequence. Did you generate them?\")\n raise\n\n if concat:\n # We want to pass the sequence back as a single array. This\n # is used to pass into a CNN or MLP, rather than an RNN.\n sequence = np.concatenate(sequence).ravel()\n\n X.append(sequence)\n y.append(self.get_class_one_hot(row[1]))\n\n return np.array(X), np.array(y)\n\n def frame_generator(self, batch_size, train_test, data_type, concat=False):\n \"\"\"Return a generator that we can use to train on. There are\n a couple different things we can return:\n\n data_type: 'features', 'images'\n \"\"\"\n # Get the right dataset for the generator.\n train, test = self.split_train_test()\n data = train if train_test == 'train' else test\n\n print(\"Creating %s generator with %d samples.\" % (train_test, len(data)))\n\n while 1:\n X, y = [], []\n\n # Generate batch_size samples.\n for _ in range(batch_size):\n # Reset to be safe.\n sequence = None\n\n # Get a random sample.\n sample = random.choice(data)\n\n # Check to see if we've already saved this sequence.\n if data_type is \"images\":\n # Get and resample frames.\n frames = self.get_frames_for_sample(sample)\n frames = self.rescale_list(frames, self.seq_length)\n\n # Build the image sequence\n sequence = self.build_image_sequence(frames)\n else:\n # Get the sequence from disk.\n sequence = self.get_extracted_sequence(sample)\n\n if sequence is None:\n print(\"Can't find sequence. Did you generate them?\")\n sys.exit() # TODO this should raise\n\n if concat:\n # We want to pass the sequence back as a single array. This\n # is used to pass into an MLP rather than an RNN.\n sequence = np.concatenate(sequence).ravel()\n\n X.append(sequence)\n y.append(self.get_class_one_hot(sample[1]))\n\n yield np.array(X), np.array(y)\n\n def build_image_sequence(self, frames):\n \"\"\"Given a set of frames (filenames), build our sequence.\"\"\"\n return [process_image(x, self.image_shape) for x in frames]\n\n def get_extracted_sequence(self, sample):\n \"\"\"Get the saved extracted features.\"\"\"\n filename = sample[2]\n path = self.sequence_path + filename + '-' + str(self.seq_length) + \\\n '-features.txt'\n if os.path.isfile(path):\n # Use a dataframe/read_csv for speed increase over numpy.\n features = pd.read_csv(path, sep=\" \", header=None)\n return features.values\n else:\n return None\n\n @staticmethod\n def get_frames_for_sample(sample):\n \"\"\"Given a sample row from the data file, get all the corresponding frame\n filenames.\"\"\"\n path = './data/' + sample[0] + '/' + sample[1] + '/'\n filename = sample[2]\n images = sorted(glob.glob(path + filename + '*jpg'))\n return images\n\n @staticmethod\n def get_filename_from_image(filename):\n parts = filename.split('/')\n return parts[-1].replace('.jpg', '')\n\n @staticmethod\n def rescale_list(input_list, size):\n \"\"\"Given a list and a size, return a rescaled/samples list. For example,\n if we want a list of size 5 and we have a list of size 25, return a new\n list of size five which is every 5th element of the origina list.\"\"\"\n assert len(input_list) >= size\n\n # Get the number to skip between iterations.\n skip = len(input_list) // size\n\n # Build our new output.\n output = [input_list[i] for i in range(0, len(input_list), skip)]\n\n # Cut off the last one if needed.\n return output[:size]\n\n @staticmethod\n def print_class_from_prediction(predictions, nb_to_return=5):\n \"\"\"Given a prediction, print the top classes.\"\"\"\n # Get the prediction for each label.\n label_predictions = {}\n for i, label in enumerate(data.classes):\n label_predictions[label] = predictions[i]\n\n # Now sort them.\n sorted_lps = sorted(\n label_predictions.items(),\n key=operator.itemgetter(1),\n reverse=True\n )\n\n # And return the top N.\n for i, class_prediction in enumerate(sorted_lps):\n if i > nb_to_return - 1 or class_prediction[1] == 0.0:\n break\n print(\"%s: %.2f\" % (class_prediction[0], class_prediction[1]))\n"
] |
[
[
"numpy.concatenate",
"numpy.array",
"pandas.read_csv"
]
] |
benSepanski/loopy
|
[
"5db582d579eb65ce58b93e2c53feb1d48404cf2d"
] |
[
"test/test_callables.py"
] |
[
"from __future__ import division, absolute_import, print_function\n\n__copyright__ = \"Copyright (C) 2018 Kaushik Kulkarni\"\n\n__license__ = \"\"\"\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in\nall copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\nTHE SOFTWARE.\n\"\"\"\n\nimport numpy as np\nimport pyopencl as cl\nimport pyopencl.clrandom # noqa: F401\nimport loopy as lp\nimport pytest\nimport sys\n\n\nfrom pyopencl.tools import ( # noqa: F401\n pytest_generate_tests_for_pyopencl\n as pytest_generate_tests)\n\nfrom loopy.version import LOOPY_USE_LANGUAGE_VERSION_2018_2 # noqa: F401\n\n\ndef test_register_function_lookup(ctx_factory):\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n\n from testlib import register_log2_lookup\n\n x = np.random.rand(10)\n ctx = cl.create_some_context()\n queue = cl.CommandQueue(ctx)\n\n prog = lp.make_kernel(\n \"{[i]: 0<=i<10}\",\n \"\"\"\n y[i] = log2(x[i])\n \"\"\")\n prog = lp.register_function_id_to_in_knl_callable_mapper(prog,\n register_log2_lookup)\n\n evt, (out, ) = prog(queue, x=x)\n\n assert np.linalg.norm(np.log2(x)-out)/np.linalg.norm(np.log2(x)) < 1e-15\n\n\[email protected](\"inline\", [False, True])\ndef test_register_knl(ctx_factory, inline):\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n n = 2 ** 4\n\n x = np.random.rand(n, n, n, n, n)\n y = np.random.rand(n, n, n, n, n)\n\n grandchild_knl = lp.make_function(\n \"{[i, j]:0<= i, j< 16}\",\n \"\"\"\n c[i, j] = 2*a[i, j] + 3*b[i, j]\n \"\"\", name='linear_combo1')\n\n child_knl = lp.make_function(\n \"{[i, j]:0<=i, j < 16}\",\n \"\"\"\n [i, j]: g[i, j] = linear_combo1([i, j]: e[i, j], [i, j]: f[i, j])\n \"\"\", name='linear_combo2')\n\n parent_knl = lp.make_kernel(\n \"{[i, j, k, l, m]: 0<=i, j, k, l, m<16}\",\n \"\"\"\n [j, l]: z[i, j, k, l, m] = linear_combo2([j, l]: x[i, j, k, l, m],\n [j, l]: y[i, j, k, l, m])\n \"\"\",\n kernel_data=[\n lp.GlobalArg(\n name='x',\n dtype=np.float64,\n shape=(16, 16, 16, 16, 16)),\n lp.GlobalArg(\n name='y',\n dtype=np.float64,\n shape=(16, 16, 16, 16, 16)), '...'],\n )\n\n knl = lp.register_callable_kernel(\n parent_knl, child_knl)\n knl = lp.register_callable_kernel(\n knl, grandchild_knl)\n if inline:\n knl = lp.inline_callable_kernel(knl, 'linear_combo2')\n knl = lp.inline_callable_kernel(knl, 'linear_combo1')\n\n evt, (out, ) = knl(queue, x=x, y=y)\n\n assert (np.linalg.norm(2*x+3*y-out)/(\n np.linalg.norm(2*x+3*y))) < 1e-15\n\n\[email protected](\"inline\", [False, True])\ndef test_slices_with_negative_step(ctx_factory, inline):\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n n = 2 ** 4\n\n x = np.random.rand(n, n, n, n, n)\n y = np.random.rand(n, n, n, n, n)\n\n child_knl = lp.make_function(\n \"{[i, j]:0<=i, j < 16}\",\n \"\"\"\n g[i, j] = 2*e[i, j] + 3*f[i, j]\n \"\"\", name=\"linear_combo\")\n\n parent_knl = lp.make_kernel(\n \"{[i, k, m]: 0<=i, k, m<16}\",\n \"\"\"\n z[i, 15:-1:-1, k, :, m] = linear_combo(x[i, :, k, :, m],\n y[i, :, k, :, m])\n \"\"\",\n kernel_data=[\n lp.GlobalArg(\n name='x',\n dtype=np.float64,\n shape=(16, 16, 16, 16, 16)),\n lp.GlobalArg(\n name='y',\n dtype=np.float64,\n shape=(16, 16, 16, 16, 16)),\n lp.GlobalArg(\n name='z',\n dtype=np.float64,\n shape=(16, 16, 16, 16, 16)), '...'],\n )\n\n knl = lp.register_callable_kernel(\n parent_knl, child_knl)\n if inline:\n knl = lp.inline_callable_kernel(knl, 'linear_combo')\n\n evt, (out, ) = knl(queue, x=x, y=y)\n\n assert (np.linalg.norm(2*x+3*y-out[:, ::-1, :, :, :])/(\n np.linalg.norm(2*x+3*y))) < 1e-15\n\n\[email protected](\"inline\", [False, True])\ndef test_register_knl_with_call_with_kwargs(ctx_factory, inline):\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n\n n = 2 ** 2\n\n a_dev = cl.clrandom.rand(queue, (n, n, n, n, n), np.float32)\n b_dev = cl.clrandom.rand(queue, (n, n, n, n, n), np.float32)\n c_dev = cl.clrandom.rand(queue, (n, n, n, n, n), np.float64)\n\n callee_knl = lp.make_function(\n \"{[i, j]:0<=i, j < %d}\" % n,\n \"\"\"\n h[i, j] = 2 * e[i, j] + 3*f[i, j] + 4*g[i, j]\n <>f1[i, j] = 2*f[i, j]\n p[i, j] = 7 * e[i, j] + 4*f1[i, j] + 2*g[i, j]\n \"\"\",\n [\n lp.GlobalArg('f, e, h, g'), '...'],\n name='linear_combo')\n\n caller_knl = lp.make_kernel(\n \"{[i, j, k, l, m]: 0<=i, j, k, l, m<%d}\" % n,\n \"\"\"\n <> d[i, j, k, l, m] = 2*b[i, j, k, l, m]\n [j, l]: x[i, j, k, l, m], [j, l]: y[i, j, k, l, m] = linear_combo(\n f=[j, l]: a[i, j, k, l, m],\n g=[j, l]: d[i, j, k, l, m],\n e=[j, l]: c[i, j, k, l, m])\n \"\"\")\n\n knl = lp.register_callable_kernel(\n caller_knl, callee_knl)\n if inline:\n knl = lp.inline_callable_kernel(knl, 'linear_combo')\n\n evt, (out1, out2, ) = knl(queue, a=a_dev, b=b_dev, c=c_dev)\n\n a = a_dev.get()\n b = b_dev.get()\n c = c_dev.get()\n\n h = out1.get() # h = 2c + 3a + 8b\n p = out2.get() # p = 7c + 8a + 4b\n h_exact = 3*a + 8*b + 2*c\n p_exact = 8*a + 4*b + 7*c\n\n assert np.linalg.norm(h-h_exact)/np.linalg.norm(h_exact) < 1e-7\n assert np.linalg.norm(p-p_exact)/np.linalg.norm(p_exact) < 1e-7\n\n\[email protected](\"inline\", [False, True])\ndef test_register_knl_with_hw_axes(ctx_factory, inline):\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n\n n = 2 ** 4\n\n x_dev = cl.clrandom.rand(queue, (n, n, n, n, n), np.float64)\n y_dev = cl.clrandom.rand(queue, (n, n, n, n, n), np.float64)\n\n callee_knl = lp.make_function(\n \"{[i, j]:0<=i, j < 16}\",\n \"\"\"\n g[i, j] = 2*e[i, j] + 3*f[i, j]\n \"\"\", name='linear_combo')\n\n callee_knl = lp.split_iname(callee_knl, \"i\", 4, inner_tag=\"l.0\", outer_tag=\"g.0\")\n\n caller_knl = lp.make_kernel(\n \"{[i, j, k, l, m]: 0<=i, j, k, l, m<16}\",\n \"\"\"\n [j, l]: z[i, j, k, l, m] = linear_combo([j, l]: x[i, j, k, l, m],\n [j, l]: y[i, j, k, l, m])\n \"\"\"\n )\n caller_knl = lp.split_iname(caller_knl, \"i\", 4, inner_tag=\"l.1\", outer_tag=\"g.1\")\n\n knl = lp.register_callable_kernel(\n caller_knl, callee_knl)\n\n if inline:\n knl = lp.inline_callable_kernel(knl, 'linear_combo')\n\n evt, (out, ) = knl(queue, x=x_dev, y=y_dev)\n\n x_host = x_dev.get()\n y_host = y_dev.get()\n\n assert np.linalg.norm(2*x_host+3*y_host-out.get())/np.linalg.norm(\n 2*x_host+3*y_host) < 1e-15\n\n\[email protected](\"inline\", [False, True])\ndef test_shape_translation_through_sub_array_ref(ctx_factory, inline):\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n\n x1 = cl.clrandom.rand(queue, (3, 2), dtype=np.float64)\n x2 = cl.clrandom.rand(queue, (6, ), dtype=np.float64)\n x3 = cl.clrandom.rand(queue, (6, 6), dtype=np.float64)\n\n callee1 = lp.make_function(\n \"{[i]: 0<=i<6}\",\n \"\"\"\n a[i] = 2*abs(b[i])\n \"\"\", name=\"callee_fn1\")\n\n callee2 = lp.make_function(\n \"{[i, j]: 0<=i<3 and 0 <= j < 2}\",\n \"\"\"\n a[i, j] = 3*b[i, j]\n \"\"\", name=\"callee_fn2\")\n\n callee3 = lp.make_function(\n \"{[i]: 0<=i<6}\",\n \"\"\"\n a[i] = 5*b[i]\n \"\"\", name=\"callee_fn3\")\n\n knl = lp.make_kernel(\n \"{[i, j, k, l]: 0<= i < 6 and 0 <= j < 3 and 0 <= k < 2 and 0<=l<6}\",\n \"\"\"\n [i]: y1[i//2, i%2] = callee_fn1([i]: x1[i//2, i%2])\n [j, k]: y2[2*j+k] = callee_fn2([j, k]: x2[2*j+k])\n [l]: y3[l, l] = callee_fn3([l]: x3[l, l])\n \"\"\")\n\n knl = lp.register_callable_kernel(knl, callee1)\n knl = lp.register_callable_kernel(knl, callee2)\n knl = lp.register_callable_kernel(knl, callee3)\n\n if inline:\n knl = lp.inline_callable_kernel(knl, 'callee_fn1')\n knl = lp.inline_callable_kernel(knl, 'callee_fn2')\n knl = lp.inline_callable_kernel(knl, 'callee_fn3')\n\n knl = lp.set_options(knl, \"write_cl\")\n knl = lp.set_options(knl, \"return_dict\")\n evt, out_dict = knl(queue, x1=x1, x2=x2, x3=x3)\n\n y1 = out_dict['y1'].get()\n y2 = out_dict['y2'].get()\n y3 = out_dict['y3'].get()\n\n assert (np.linalg.norm(y1-2*x1.get())) < 1e-15\n assert (np.linalg.norm(y2-3*x2.get())) < 1e-15\n assert (np.linalg.norm(np.diag(y3-5*x3.get()))) < 1e-15\n\n\ndef test_multi_arg_array_call(ctx_factory):\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n import pymbolic.primitives as p\n n = 10\n acc_i = p.Variable(\"acc_i\")[0]\n i = p.Variable(\"i\")\n index = p.Variable(\"index\")[0]\n a_i = p.Subscript(p.Variable(\"a\"), p.Variable(\"i\"))\n argmin_kernel = lp.make_function(\n \"{[i]: 0 <= i < n}\",\n [\n lp.Assignment(id=\"init2\", assignee=index,\n expression=0),\n lp.Assignment(id=\"init1\", assignee=acc_i,\n expression=\"214748367\"),\n lp.Assignment(id=\"insn\", assignee=index,\n expression=p.If(p.Expression.eq(acc_i, a_i), i, index),\n depends_on=\"update\"),\n lp.Assignment(id=\"update\", assignee=acc_i,\n expression=p.Variable(\"min\")(acc_i, a_i),\n depends_on=\"init1,init2\")],\n name=\"custom_argmin\")\n\n argmin_kernel = lp.fix_parameters(argmin_kernel, n=n)\n\n knl = lp.make_kernel(\n \"{[i]:0<=i<n}\",\n \"\"\"\n min_val, min_index = custom_argmin([i]:b[i])\n \"\"\")\n\n knl = lp.fix_parameters(knl, n=n)\n knl = lp.set_options(knl, return_dict=True)\n\n knl = lp.register_callable_kernel(knl, argmin_kernel)\n b = np.random.randn(n)\n evt, out_dict = knl(queue, b=b)\n tol = 1e-15\n from numpy.linalg import norm\n assert(norm(out_dict['min_val'][0] - np.min(b)) < tol)\n assert(norm(out_dict['min_index'][0] - np.argmin(b)) < tol)\n\n\[email protected](\"inline\", [False, True])\ndef test_packing_unpacking(ctx_factory, inline):\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n\n x1 = cl.clrandom.rand(queue, (3, 2), dtype=np.float64)\n x2 = cl.clrandom.rand(queue, (6, ), dtype=np.float64)\n\n callee1 = lp.make_function(\n \"{[i]: 0<=i<6}\",\n \"\"\"\n a[i] = 2*b[i]\n \"\"\", name=\"callee_fn1\")\n\n callee2 = lp.make_function(\n \"{[i, j]: 0<=i<2 and 0 <= j < 3}\",\n \"\"\"\n a[i, j] = 3*b[i, j]\n \"\"\", name=\"callee_fn2\")\n\n knl = lp.make_kernel(\n \"{[i, j, k]: 0<= i < 3 and 0 <= j < 2 and 0 <= k < 6}\",\n \"\"\"\n [i, j]: y1[i, j] = callee_fn1([i, j]: x1[i, j])\n [k]: y2[k] = callee_fn2([k]: x2[k])\n \"\"\")\n\n knl = lp.register_callable_kernel(knl, callee1)\n knl = lp.register_callable_kernel(knl, callee2)\n\n knl = lp.pack_and_unpack_args_for_call(knl, 'callee_fn1')\n knl = lp.pack_and_unpack_args_for_call(knl, 'callee_fn2')\n\n if inline:\n knl = lp.inline_callable_kernel(knl, 'callee_fn1')\n knl = lp.inline_callable_kernel(knl, 'callee_fn2')\n\n knl = lp.set_options(knl, \"write_cl\")\n knl = lp.set_options(knl, \"return_dict\")\n evt, out_dict = knl(queue, x1=x1, x2=x2)\n\n y1 = out_dict['y1'].get()\n y2 = out_dict['y2'].get()\n\n assert np.linalg.norm(2*x1.get()-y1)/np.linalg.norm(\n 2*x1.get()) < 1e-15\n assert np.linalg.norm(3*x2.get()-y2)/np.linalg.norm(\n 3*x2.get()) < 1e-15\n\n\ndef test_non_sub_array_refs_arguments(ctx_factory):\n import loopy as lp\n from loopy.transform.callable import _match_caller_callee_argument_dimension_\n\n callee = lp.make_function(\"{[i] : 0 <= i < 6}\", \"a[i] = a[i] + j\",\n [lp.GlobalArg(\"a\", dtype=\"double\", shape=(6,), is_output_only=False),\n lp.ValueArg(\"j\", dtype=\"int\")], name=\"callee\")\n caller1 = lp.make_kernel(\"{[j] : 0 <= j < 2}\", \"callee(a[:], b[0])\",\n [lp.GlobalArg(\"a\", dtype=\"double\", shape=(6, ), is_output_only=False),\n lp.GlobalArg(\"b\", dtype=\"double\", shape=(1, ), is_output_only=False)],\n name=\"caller\", target=lp.CTarget())\n\n caller2 = lp.make_kernel(\"{[j] : 0 <= j < 2}\", \"callee(a[:], 3.1415926)\",\n [lp.GlobalArg(\"a\", dtype=\"double\", shape=(6, ),\n is_output_only=False)],\n name=\"caller\", target=lp.CTarget())\n\n caller3 = lp.make_kernel(\"{[j] : 0 <= j < 2}\", \"callee(a[:], kappa)\",\n [lp.GlobalArg(\"a\", dtype=\"double\", shape=(6, ),\n is_output_only=False)],\n name=\"caller\", target=lp.CTarget())\n\n registered = lp.register_callable_kernel(caller1, callee)\n inlined = _match_caller_callee_argument_dimension_(registered, callee.name)\n inlined = lp.inline_callable_kernel(inlined, callee.name)\n\n print(inlined)\n\n registered = lp.register_callable_kernel(caller2, callee)\n inlined = _match_caller_callee_argument_dimension_(registered, callee.name)\n inlined = lp.inline_callable_kernel(inlined, callee.name)\n\n print(inlined)\n\n registered = lp.register_callable_kernel(caller3, callee)\n inlined = _match_caller_callee_argument_dimension_(registered, callee.name)\n inlined = lp.inline_callable_kernel(inlined, callee.name)\n\n print(inlined)\n\n\[email protected](\"inline\", [False, True])\ndef test_empty_sub_array_refs(ctx_factory, inline):\n # See: https://github.com/OP2/PyOP2/pull/559#discussion_r272208618\n ctx = ctx_factory()\n queue = cl.CommandQueue(ctx)\n\n x = np.random.randn(10)\n y = np.random.randn(10)\n\n callee = lp.make_function(\n \"{[d]:0<=d<1}\",\n \"\"\"\n a[d] = b[d] - c[d]\n\n \"\"\", name='wence_function')\n\n caller = lp.make_kernel(\"{[i]: 0<=i<10}\",\n \"\"\"\n []:z[i] = wence_function([]:x[i], []:y[i])\n \"\"\",\n [lp.GlobalArg('x, y', dtype=np.float64, shape=(10, )), '...'])\n\n caller = lp.register_callable_kernel(caller, callee)\n\n if inline:\n caller = lp.inline_callable_kernel(caller, callee.name)\n\n evt, (out, ) = caller(queue, x=x, y=y)\n assert np.allclose(out, x-y)\n\n\ndef test_nested_callable_inline():\n callee1 = lp.make_function(\n \"{[i]: 0<=i<1}\",\n \"\"\"\n y[i] = 2*x[i]\n \"\"\", name='callee1')\n callee2 = lp.make_kernel(\n \"{[i]: 0<=i<1}\",\n \"\"\"\n []:y[i] = callee1([]: x[i])\n \"\"\", name='callee2')\n\n caller = lp.make_kernel(\"{[i]: 0<=i<10}\",\n \"\"\"\n []:z[i] = callee2([]:x[i])\n \"\"\",\n [lp.GlobalArg('x', dtype=float, shape=lp.auto),\n '...'])\n\n callee2 = lp.register_callable_kernel(callee2, callee1)\n callee2 = lp.inline_callable_kernel(callee2, callee1.name)\n callee2 = callee2.root_kernel\n caller = lp.register_callable_kernel(caller, callee2)\n caller = lp.inline_callable_kernel(caller, callee2.name)\n print(caller)\n\n\nif __name__ == \"__main__\":\n if len(sys.argv) > 1:\n exec(sys.argv[1])\n else:\n from pytest import main\n main([__file__])\n\n# vim: foldmethod=marker\n"
] |
[
[
"numpy.log2",
"numpy.allclose",
"numpy.min",
"numpy.linalg.norm",
"numpy.random.randn",
"numpy.random.rand",
"numpy.argmin"
]
] |
Miraneh/seekr
|
[
"e8b4fed2c6de25fa81956638a9a5c4a897a00b38"
] |
[
"seekr/pwm.py"
] |
[
"# TODO (Dan) What should this file be called?\nimport pandas as pd\nimport numpy as np\n\nfrom collections import defaultdict\nfrom itertools import product\nfrom pathlib import Path\n\n\nclass CountsWeighter:\n \"\"\"Weight kmer counts by a collection of PWMs.\n\n Parameters\n ----------\n pwm_dir: str (default=None)\n Path to directory containing pwm files patterned *.txt.\n counts: str | ndarray | DataFrame (default=None)\n (Path to) kmer counts matrix.\n k: int\n Length of kmer.\n out_path: str (default=None)\n Path to .csv file for weighted counts\n\n Attributes\n ----------\n k_sub: int (default=4)\n Length of sub_kmers to use if motif length is less than k.\n Currently hard-coded to 4.\n kmers: list\n Str elements of all kmers of size k\n df: pd.DataFrame (default=None)\n # TODO (Dan) One line description of contents\n \"\"\"\n\n def __init__(self, pwm_dir=None, counts=None, k=5, out_path=None):\n self.pwm_dir = pwm_dir\n if pwm_dir is not None:\n self.pwm_dir = Path(pwm_dir)\n self.counts = counts\n self.k = k\n self.out_path = out_path\n\n self.k_sub = 4\n self.kmers = [\"\".join(p) for p in product(\"AGTC\", repeat=self.k)]\n self.df = None\n if counts is not None: # get_counts depends on self.kmers\n self.counts = self.get_counts(counts)\n\n def get_counts(self, counts):\n \"\"\"Load kmer counts matrix from .csv or .npy file, if necessary.\n\n Parameters\n ----------\n counts: str | ndarray | DataFrame\n (Path to) kmer counts matrix.\n\n Returns\n -------\n counts: DataFrame\n Kmer counts matrix describing transcript kmer profiles.\n \"\"\"\n counts_types = (str, pd.DataFrame, np.ndarray)\n err_msg = f\"adj must be one of {counts_types}, not {type(counts)}.\"\n assert type(counts) in counts_types, err_msg\n if isinstance(counts, str):\n try:\n counts = pd.read_csv(counts, index_col=0)\n except UnicodeDecodeError:\n counts = np.load(counts)\n if isinstance(counts, np.ndarray):\n counts = pd.DataFrame(counts, columns=self.kmers)\n return counts\n\n def gen_pwm_dicts(self):\n \"\"\"Search directory for non-empty pwm files, and load them.\n\n Yields\n ------\n pwm_path: str\n Path to non-empty pwm file.\n pwm: Dict[str: Dict[int: float]]\n Position weight matrix as a nested dict (for fast lookups).\n Outer keys are nucleotides. Inner keys are positions. Inner values are weights.\n \"\"\"\n for pwm_path in self.pwm_dir.glob(\"*.txt\"):\n try:\n pwm = pd.read_csv(pwm_path, sep=\"\\t\")\n except pd.errors.EmptyDataError:\n print(f\"The motif file {pwm_path} is empty. Skipping.\")\n continue\n pwm.drop(\"Pos\", axis=1, inplace=True)\n pwm = pwm.rename(columns={\"U\": \"T\"}).to_dict()\n yield pwm_path, pwm\n\n def set_kmer2weight(self, kmer2weight, pwm, key_kmer, iter_kmer, n_kmers):\n for frame in range(n_kmers):\n weight = 1\n for pos, nucleotide in enumerate(iter_kmer):\n weight *= pwm[nucleotide][pos + frame]\n kmer2weight[key_kmer] += weight\n\n def build_weights_dict(self, pwm):\n \"\"\"Create a mapping between all kmers their weights in a given PWM.\n\n Parameters\n ----------\n pwm: Dict[str: Dict[int: float]]\n Position weight matrix.\n\n Returns\n -------\n kmer2weight: Dict\n Keys are all kmers, values are the kmer's weight in a given pwm.\n \"\"\"\n kmer2weight = defaultdict(int)\n motif_len = len(pwm[\"A\"])\n if motif_len < self.k:\n n_kmers = motif_len - 4 + 1\n for kmer in self.kmers:\n for sub_kmer in (kmer[i : i + self.k_sub] for i in range(self.k - self.k_sub + 1)):\n self.set_kmer2weight(kmer2weight, pwm, kmer, sub_kmer, n_kmers)\n else:\n for kmer in self.kmers:\n n_kmers = motif_len - self.k + 1\n self.set_kmer2weight(kmer2weight, pwm, kmer, kmer, n_kmers)\n return kmer2weight\n\n def weight_counts(self, kmer2weight):\n \"\"\"Weight each kmer in counts matix by corresponding kmer weight found in a PWM.\n\n Parameters\n ----------\n kmer2weight: Dict\n Keys are all kmers, values are the kmer's weight in a given pwm.\n\n Returns\n -------\n scores_sums: np.array\n Each element corresponds to sum of weighted kmer profile for given transcript.\n Length of scores_sums is equal to length of counts.\n \"\"\"\n sorted_weights = np.array([kmer2weight[k] for k in self.counts.columns])\n weighted_z_scores = self.counts.values.copy() * sorted_weights\n scores_sums = weighted_z_scores.sum(axis=1)\n return scores_sums\n\n def save(self):\n \"\"\"Save df to csv file.\"\"\"\n if self.out_path is not None:\n self.df.to_csv(self.out_path, float_format=\"%.4f\")\n\n def run(self):\n \"\"\"TODO (Dan) Update based on description of self.df\"\"\"\n score_dict = {}\n for pwm_path, pwm in self.gen_pwm_dicts():\n kmer2weight = self.build_weights_dict(pwm)\n score_dict[pwm_path.name] = self.weight_counts(kmer2weight)\n self.df = pd.DataFrame.from_dict(score_dict, orient=\"index\", columns=self.counts.index)\n self.save()\n"
] |
[
[
"pandas.read_csv",
"pandas.DataFrame",
"pandas.DataFrame.from_dict",
"numpy.load",
"numpy.array"
]
] |
mithunpaul08/bert_tensorflow
|
[
"0b2487b700f0c4d46ff7461759593bed8cad9e84"
] |
[
"run_classifier_ARC_DETAILED_sandeep.py"
] |
[
"# coding=utf-8\n# Copyright 2018 The Google AI Language Team Authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\"\"\"BERT finetuning runner.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom comet_ml import Experiment,ExistingExperiment\nimport collections\nimport csv\nimport os\nimport modeling\nimport optimization\nimport tokenization\nimport tensorflow as tf\nimport logging\nflags = tf.flags\n\nFLAGS = flags.FLAGS\n\n## Required parameters\nflags.DEFINE_string(\n \"data_dir\", None,\n \"The input data dir. Should contain the .tsv files (or other data files) \"\n \"for the task.\")\n\nflags.DEFINE_string(\n \"data_dir_cross_domain\", None,\n \"input directory where cross domain files will be stored.\")\n\nflags.DEFINE_string(\n \"bert_config_file\", None,\n \"The config json file corresponding to the pre-trained BERT model. \"\n \"This specifies the model architecture.\")\n\nflags.DEFINE_string(\"task_name\", None, \"The name of the task to train.\")\n\nflags.DEFINE_string(\"vocab_file\", None,\n \"The vocabulary file that the BERT model was trained on.\")\n\nflags.DEFINE_string(\n \"output_dir\", None,\n \"The output directory where the model checkpoints will be written.\")\n\n\n\n\n\n## Other parameters\n\nflags.DEFINE_string(\n \"init_checkpoint\", None,\n \"Initial checkpoint (usually from a pre-trained BERT model).\")\n\nflags.DEFINE_bool(\n \"do_lower_case\", True,\n \"Whether to lower case the input text. Should be True for uncased \"\n \"models and False for cased models.\")\n\nflags.DEFINE_integer(\n \"max_seq_length\", 128,\n \"The maximum total input sequence length after WordPiece tokenization. \"\n \"Sequences longer than this will be truncated, and sequences shorter \"\n \"than this will be padded.\")\n\nflags.DEFINE_bool(\"do_train\", True, \"Whether to run training.\")\n\nflags.DEFINE_bool(\"do_eval\", True, \"Whether to run eval on the dev set.\")\n\nflags.DEFINE_bool(\n \"do_predict\", True,\n \"Whether to run the model in inference mode on the test set.\")\n\nflags.DEFINE_integer(\"train_batch_size\", 32, \"Total batch size for training.\")\n\nflags.DEFINE_integer(\"eval_batch_size\", 8, \"Total batch size for eval.\")\n\nflags.DEFINE_integer(\"predict_batch_size\", 8, \"Total batch size for predict.\")\n\nflags.DEFINE_float(\"learning_rate\", 5e-5, \"The initial learning rate for Adam.\")\n\nflags.DEFINE_float(\"num_train_epochs\", 3.0,\n \"Total number of training epochs to perform.\")\n\nflags.DEFINE_float(\n \"warmup_proportion\", 0.1,\n \"Proportion of training to perform linear learning rate warmup for. \"\n \"E.g., 0.1 = 10% of training.\")\n\nflags.DEFINE_integer(\"save_checkpoints_steps\", 0,\n \"How often to save the model checkpoint.\")\n\nflags.DEFINE_integer(\"iterations_per_loop\", 800,\n \"How many steps to make in each estimator call.\")\n\nflags.DEFINE_bool(\"use_tpu\", False, \"Whether to use TPU or GPU/CPU.\")\n\ntf.flags.DEFINE_string(\n \"tpu_name\", None,\n \"The Cloud TPU to use for training. This should be either the name \"\n \"used when creating the Cloud TPU, or a grpc://ip.address.of.tpu:8470 \"\n \"url.\")\n\ntf.flags.DEFINE_string(\n \"tpu_zone\", None,\n \"[Optional] GCE zone where the Cloud TPU is located in. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\n \"gcp_project\", None,\n \"[Optional] Project name for the Cloud TPU-enabled project. If not \"\n \"specified, we will attempt to automatically detect the GCE project from \"\n \"metadata.\")\n\ntf.flags.DEFINE_string(\"master\", None, \"[Optional] TensorFlow master URL.\")\n\nflags.DEFINE_integer(\n \"num_tpu_cores\", 8,\n \"Only used if `use_tpu` is True. Total number of TPU cores to use.\")\ndef initialize_comet():\n # for drawing graphs on comet:\n comet_Expt_object=None\n\n comet_Expt_object = Experiment(api_key=\"XUbi4cShweB6drrJ5eAKMT6FT\", project_name=\"sandeep_bert_code\")\n\n return comet_Expt_object\n\n\nclass InputExample(object):\n \"\"\"A single training/test example for simple sequence classification.\"\"\"\n\n def __init__(self, guid, text_a, text_b=None, label=None):\n \"\"\"Constructs a InputExample.\n\n Args:\n guid: Unique id for the example.\n text_a: string. The untokenized text of the first sequence. For single\n sequence tasks, only this sequence must be specified.\n text_b: (Optional) string. The untokenized text of the second sequence.\n Only must be specified for sequence pair tasks.\n label: (Optional) string. The label of the example. This should be\n specified for train and dev examples, but not for test examples.\n \"\"\"\n self.guid = guid\n self.text_a = text_a\n self.text_b = text_b\n self.label = label\n\n\nclass PaddingInputExample(object):\n \"\"\"Fake example so the num input examples is a multiple of the batch size.\n\n When running eval/predict on the TPU, we need to pad the number of examples\n to be a multiple of the batch size, because the TPU requires a fixed batch\n size. The alternative is to drop the last batch, which is bad because it means\n the entire output data won't be generated.\n\n We use this class instead of `None` because treating `None` as padding\n battches could cause silent errors.\n \"\"\"\n\n\nclass InputFeatures(object):\n \"\"\"A single set of features of data.\"\"\"\n\n def __init__(self,\n input_ids,\n input_mask,\n segment_ids,\n label_id,\n is_real_example=True):\n self.input_ids = input_ids\n self.input_mask = input_mask\n self.segment_ids = segment_ids\n self.label_id = label_id\n self.is_real_example = is_real_example\n\n\nclass DataProcessor(object):\n \"\"\"Base class for data converters for sequence classification data sets.\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the train set.\"\"\"\n raise NotImplementedError()\n\n def get_dev_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for the dev set.\"\"\"\n raise NotImplementedError()\n\n def get_test_examples(self, data_dir):\n \"\"\"Gets a collection of `InputExample`s for prediction.\"\"\"\n raise NotImplementedError()\n\n def get_labels(self):\n \"\"\"Gets the list of labels for this data set.\"\"\"\n raise NotImplementedError()\n\n @classmethod\n def _read_tsv(cls, input_file, quotechar=None):\n \"\"\"Reads a tab separated value file.\"\"\"\n with tf.gfile.Open(input_file, \"r\") as f:\n reader = csv.reader(f, delimiter=\"\\t\", quotechar=quotechar)\n lines = []\n for line in reader:\n lines.append(line)\n return lines\n\n\n\nclass FeverProcessorCrossDomain(DataProcessor):\n \"\"\"Processor for the Fever data set cross-domain (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")),\n \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"agree\", \"disagree\", \"discuss\", \"unrelated\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n # if set_type == \"test\" and i == 0:\n # continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[2])\n text_b = tokenization.convert_to_unicode(line[3])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\nclass FeverProcessorInDomain(DataProcessor):\n \"\"\"Processor for the Fever data set in-domain (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")),\n \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"pasing the value as dev instead of test because the code create_examples drops first line\n assuming it to be header when the partition is \"test\".\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"agree\", \"disagree\", \"nei\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n # if set_type == \"test\" and i == 0:\n # continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[2])\n text_b = tokenization.convert_to_unicode(line[3])\n label = tokenization.convert_to_unicode(line[1])\n #tf.logging.info(\"*#*#Begin\")\n #tf.logging.info(text_a)\n #tf.logging.info(text_b)\n #tf.logging.info(label)\n #tf.logging.info(\"#*#*End\")\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\nclass FNCProcessorCrossDomain(DataProcessor):\n \"\"\"Processor for the FNC data set cross domain (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")),\n \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"test.tsv\")), \"test\")\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"agree\", \"disagree\", \"nei\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n # if set_type == \"test\" and i == 0:\n # continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[2])\n text_b = tokenization.convert_to_unicode(line[3])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\nclass FNCProcessorInDomain(DataProcessor):\n \"\"\"Processor for the FNC data set in-domain (GLUE version).\"\"\"\n\n def get_train_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"train.tsv\")), \"train\")\n\n def get_dev_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n return self._create_examples(\n self._read_tsv(os.path.join(data_dir, \"dev.tsv\")),\n \"dev\")\n\n def get_test_examples(self, data_dir):\n \"\"\"See base class.\"\"\"\n print(\"test\")\n tsv_input=self._read_tsv(os.path.join(data_dir, \"test.tsv\"))\n ret= self._create_examples(tsv_input, \"test\")\n print(ret)\n return ret\n\n def get_labels(self):\n \"\"\"See base class.\"\"\"\n return [\"agree\", \"disagree\", \"discuss\", \"unrelated\"]\n\n def _create_examples(self, lines, set_type):\n \"\"\"Creates examples for the training and dev sets.\"\"\"\n examples = []\n for (i, line) in enumerate(lines):\n # if set_type == \"test\" and i == 0:\n # continue\n guid = \"%s-%s\" % (set_type, i)\n text_a = tokenization.convert_to_unicode(line[2])\n text_b = tokenization.convert_to_unicode(line[3])\n label = tokenization.convert_to_unicode(line[1])\n examples.append(\n InputExample(guid=guid, text_a=text_a, text_b=text_b, label=label))\n return examples\n\n\ndef convert_single_example(ex_index, example, label_list, max_seq_length,\n tokenizer):\n \"\"\"Converts a single `InputExample` into a single `InputFeatures`.\"\"\"\n\n if isinstance(example, PaddingInputExample):\n return InputFeatures(\n input_ids=[0] * max_seq_length,\n input_mask=[0] * max_seq_length,\n segment_ids=[0] * max_seq_length,\n label_id=0,\n is_real_example=False)\n\n label_map = {}\n for (i, label) in enumerate(label_list):\n label_map[label] = i\n\n tokens_a = tokenizer.tokenize(example.text_a)\n tokens_b = None\n if example.text_b:\n tokens_b = tokenizer.tokenize(example.text_b)\n\n if tokens_b:\n # Modifies `tokens_a` and `tokens_b` in place so that the total\n # length is less than the specified length.\n # Account for [CLS], [SEP], [SEP] with \"- 3\"\n _truncate_seq_pair(tokens_a, tokens_b, max_seq_length - 3)\n else:\n # Account for [CLS] and [SEP] with \"- 2\"\n if len(tokens_a) > max_seq_length - 2:\n tokens_a = tokens_a[0:(max_seq_length - 2)]\n\n # The convention in BERT is:\n # (a) For sequence pairs:\n # tokens: [CLS] is this jack ##son ##ville ? [SEP] no it is not . [SEP]\n # type_ids: 0 0 0 0 0 0 0 0 1 1 1 1 1 1\n # (b) For single sequences:\n # tokens: [CLS] the dog is hairy . [SEP]\n # type_ids: 0 0 0 0 0 0 0\n #\n # Where \"type_ids\" are used to indicate whether this is the first\n # sequence or the second sequence. The embedding vectors for `type=0` and\n # `type=1` were learned during pre-training and are added to the wordpiece\n # embedding vector (and position vector). This is not *strictly* necessary\n # since the [SEP] token unambiguously separates the sequences, but it makes\n # it easier for the model to learn the concept of sequences.\n #\n # For classification tasks, the first vector (corresponding to [CLS]) is\n # used as the \"sentence vector\". Note that this only makes sense because\n # the entire model is fine-tuned.\n tokens = []\n segment_ids = []\n tokens.append(\"[CLS]\")\n segment_ids.append(0)\n for token in tokens_a:\n tokens.append(token)\n segment_ids.append(0)\n tokens.append(\"[SEP]\")\n segment_ids.append(0)\n\n if tokens_b:\n for token in tokens_b:\n tokens.append(token)\n segment_ids.append(1)\n tokens.append(\"[SEP]\")\n segment_ids.append(1)\n\n input_ids = tokenizer.convert_tokens_to_ids(tokens)\n\n # The mask has 1 for real tokens and 0 for padding tokens. Only real\n # tokens are attended to.\n input_mask = [1] * len(input_ids)\n\n # Zero-pad up to the sequence length.\n while len(input_ids) < max_seq_length:\n input_ids.append(0)\n input_mask.append(0)\n segment_ids.append(0)\n\n assert len(input_ids) == max_seq_length\n assert len(input_mask) == max_seq_length\n assert len(segment_ids) == max_seq_length\n\n label_id = label_map[example.label]\n if ex_index < 5:\n tf.logging.info(\"*** Example ***\")\n tf.logging.info(\"guid: %s\" % (example.guid))\n tf.logging.info(\"tokens: %s\" % \" \".join(\n [tokenization.printable_text(x) for x in tokens]))\n tf.logging.info(\"input_ids: %s\" % \" \".join([str(x) for x in input_ids]))\n tf.logging.info(\"input_mask: %s\" % \" \".join([str(x) for x in input_mask]))\n tf.logging.info(\"segment_ids: %s\" % \" \".join([str(x) for x in segment_ids]))\n tf.logging.info(\"label: %s (id = %d)\" % (example.label, label_id))\n\n feature = InputFeatures(\n input_ids=input_ids,\n input_mask=input_mask,\n segment_ids=segment_ids,\n label_id=label_id,\n is_real_example=True)\n return feature\n\n\ndef file_based_convert_examples_to_features(\n examples, label_list, max_seq_length, tokenizer, output_file):\n \"\"\"Convert a set of `InputExample`s to a TFRecord file.\"\"\"\n\n writer = tf.python_io.TFRecordWriter(output_file)\n\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n def create_int_feature(values):\n f = tf.train.Feature(int64_list=tf.train.Int64List(value=list(values)))\n return f\n\n features = collections.OrderedDict()\n features[\"input_ids\"] = create_int_feature(feature.input_ids)\n features[\"input_mask\"] = create_int_feature(feature.input_mask)\n features[\"segment_ids\"] = create_int_feature(feature.segment_ids)\n features[\"label_ids\"] = create_int_feature([feature.label_id])\n features[\"is_real_example\"] = create_int_feature(\n [int(feature.is_real_example)])\n\n tf_example = tf.train.Example(features=tf.train.Features(feature=features))\n writer.write(tf_example.SerializeToString())\n writer.close()\n\n\ndef file_based_input_fn_builder(input_file, seq_length, is_training,\n drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n name_to_features = {\n \"input_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"input_mask\": tf.FixedLenFeature([seq_length], tf.int64),\n \"segment_ids\": tf.FixedLenFeature([seq_length], tf.int64),\n \"label_ids\": tf.FixedLenFeature([], tf.int64),\n \"is_real_example\": tf.FixedLenFeature([], tf.int64),\n }\n\n def _decode_record(record, name_to_features):\n \"\"\"Decodes a record to a TensorFlow example.\"\"\"\n example = tf.parse_single_example(record, name_to_features)\n\n # tf.Example only supports tf.int64, but the TPU only supports tf.int32.\n # So cast all int64 to int32.\n for name in list(example.keys()):\n t = example[name]\n if t.dtype == tf.int64:\n t = tf.to_int32(t)\n example[name] = t\n\n return example\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n # For training, we want a lot of parallel reading and shuffling.\n # For eval, we want no shuffling and parallel reading doesn't matter.\n d = tf.data.TFRecordDataset(input_file)\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.apply(\n tf.contrib.data.map_and_batch(\n lambda record: _decode_record(record, name_to_features),\n batch_size=batch_size,\n drop_remainder=drop_remainder))\n\n return d\n\n return input_fn\n\n\ndef _truncate_seq_pair(tokens_a, tokens_b, max_length):\n \"\"\"Truncates a sequence pair in place to the maximum length.\"\"\"\n\n # This is a simple heuristic which will always truncate the longer sequence\n # one token at a time. This makes more sense than truncating an equal percent\n # of tokens from each, since if one sequence is very short then each token\n # that's truncated likely contains more information than a longer sequence.\n while True:\n total_length = len(tokens_a) + len(tokens_b)\n if total_length <= max_length:\n break\n if len(tokens_a) > len(tokens_b):\n tokens_a.pop()\n else:\n tokens_b.pop()\n\n\ndef create_model(bert_config, is_training, input_ids, input_mask, segment_ids,\n labels, num_labels, use_one_hot_embeddings):\n \"\"\"Creates a classification model.\"\"\"\n model = modeling.BertModel(\n config=bert_config,\n is_training=is_training,\n input_ids=input_ids,\n input_mask=input_mask,\n token_type_ids=segment_ids,\n use_one_hot_embeddings=use_one_hot_embeddings)\n\n # In the demo, we are doing a simple classification task on the entire\n # segment.\n #\n # If you want to use the token-level output, use model.get_sequence_output()\n # instead.\n output_layer = model.get_pooled_output()\n\n hidden_size = output_layer.shape[-1].value\n\n output_weights = tf.get_variable(\n \"output_weights\", [num_labels, hidden_size],\n initializer=tf.truncated_normal_initializer(stddev=0.02))\n\n output_bias = tf.get_variable(\n \"output_bias\", [num_labels], initializer=tf.zeros_initializer())\n\n with tf.variable_scope(\"loss\"):\n if is_training:\n # I.e., 0.1 dropout\n output_layer = tf.nn.dropout(output_layer, keep_prob=0.9)\n\n logits = tf.matmul(output_layer, output_weights, transpose_b=True)\n logits = tf.nn.bias_add(logits, output_bias)\n probabilities = tf.nn.softmax(logits, axis=-1)\n log_probs = tf.nn.log_softmax(logits, axis=-1)\n\n one_hot_labels = tf.one_hot(labels, depth=num_labels, dtype=tf.float32)\n\n per_example_loss = -tf.reduce_sum(one_hot_labels * log_probs, axis=-1)\n loss = tf.reduce_mean(per_example_loss)\n\n return (loss, per_example_loss, logits, probabilities)\n\n\ndef model_fn_builder(bert_config, num_labels, init_checkpoint, learning_rate,\n num_train_steps, num_warmup_steps, use_tpu,\n use_one_hot_embeddings):\n \"\"\"Returns `model_fn` closure for TPUEstimator.\"\"\"\n\n def model_fn(features, labels, mode, params): # pylint: disable=unused-argument\n \"\"\"The `model_fn` for TPUEstimator.\"\"\"\n\n tf.logging.info(\"*** Features ***\")\n for name in sorted(features.keys()):\n tf.logging.info(\" name = %s, shape = %s\" % (name, features[name].shape))\n\n input_ids = features[\"input_ids\"]\n input_mask = features[\"input_mask\"]\n segment_ids = features[\"segment_ids\"]\n label_ids = features[\"label_ids\"]\n tf.logging.info(\"*** Sandeep Features-1 ***\")\n tf.logging.info(label_ids)\n is_real_example = None\n if \"is_real_example\" in features:\n is_real_example = tf.cast(features[\"is_real_example\"], dtype=tf.float32)\n else:\n is_real_example = tf.ones(tf.shape(label_ids), dtype=tf.float32)\n\n is_training = (mode == tf.estimator.ModeKeys.TRAIN)\n tf.logging.info(\"*** Sandeep Features-2 ***\")\n (total_loss, per_example_loss, logits, probabilities) = create_model(\n bert_config, is_training, input_ids, input_mask, segment_ids, label_ids,\n num_labels, use_one_hot_embeddings)\n tf.logging.info(\"*** Sandeep Features-3 ***\")\n tvars = tf.trainable_variables()\n initialized_variable_names = {}\n scaffold_fn = None\n if init_checkpoint:\n tf.logging.info(\"*** Sandeep Features-4.1 ***\")\n tf.logging.info(init_checkpoint)\n (assignment_map, initialized_variable_names\n ) = modeling.get_assignment_map_from_checkpoint(tvars, init_checkpoint)\n tf.logging.info(\"*** Sandeep Features-4 ***\")\n if use_tpu:\n\n def tpu_scaffold():\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n return tf.train.Scaffold()\n\n scaffold_fn = tpu_scaffold\n else:\n tf.logging.info(\"*** Sandeep Features-5 ***\")\n tf.train.init_from_checkpoint(init_checkpoint, assignment_map)\n tf.logging.info(\"*** Sandeep Features-6 ***\")\n\n tf.logging.info(\"**** Trainable Variables ****\")\n for var in tvars:\n init_string = \"\"\n if var.name in initialized_variable_names:\n init_string = \", *INIT_FROM_CKPT*\"\n tf.logging.info(\" name = %s, shape = %s%s\", var.name, var.shape,\n init_string)\n tf.logging.info(\"Mode is\")\n tf.logging.info(mode)\n output_spec = None\n if mode == tf.estimator.ModeKeys.TRAIN:\n\n train_op = optimization.create_optimizer(\n total_loss, learning_rate, num_train_steps, num_warmup_steps, use_tpu)\n\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n train_op=train_op,\n scaffold_fn=scaffold_fn)\n elif mode == tf.estimator.ModeKeys.EVAL:\n\n def metric_fn(per_example_loss, label_ids, logits, is_real_example):\n tf.logging.info(\"Sandeep in metric_fn\")\n predictions = tf.argmax(logits, axis=-1, output_type=tf.int32)\n accuracy = tf.metrics.accuracy(\n labels=label_ids, predictions=predictions, weights=is_real_example)\n loss = tf.metrics.mean(values=per_example_loss, weights=is_real_example)\n return {\n \"eval_accuracy\": accuracy,\n \"eval_loss\": loss,\n }\n\n eval_metrics = (metric_fn,\n [per_example_loss, label_ids, logits, is_real_example])\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n loss=total_loss,\n eval_metrics=eval_metrics,\n scaffold_fn=scaffold_fn)\n else:\n output_spec = tf.contrib.tpu.TPUEstimatorSpec(\n mode=mode,\n predictions={\"probabilities\": probabilities},\n scaffold_fn=scaffold_fn)\n return output_spec\n\n return model_fn\n\n\n# This function is not used by this file but is still used by the Colab and\n# people who depend on it.\ndef input_fn_builder(features, seq_length, is_training, drop_remainder):\n \"\"\"Creates an `input_fn` closure to be passed to TPUEstimator.\"\"\"\n\n all_input_ids = []\n all_input_mask = []\n all_segment_ids = []\n all_label_ids = []\n\n for feature in features:\n all_input_ids.append(feature.input_ids)\n all_input_mask.append(feature.input_mask)\n all_segment_ids.append(feature.segment_ids)\n all_label_ids.append(feature.label_id)\n\n def input_fn(params):\n \"\"\"The actual input function.\"\"\"\n batch_size = params[\"batch_size\"]\n\n num_examples = len(features)\n\n # This is for demo purposes and does NOT scale to large data sets. We do\n # not use Dataset.from_generator() because that uses tf.py_func which is\n # not TPU compatible. The right way to load data is with TFRecordReader.\n d = tf.data.Dataset.from_tensor_slices({\n \"input_ids\":\n tf.constant(\n all_input_ids, shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"input_mask\":\n tf.constant(\n all_input_mask,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"segment_ids\":\n tf.constant(\n all_segment_ids,\n shape=[num_examples, seq_length],\n dtype=tf.int32),\n \"label_ids\":\n tf.constant(all_label_ids, shape=[num_examples], dtype=tf.int32),\n })\n\n if is_training:\n d = d.repeat()\n d = d.shuffle(buffer_size=100)\n\n d = d.batch(batch_size=batch_size, drop_remainder=drop_remainder)\n return d\n\n return input_fn\n\n\n# This function is not used by this file but is still used by the Colab and\n# people who depend on it.\ndef convert_examples_to_features(examples, label_list, max_seq_length,\n tokenizer):\n \"\"\"Convert a set of `InputExample`s to a list of `InputFeatures`.\"\"\"\n\n features = []\n for (ex_index, example) in enumerate(examples):\n if ex_index % 10000 == 0:\n tf.logging.info(\"Writing example %d of %d\" % (ex_index, len(examples)))\n\n feature = convert_single_example(ex_index, example, label_list,\n max_seq_length, tokenizer)\n\n features.append(feature)\n return features\n\n\ndef main(_):\n\n\n tf.logging.set_verbosity(tf.logging.INFO)\n comet_value_updater = initialize_comet()\n\n processors = {\n # \"cola\": ColaProcessor,\n # \"mnli\": MnliProcessor,\n # \"mrpc\": MrpcProcessor,\n # \"xnli\": XnliProcessor,\n \"fevercd\": FeverProcessorCrossDomain\n # \"fnccd\": FNCProcessorCrossDomain,\n # \"feverid\": FeverProcessorInDomain,\n # \"fncid\": FNCProcessorInDomain,\n\n }\n\n tokenization.validate_case_matches_checkpoint(FLAGS.do_lower_case,\n FLAGS.init_checkpoint)\n\n if not FLAGS.do_train and not FLAGS.do_eval and not FLAGS.do_predict:\n raise ValueError(\n \"At least one of `do_train`, `do_eval` or `do_predict' must be True.\")\n\n bert_config = modeling.BertConfig.from_json_file(FLAGS.bert_config_file)\n\n if FLAGS.max_seq_length > bert_config.max_position_embeddings:\n raise ValueError(\n \"Cannot use sequence length %d because the BERT model \"\n \"was only trained up to sequence length %d\" %\n (FLAGS.max_seq_length, bert_config.max_position_embeddings))\n\n tf.gfile.MakeDirs(FLAGS.output_dir)\n\n task_name = FLAGS.task_name.lower()\n\n if task_name not in processors:\n raise ValueError(\"Task not found: %s\" % (task_name))\n\n processor = processors[task_name]()\n\n label_list = processor.get_labels()\n\n tokenizer = tokenization.FullTokenizer(\n vocab_file=FLAGS.vocab_file, do_lower_case=FLAGS.do_lower_case)\n\n tpu_cluster_resolver = None\n if FLAGS.use_tpu and FLAGS.tpu_name:\n tpu_cluster_resolver = tf.contrib.cluster_resolver.TPUClusterResolver(\n FLAGS.tpu_name, zone=FLAGS.tpu_zone, project=FLAGS.gcp_project)\n\n is_per_host = tf.contrib.tpu.InputPipelineConfig.PER_HOST_V2\n run_config = tf.contrib.tpu.RunConfig(\n cluster=tpu_cluster_resolver,\n master=FLAGS.master,\n model_dir=FLAGS.output_dir,\n keep_checkpoint_max = 2,\n save_checkpoints_steps=FLAGS.save_checkpoints_steps,\n tpu_config=tf.contrib.tpu.TPUConfig(\n iterations_per_loop=FLAGS.iterations_per_loop,\n num_shards=FLAGS.num_tpu_cores,\n per_host_input_for_training=is_per_host))\n\n train_examples = None\n num_train_steps = None\n num_warmup_steps = None\n if FLAGS.do_train:\n train_examples = processor.get_train_examples(FLAGS.data_dir)\n num_train_steps = int(\n len(train_examples) / FLAGS.train_batch_size * FLAGS.num_train_epochs)\n num_warmup_steps = int(num_train_steps * FLAGS.warmup_proportion)\n\n model_fn = model_fn_builder(\n bert_config=bert_config,\n num_labels=len(label_list),\n init_checkpoint=FLAGS.init_checkpoint,\n learning_rate=FLAGS.learning_rate,\n num_train_steps=num_train_steps,\n num_warmup_steps=num_warmup_steps,\n use_tpu=FLAGS.use_tpu,\n use_one_hot_embeddings=FLAGS.use_tpu)\n\n # If TPU is not available, this will fall back to normal Estimator on CPU\n # or GPU.\n estimator = tf.contrib.tpu.TPUEstimator(\n use_tpu=FLAGS.use_tpu,\n model_fn=model_fn,\n config=run_config,\n train_batch_size=FLAGS.train_batch_size,\n eval_batch_size=FLAGS.eval_batch_size,\n predict_batch_size=FLAGS.predict_batch_size)\n\n if FLAGS.do_train:\n train_file = os.path.join(FLAGS.output_dir, \"train.tf_record\")\n file_based_convert_examples_to_features(\n train_examples, label_list, FLAGS.max_seq_length, tokenizer, train_file)\n tf.logging.info(\"***** Running training *****\")\n tf.logging.info(\" Num examples = %d\", len(train_examples))\n tf.logging.info(\" Batch size = %d\", FLAGS.train_batch_size)\n tf.logging.info(\" Num steps = %d\", num_train_steps)\n train_input_fn = file_based_input_fn_builder(\n input_file=train_file,\n seq_length=FLAGS.max_seq_length,\n is_training=True,\n drop_remainder=True)\n train_output=estimator.train(input_fn=train_input_fn, max_steps=num_train_steps)\n\n if FLAGS.do_eval:\n eval_examples = processor.get_dev_examples(FLAGS.data_dir)\n num_actual_eval_examples = len(eval_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on. These do NOT count towards the metric (all tf.metrics\n # support a per-instance weight, and these get a weight of 0.0).\n while len(eval_examples) % FLAGS.eval_batch_size != 0:\n eval_examples.append(PaddingInputExample())\n\n eval_file = os.path.join(FLAGS.output_dir, \"eval_tf_record.txt\")\n file_based_convert_examples_to_features(\n eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)\n\n tf.logging.info(\"***** Running evaluation *****\")\n tf.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(eval_examples), num_actual_eval_examples,\n len(eval_examples) - num_actual_eval_examples)\n tf.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)\n\n # This tells the estimator to run through the entire set.\n eval_steps = None\n # However, if running eval on the TPU, you will need to specify the\n # number of steps.\n if FLAGS.use_tpu:\n assert len(eval_examples) % FLAGS.eval_batch_size == 0\n eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)\n\n eval_drop_remainder = True if FLAGS.use_tpu else False\n eval_input_fn = file_based_input_fn_builder(\n input_file=eval_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=eval_drop_remainder)\n\n result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)\n comet_value_updater.log_metric(\n \"eval_accuracy\",\n result[\"eval_accuracy\"],\n step=eval_steps)\n filename_fever = \"eval_fever_results\" + str(FLAGS.num_train_epochs) + \"_epochs.txt\"\n\n output_eval_file = os.path.join(FLAGS.output_dir, filename_fever)\n \n tf.logging.info(\"Sandeep-4\")\n tf.logging.info(output_eval_file)\n\n\n with tf.gfile.GFile(output_eval_file, \"a\") as writer:\n tf.logging.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n tf.logging.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n\n #running eval twice . once on fever-dev and another on fnc-dev. the predict below is useless.. it just prints logits\n if FLAGS.do_eval:\n eval_examples = processor.get_dev_examples(FLAGS.data_dir_cross_domain)\n num_actual_eval_examples = len(eval_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on. These do NOT count towards the metric (all tf.metrics\n # support a per-instance weight, and these get a weight of 0.0).\n while len(eval_examples) % FLAGS.eval_batch_size != 0:\n eval_examples.append(PaddingInputExample())\n\n eval_file = os.path.join(FLAGS.output_dir, \"eval_tf_record.txt\")\n file_based_convert_examples_to_features(\n eval_examples, label_list, FLAGS.max_seq_length, tokenizer, eval_file)\n\n tf.logging.info(\"***** Running evaluation *****\")\n tf.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(eval_examples), num_actual_eval_examples,\n len(eval_examples) - num_actual_eval_examples)\n tf.logging.info(\" Batch size = %d\", FLAGS.eval_batch_size)\n\n # This tells the estimator to run through the entire set.\n eval_steps = None\n # However, if running eval on the TPU, you will need to specify the\n # number of steps.\n if FLAGS.use_tpu:\n assert len(eval_examples) % FLAGS.eval_batch_size == 0\n eval_steps = int(len(eval_examples) // FLAGS.eval_batch_size)\n\n eval_drop_remainder = True if FLAGS.use_tpu else False\n eval_input_fn = file_based_input_fn_builder(\n input_file=eval_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=eval_drop_remainder)\n\n result = estimator.evaluate(input_fn=eval_input_fn, steps=eval_steps)\n\n comet_value_updater.log_metric(\n \"eval_accuracy\",\n result[\"eval_accuracy\"],\n step=eval_steps)\n\n name_fnc = \"eval_fnc_results_\"+str(FLAGS.num_train_epochs)+\"_epochs.txt\"\n output_eval_file = os.path.join(FLAGS.output_dir, name_fnc)\n\n tf.logging.info(\"Sandeep-4\")\n tf.logging.info(output_eval_file)\n\n with tf.gfile.GFile(output_eval_file, \"a\") as writer:\n tf.logging.info(\"***** Eval results *****\")\n for key in sorted(result.keys()):\n tf.logging.info(\" %s = %s\", key, str(result[key]))\n writer.write(\"%s = %s\\n\" % (key, str(result[key])))\n\n if FLAGS.do_predict:\n predict_examples = processor.get_dev_examples(FLAGS.data_dir_cross_domain)\n num_actual_predict_examples = len(predict_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on.\n while len(predict_examples) % FLAGS.predict_batch_size != 0:\n predict_examples.append(PaddingInputExample())\n\n predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\")\n file_based_convert_examples_to_features(predict_examples, label_list,\n FLAGS.max_seq_length, tokenizer,\n predict_file)\n assert len(predict_examples)== num_actual_predict_examples\n tf.logging.info(\"***** Running prediction*****\")\n tf.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(predict_examples), num_actual_predict_examples,\n len(predict_examples) - num_actual_predict_examples)\n tf.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\n\n predict_drop_remainder = True if FLAGS.use_tpu else False\n predict_input_fn = file_based_input_fn_builder(\n input_file=predict_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=predict_drop_remainder)\n\n result = estimator.predict(input_fn=predict_input_fn)\n\n tf.logging.info(\"Sandeep-5\")\n test_file_name=\"fnc_dev_predictinos_at_the_end_of\"+str(FLAGS.num_train_epochs)+\"_trainepochs.tsv\"\n output_predict_file = os.path.join(FLAGS.output_dir, test_file_name)\n tf.logging.info(\"Sandeep-5\")\n tf.logging.info(output_predict_file)\n tf.logging.info(estimator.eval_dir())\n with open(output_predict_file, \"w+\") as writer:\n pass\n os.chmod(output_predict_file, 0o777)\n with tf.gfile.GFile(output_predict_file, \"a+\") as writer:\n num_written_lines = 0\n tf.logging.info(\"****Sandeep*****\")\n tf.logging.info(result)\n tf.logging.info(\"***** Predict results *****\")\n tf.logging.info(\"***** End *****\")\n for (i, prediction) in enumerate(result):\n tf.logging.info(\"inside loop-1\")\n tf.logging.info(i)\n probabilities = prediction[\"probabilities\"]\n tf.logging.info(\"inside loop-2\")\n if i >= num_actual_predict_examples:\n break\n output_line = \"\\t\".join(\n str(class_probability)\n for class_probability in probabilities) + \"\\n\"\n writer.write(output_line)\n num_written_lines += 1\n assert num_written_lines == num_actual_predict_examples\n\n if FLAGS.do_predict:\n predict_examples = processor.get_test_examples(FLAGS.data_dir_cross_domain)\n num_actual_predict_examples = len(predict_examples)\n if FLAGS.use_tpu:\n # TPU requires a fixed batch size for all batches, therefore the number\n # of examples must be a multiple of the batch size, or else examples\n # will get dropped. So we pad with fake examples which are ignored\n # later on.\n while len(predict_examples) % FLAGS.predict_batch_size != 0:\n predict_examples.append(PaddingInputExample())\n\n predict_file = os.path.join(FLAGS.output_dir, \"predict.tf_record\")\n file_based_convert_examples_to_features(predict_examples, label_list,\n FLAGS.max_seq_length, tokenizer,\n predict_file)\n assert len(predict_examples)== num_actual_predict_examples\n tf.logging.info(\"***** Running prediction*****\")\n tf.logging.info(\" Num examples = %d (%d actual, %d padding)\",\n len(predict_examples), num_actual_predict_examples,\n len(predict_examples) - num_actual_predict_examples)\n tf.logging.info(\" Batch size = %d\", FLAGS.predict_batch_size)\n\n predict_drop_remainder = True if FLAGS.use_tpu else False\n predict_input_fn = file_based_input_fn_builder(\n input_file=predict_file,\n seq_length=FLAGS.max_seq_length,\n is_training=False,\n drop_remainder=predict_drop_remainder)\n\n result = estimator.predict(input_fn=predict_input_fn)\n\n tf.logging.info(\"Sandeep-5\")\n test_file_name=\"fnc_test_predictinos_at_the_\"+str(FLAGS.num_train_epochs)+\"_trainepochs.tsv\"\n output_predict_file = os.path.join(FLAGS.output_dir, test_file_name)\n tf.logging.info(\"Sandeep-5\")\n tf.logging.info(output_predict_file)\n tf.logging.info(estimator.eval_dir())\n with open(output_predict_file, \"w+\") as writer:\n pass\n os.chmod(output_predict_file, 0o777)\n with tf.gfile.GFile(output_predict_file, \"a+\") as writer:\n num_written_lines = 0\n tf.logging.info(\"****Sandeep*****\")\n tf.logging.info(result)\n tf.logging.info(\"***** Predict results *****\")\n tf.logging.info(\"***** End *****\")\n for (i, prediction) in enumerate(result):\n tf.logging.info(\"inside loop-1\")\n tf.logging.info(i)\n probabilities = prediction[\"probabilities\"]\n tf.logging.info(\"inside loop-2\")\n if i >= num_actual_predict_examples:\n break\n output_line = \"\\t\".join(\n str(class_probability)\n for class_probability in probabilities) + \"\\n\"\n writer.write(output_line)\n num_written_lines += 1\n #os.chmod(output_predict_file, 0o777)\n assert num_written_lines == num_actual_predict_examples\n\n\nif __name__ == \"__main__\":\n flags.mark_flag_as_required(\"data_dir\")\n flags.mark_flag_as_required(\"task_name\")\n flags.mark_flag_as_required(\"vocab_file\")\n flags.mark_flag_as_required(\"bert_config_file\")\n flags.mark_flag_as_required(\"output_dir\")\n tf.app.run()\n"
] |
[
[
"tensorflow.contrib.cluster_resolver.TPUClusterResolver",
"tensorflow.metrics.accuracy",
"tensorflow.FixedLenFeature",
"tensorflow.nn.log_softmax",
"tensorflow.reduce_sum",
"tensorflow.gfile.GFile",
"tensorflow.cast",
"tensorflow.train.init_from_checkpoint",
"tensorflow.gfile.MakeDirs",
"tensorflow.to_int32",
"tensorflow.contrib.tpu.TPUEstimatorSpec",
"tensorflow.contrib.tpu.TPUEstimator",
"tensorflow.data.TFRecordDataset",
"tensorflow.truncated_normal_initializer",
"tensorflow.python_io.TFRecordWriter",
"tensorflow.logging.set_verbosity",
"tensorflow.trainable_variables",
"tensorflow.parse_single_example",
"tensorflow.argmax",
"tensorflow.app.run",
"tensorflow.nn.dropout",
"tensorflow.metrics.mean",
"tensorflow.matmul",
"tensorflow.gfile.Open",
"tensorflow.shape",
"tensorflow.zeros_initializer",
"tensorflow.logging.info",
"tensorflow.one_hot",
"tensorflow.contrib.tpu.TPUConfig",
"tensorflow.train.Features",
"tensorflow.nn.bias_add",
"tensorflow.nn.softmax",
"tensorflow.constant",
"tensorflow.train.Scaffold",
"tensorflow.reduce_mean",
"tensorflow.flags.DEFINE_string",
"tensorflow.variable_scope"
]
] |
RichardScottOZ/subsurface
|
[
"637217f2f7f5c25c4e83b26e8c89e7e856ad209c"
] |
[
"subsurface/visualization/to_pyvista.py"
] |
[
"from typing import Union\n\nfrom subsurface.structs import PointSet, TriSurf, LineSet, TetraMesh, StructuredGrid\nfrom subsurface.structs.common import Common\nfrom subsurface.structs.errors import PyVistaImportError\nimport numpy as np\n\ntry:\n import pyvista as pv\nexcept ImportError:\n raise ImportError()\n\n\ndef pv_plot(meshes: list,\n image_2d=False,\n plotter_kwargs: dict = None,\n add_mesh_kwargs: dict = None):\n \"\"\"\n\n Args:\n meshes (List[pv.PolyData]):\n image_2d (bool): If True convert plot to matplotlib imshow. This helps for visualizing\n the plot in IDEs\n plotter_kwargs (dict): pyvista.Plotter kwargs\n add_mesh_kwargs (dict): pyvista.add_mesh kwargs\n\n \"\"\"\n\n plotter_kwargs = dict() if plotter_kwargs is None else plotter_kwargs\n add_mesh_kwargs = dict() if add_mesh_kwargs is None else add_mesh_kwargs\n\n p = pv.Plotter(**plotter_kwargs, off_screen=image_2d)\n\n for m in meshes:\n p.add_mesh(m, **add_mesh_kwargs)\n\n if image_2d is False:\n return p.show()\n\n else:\n try:\n import matplotlib.pyplot as plt\n except ImportError:\n raise ImportError('Matplotlib is necessary for generating a 2D image.')\n img = p.plot(screenshot=True)\n fig = plt.imshow(img[1])\n plt.axis('off')\n plt.show()\n p.close()\n return fig\n\n\ndef to_pyvista_points(point_set: PointSet):\n \"\"\"Create pyvista.PolyData from PointSet\n\n Args:\n point_set (PointSet): Class for pointset based data structures.\n\n Returns:\n pv.PolyData\n \"\"\"\n poly = pv.PolyData(point_set.data.vertex)\n poly.point_arrays.update(point_set.data.attributes_to_dict)\n\n return poly\n\n\ndef to_pyvista_mesh(unstructured_element: Union[TriSurf]) -> pv.PolyData:\n \"\"\"Create planar surface PolyData from unstructured element such as TriSurf\n \"\"\"\n nve = unstructured_element.data.n_vertex_per_element\n vertices = unstructured_element.data.vertex\n cells = np.c_[np.full(unstructured_element.data.n_elements, nve),\n unstructured_element.data.cells]\n mesh = pv.PolyData(vertices, cells)\n mesh.cell_arrays.update(unstructured_element.data.attributes_to_dict)\n mesh.point_arrays.update(unstructured_element.data.points_attributes)\n return mesh\n\n\ndef to_pyvista_line(line_set: LineSet, as_tube=True, radius=None,\n spline=False, n_interp_points=1000):\n \"\"\"Create pyvista PolyData for 1D lines\n\n Args:\n line_set:\n as_tube (bool):\n radius (float): radius of the tube\n spline: NotImplemented\n n_interp_points: NotImplemented\n\n Returns:\n pv.PolyData\n \"\"\"\n nve = line_set.data.n_vertex_per_element\n vertices = line_set.data.vertex\n cells = np.c_[np.full(line_set.data.n_elements, nve),\n line_set.data.cells]\n if spline is False:\n mesh = pv.PolyData()\n mesh.points = vertices\n mesh.lines = cells\n else:\n raise NotImplementedError\n # mesh = pv.Spline(ver)\n mesh.cell_arrays.update(line_set.data.attributes_to_dict)\n if as_tube is True:\n return mesh.tube(radius=radius)\n else:\n return mesh\n\n\ndef to_pyvista_tetra(tetra_mesh: TetraMesh):\n \"\"\"Create pyvista.UnstructuredGrid\"\"\"\n vertices = tetra_mesh.data.vertex\n tets = tetra_mesh.data.cells\n cells = np.c_[np.full(len(tets), 4), tets]\n import vtk\n ctypes = np.array([vtk.VTK_TETRA, ], np.int32)\n mesh = pv.UnstructuredGrid(cells, ctypes, vertices)\n mesh.cell_arrays.update(tetra_mesh.data.attributes_to_dict)\n return mesh\n\n\ndef to_pyvista_grid(structured_grid: StructuredGrid, attribute: str):\n ndim = structured_grid.ds.data[attribute].ndim\n if ndim == 2:\n meshgrid = structured_grid.meshgrid_2d(attribute)\n elif ndim == 3:\n meshgrid = structured_grid.meshgrid_3d\n else:\n raise AttributeError('The DataArray does not have valid dimensionality.')\n\n mesh = pv.StructuredGrid(*meshgrid)\n mesh.point_arrays.update({attribute: structured_grid.ds.data[attribute].values.ravel()})\n\n return mesh"
] |
[
[
"matplotlib.pyplot.imshow",
"numpy.full",
"matplotlib.pyplot.axis",
"numpy.array",
"matplotlib.pyplot.show"
]
] |
zhang677/A-case-study-of-GPR
|
[
"a85c59d8bf043a5b1201e88604a310ddf2627384"
] |
[
"main.py"
] |
[
"import pandas as pd\nimport torch\nimport numpy as np\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport math\nimport gpytorch\nimport argparse\nmatplotlib.use('Agg')\n\n\nclass ExactGPModel(gpytorch.models.ExactGP):\n def __init__(self, train_x, train_y, likelihood):\n super(ExactGPModel, self).__init__(train_x, train_y, likelihood)\n self.mean_module = gpytorch.means.ConstantMean()\n self.covar_module = gpytorch.kernels.ScaleKernel(gpytorch.kernels.RBFKernel()+ gpytorch.kernels.MaternKernel())\n\n def forward(self, x):\n mean_x = self.mean_module(x)\n covar_x = self.covar_module(x)\n return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)\n\ndef std_norm(y_total):\n # y_total: np.array\n y_std = np.std(y_total)\n y_mean = sum(y_total)/len(y_total)\n y_norm = (y_total-y_mean)/y_std\n # y_norm: torch.tensor\n return (y_std,y_mean,y_norm)\n\ndef std_denorm(y_std, y_mean, y_norm):\n y_norm = np.array(y_norm)\n return y_norm*y_std + y_mean\n\ndef train_test_split(x_norm,y_norm,rate=0.9):\n idx = np.int(np.floor(rate*len(x_norm)))\n print(idx)\n X_train = x_norm[0:idx]\n X_test = x_norm[idx:]\n y_train = y_norm[0:idx]\n y_test = y_norm[idx:] \n #from sklearn.model_selection import train_test_split\n #X_train, X_test, y_train, y_test = train_test_split(x_norm, y_norm, test_size=rate, random_state=42)\n return (X_train, X_test, y_train, y_test)\ndef get_mape(y_true, y_pred):\n \"\"\"\n Compute mean absolute percentage error (MAPE)\n \"\"\"\n y_true, y_pred = np.array(y_true), np.array(y_pred)\n return np.mean(np.abs((y_true - y_pred) / y_true)) * 100\n\nif __name__ == \"__main__\" :\n parser = argparse.ArgumentParser(description='GPR')\n parser.add_argument(\"--train\", action='store_true', default=False,\n help=\"True to train\")\n parser.add_argument(\"--test\", action='store_true', default=False,\n help=\"True to test\")\n parser.add_argument(\"--val\", action='store_true', default=False,\n help=\"True to validate\") \n parser.add_argument(\"--init\", action='store_true', default=False,\n help=\"True to plot initially\")\n parser.add_argument(\"--inn\", type=str, default='', \n help=\"load Model file name appendix\")\n parser.add_argument(\"--out\", type=str, default='', \n help=\"output Model file name appendix\") \n parser.add_argument(\"--lr\", type=float, default=0.5, \n help=\"learning rate\")\n parser.add_argument(\"--first\", action='store_true', default=False,\n help=\"The first time to train\")\n parser.add_argument(\"--all\", action='store_true', default=False,\n help=\"Plot val and test\")\n parser.add_argument(\"--iter\", type = int, default=10,help=\"Training iterations\")\n parser.add_argument(\"--dataset\", type = str, default='IXIC',help=\"Cooperation's name\")\n\n \n args = parser.parse_args()\n\n # read the data and init the date\n\n df = pd.read_csv(args.dataset+'.csv',index_col=0)\n y_total = np.array(df['Adj Close'])\n x_total = np.linspace(0, y_total.shape[0]-1,y_total.shape[0])\n print(y_total.shape)\n\n # split the train and test\n\n x_train, x_test, y_train, y_test = train_test_split(x_total, y_total,0.9)\n\n # normalize\n\n y_std,y_mean,y_norm = std_norm(y_train)\n x_std,x_mean,x_norm = std_norm(x_train)\n x_test = (x_test-x_mean)/x_std\n y_test = (y_test-y_mean)/y_std\n\n if args.init:\n # plot the train and test\n\n f, ax = plt.subplots(1, 1, figsize=(6, 5))\n ax.plot(x_total,y_total,'k')\n plt.xlabel('Days')\n plt.ylabel('Index')\n plt.title(args.dataset)\n plt.savefig('raw'+args.dataset+'.png')\n f, ax = plt.subplots(1, 1, figsize=(6, 5))\n ax.plot(x_norm,y_norm,'k')\n ax.plot(x_test,y_test,'r')\n plt.xlabel('Days')\n plt.ylabel('Index')\n plt.title(args.dataset)\n plt.savefig('train'+args.dataset+'.png')\n\n # transform to torch tensor\n\n x_train = torch.tensor(x_norm).float()\n y_train = torch.tensor(y_norm).float()\n x_test = torch.tensor(x_test).float()\n y_test = torch.tensor(y_test).float()\n\n # initialize likelihood and model\n likelihood = gpytorch.likelihoods.GaussianLikelihood()\n model = ExactGPModel(x_train, y_train, likelihood)\n if args.train:\n f = open(args.out+'.txt','w')\n f.write(args.dataset+' '+'iter:'+str(args.iter)+';'+'lr:'+str(args.lr)+'\\n')\n training_iter = args.iter\n if not args.first:\n state_dict = torch.load('model_state'+args.inn+'.pth')\n model = ExactGPModel(x_train, y_train, likelihood) # Create a new GP model\n if not args.first:\n model.load_state_dict(state_dict)\n # Find optimal model hyperparameters\n model.train()\n likelihood.train()\n\n # Use the adam optimizer\n optimizer = torch.optim.Adam(model.parameters(), lr=0.3) # Includes GaussianLikelihood parameters\n\n # \"Loss\" for GPs - the marginal log likelihood\n mll = gpytorch.mlls.ExactMarginalLogLikelihood(likelihood, model)\n\n for i in range(training_iter):\n # Zero gradients from previous iteration\n optimizer.zero_grad()\n # Output from model\n output = model(x_train)\n # Calc loss and backprop gradients\n loss = -mll(output, y_train)\n loss.backward()\n# print('Iter %d/%d - Loss: %.3f lengthscale: %.3f noise: %.3f' % (\n# i + 1, training_iter, loss.item(),\n# model.covar_module.base_kernel.lengthscale.item(),\n# model.likelihood.noise.item()\n# ))\n print('Iter %d/%d - Loss: %.3f' % (i + 1, training_iter, loss.item()),file=f)\n optimizer.step()\n torch.save(model.state_dict(), 'model_state'+args.out+'.pth')\n\n if args.test:\n state_dict = torch.load('model_state'+args.inn+'.pth')\n model = ExactGPModel(x_train, y_train, likelihood) # Create a new GP model\n model.load_state_dict(state_dict)\n\n model.eval()\n likelihood.eval()\n\n with torch.no_grad():\n y_pred = model(x_test)\n f, ax = plt.subplots(1, 1, figsize=(8, 6))\n # Get upper and lower confidence bounds\n lower, upper = y_pred.confidence_region()\n # Plot training data as black stars\n ax.plot(x_test.numpy(), y_test.numpy(), 'k')\n # Plot predictive means as blue line\n ax.plot(x_test.numpy(), y_pred.mean.numpy(), 'b')\n # Shade between the lower and upper confidence bounds\n ax.fill_between(x_test.numpy(), lower.numpy(), upper.numpy(), alpha=0.5)\n ax.legend(['Observed Data', 'Mean', 'Confidence'])\n mape = get_mape(y_test,y_pred.mean)\n plt.title(args.dataset+' mape:%0.3f%%'%mape)\n plt.xlabel('Days')\n plt.ylabel('Index')\n plt.savefig('test'+args.inn+'.png')\n \n\n if args.val:\n state_dict = torch.load('model_state'+args.inn+'.pth')\n model = ExactGPModel(x_train, y_train, likelihood) # Create a new GP model\n model.load_state_dict(state_dict)\n\n model.eval()\n likelihood.eval()\n\n with torch.no_grad():\n y_pred = model(x_train)\n f, ax = plt.subplots(1, 1, figsize=(8, 6))\n # Get upper and lower confidence bounds\n lower, upper = y_pred.confidence_region()\n # Plot training data as black stars\n ax.plot(x_train.numpy(), y_train.numpy(), 'k')\n # Plot predictive means as blue line\n ax.plot(x_train.numpy(), y_pred.mean.numpy(), 'b')\n # Shade between the lower and upper confidence bounds\n ax.fill_between(x_train.numpy(), lower.numpy(), upper.numpy(), alpha=0.5)\n \n #ax.set_ylim([-4, 4])\n mape = get_mape(y_train,y_pred.mean)\n plt.title(args.dataset+' mape:%0.3f%%'%mape)\n ax.legend(['Observed Data', 'Mean', 'Confidence'])\n plt.savefig('val'+args.inn+'.png')\n \n if args.all:\n state_dict = torch.load('model_state'+args.inn+'.pth')\n model = ExactGPModel(x_train, y_train, likelihood) # Create a new GP model\n model.load_state_dict(state_dict)\n\n model.eval()\n likelihood.eval()\n\n with torch.no_grad():\n y_pred = model(x_train)\n f, ax = plt.subplots(1, 1, figsize=(8, 6))\n # Get upper and lower confidence bounds\n lower, upper = y_pred.confidence_region()\n # Plot training data as black stars\n ax.plot(x_train.numpy(), y_train.numpy(), 'k')\n # Plot predictive means as blue line\n ax.plot(x_train.numpy(), y_pred.mean.numpy(), 'b')\n # Shade between the lower and upper confidence bounds\n ax.fill_between(x_train.numpy(), lower.numpy(), upper.numpy(), alpha=0.5)\n #ax.set_ylim([-4, 4])\n y_pred = model(x_test)\n lower, upper = y_pred.confidence_region()\n ax.plot(x_test.numpy(), y_test.numpy(), 'r')\n ax.plot(x_test.numpy(), y_pred.mean.numpy(), 'g')\n ax.fill_between(x_test.numpy(), lower.numpy(), upper.numpy(), alpha=0.5)\n ax.legend(['Observed Data', 'Mean', 'Test Data', 'Predict Mean','Confidence', 'Predict Confidence'])\n plt.title(args.dataset)\n plt.xlabel('Days')\n plt.ylabel('Index')\n plt.savefig('all'+args.inn+'.png') \n\n\n\n"
] |
[
[
"pandas.read_csv",
"numpy.abs",
"numpy.linspace",
"matplotlib.pyplot.title",
"torch.load",
"matplotlib.use",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"torch.tensor",
"numpy.std",
"torch.no_grad",
"matplotlib.pyplot.xlabel",
"numpy.array",
"matplotlib.pyplot.ylabel"
]
] |
wokas36/RWK
|
[
"c44d3d650f0704af49fe41969de0848563e63f65"
] |
[
"lib/sinkhorn_algorithms.py"
] |
[
"import numpy as np\n\nclass NanInDualError(Exception):\n pass\n\ndef sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs):\n \"\"\"\n Solve the entropic regularization optimal transport problem and return the OT matrix\n The function solves the following optimization problem:\n .. math::\n \\gamma = arg\\min_\\gamma <\\gamma,M>_F + reg\\cdot\\Omega(\\gamma)\n s.t. \\gamma 1 = a\n \\gamma^T 1= b\n \\gamma\\geq 0\n where :\n - M is the (ns,nt) metric cost matrix\n - :math:`\\Omega` is the entropic regularization term :math:`\\Omega(\\gamma)=\\sum_{i,j} \\gamma_{i,j}\\log(\\gamma_{i,j})`\n - a and b are source and target weights (sum to 1)\n The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_\n Parameters\n ----------\n a : np.ndarray (ns,)\n samples weights in the source domain\n b : np.ndarray (nt,) or np.ndarray (nt,nbb)\n samples in the target domain, compute sinkhorn with multiple targets\n and fixed M if b is a matrix (return OT loss + dual variables in log)\n M : np.ndarray (ns,nt)\n loss matrix\n reg : float\n Regularization term >0\n method : str\n method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or\n 'sinkhorn_epsilon_scaling', see those function for specific parameters\n numItermax : int, optional\n Max number of iterations\n stopThr : float, optional\n Stop threshol on error (>0)\n verbose : bool, optional\n Print information along iterations\n log : bool, optional\n record log if True\n Returns\n -------\n gamma : (ns x nt) ndarray\n Optimal transportation matrix for the given parameters\n log : dict\n log dictionary return only if log==True in parameters\n Examples\n --------\n >>> import ot\n >>> a=[.5,.5]\n >>> b=[.5,.5]\n >>> M=[[0.,1.],[1.,0.]]\n >>> ot.sinkhorn(a,b,M,1)\n array([[ 0.36552929, 0.13447071],\n [ 0.13447071, 0.36552929]])\n References\n ----------\n .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013\n .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.\n .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.\n See Also\n --------\n ot.lp.emd : Unregularized OT\n ot.optim.cg : General regularized OT\n ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]\n ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]\n ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]\n \"\"\"\n\n if method.lower() == 'sinkhorn':\n def sink():\n return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,\n stopThr=stopThr, verbose=verbose, log=log, **kwargs)\n elif method.lower() == 'sinkhorn_stabilized':\n def sink():\n return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,\n stopThr=stopThr, verbose=verbose, log=log, **kwargs)\n elif method.lower() == 'sinkhorn_epsilon_scaling':\n def sink():\n return sinkhorn_epsilon_scaling(\n a, b, M, reg, numItermax=numItermax,\n stopThr=stopThr, verbose=verbose, log=log, **kwargs)\n else:\n print('Warning : unknown method using classic Sinkhorn Knopp')\n\n def sink():\n return sinkhorn_knopp(a, b, M, reg, **kwargs)\n\n return sink()\n\n\ndef sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs):\n \"\"\"\n Solve the entropic regularization optimal transport problem and return the loss\n The function solves the following optimization problem:\n .. math::\n W = \\min_\\gamma <\\gamma,M>_F + reg\\cdot\\Omega(\\gamma)\n s.t. \\gamma 1 = a\n \\gamma^T 1= b\n \\gamma\\geq 0\n where :\n - M is the (ns,nt) metric cost matrix\n - :math:`\\Omega` is the entropic regularization term :math:`\\Omega(\\gamma)=\\sum_{i,j} \\gamma_{i,j}\\log(\\gamma_{i,j})`\n - a and b are source and target weights (sum to 1)\n The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_\n Parameters\n ----------\n a : np.ndarray (ns,)\n samples weights in the source domain\n b : np.ndarray (nt,) or np.ndarray (nt,nbb)\n samples in the target domain, compute sinkhorn with multiple targets\n and fixed M if b is a matrix (return OT loss + dual variables in log)\n M : np.ndarray (ns,nt)\n loss matrix\n reg : float\n Regularization term >0\n method : str\n method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or\n 'sinkhorn_epsilon_scaling', see those function for specific parameters\n numItermax : int, optional\n Max number of iterations\n stopThr : float, optional\n Stop threshol on error (>0)\n verbose : bool, optional\n Print information along iterations\n log : bool, optional\n record log if True\n Returns\n -------\n W : (nt) ndarray or float\n Optimal transportation matrix for the given parameters\n log : dict\n log dictionary return only if log==True in parameters\n Examples\n --------\n >>> import ot\n >>> a=[.5,.5]\n >>> b=[.5,.5]\n >>> M=[[0.,1.],[1.,0.]]\n >>> ot.sinkhorn2(a,b,M,1)\n array([ 0.26894142])\n References\n ----------\n .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013\n .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.\n .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.\n See Also\n --------\n ot.lp.emd : Unregularized OT\n ot.optim.cg : General regularized OT\n ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2]\n ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10]\n ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]\n \"\"\"\n\n if method.lower() == 'sinkhorn':\n def sink():\n return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax,\n stopThr=stopThr, verbose=verbose, log=log, **kwargs)\n elif method.lower() == 'sinkhorn_stabilized':\n def sink():\n return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax,\n stopThr=stopThr, verbose=verbose, log=log, **kwargs)\n elif method.lower() == 'sinkhorn_epsilon_scaling':\n def sink():\n return sinkhorn_epsilon_scaling(\n a, b, M, reg, numItermax=numItermax,\n stopThr=stopThr, verbose=verbose, log=log, **kwargs)\n else:\n print('Warning : unknown method using classic Sinkhorn Knopp')\n\n def sink():\n return sinkhorn_knopp(a, b, M, reg, **kwargs)\n\n b = np.asarray(b, dtype=np.float64)\n if len(b.shape) < 2:\n b = b.reshape((-1, 1))\n\n return sink()\n\ndef sinkhorn_scaling(a,b,K,numItermax=1000, stopThr=1e-9, verbose=False,log=False,always_raise=False, **kwargs):\n a = np.asarray(a, dtype=np.float64)\n b = np.asarray(b, dtype=np.float64)\n K = np.asarray(K, dtype=np.float64)\n\n # init data\n Nini = len(a)\n Nfin = len(b)\n\n if len(b.shape) > 1:\n nbb = b.shape[1]\n else:\n nbb = 0\n\n if log:\n log = {'err': []}\n\n # we assume that no distances are null except those of the diagonal of\n # distances\n if nbb:\n u = np.ones((Nini, nbb)) / Nini\n v = np.ones((Nfin, nbb)) / Nfin\n else:\n u = np.ones(Nini) / Nini\n v = np.ones(Nfin) / Nfin\n\n # print(reg)\n # print(np.min(K))\n\n Kp = (1 / a).reshape(-1, 1) * K\n cpt = 0\n err = 1\n while (err > stopThr and cpt < numItermax):\n uprev = u\n vprev = v\n KtransposeU = np.dot(K.T, u)\n v = np.divide(b, KtransposeU)\n u = 1. / np.dot(Kp, v)\n\n zero_in_transp=np.any(KtransposeU == 0)\n nan_in_dual= np.any(np.isnan(u)) or np.any(np.isnan(v))\n inf_in_dual=np.any(np.isinf(u)) or np.any(np.isinf(v))\n if zero_in_transp or nan_in_dual or inf_in_dual:\n # we have reached the machine precision\n # come back to previous solution and quit loop\n print('Warning: numerical errors at iteration in sinkhorn_scaling', cpt)\n #if zero_in_transp:\n #print('Zero in transp : ',KtransposeU)\n #if nan_in_dual:\n #print('Nan in dual')\n #print('u : ',u)\n #print('v : ',v)\n #print('KtransposeU ',KtransposeU)\n #print('K ',K)\n #print('M ',M)\n\n # if always_raise:\n # raise NanInDualError\n #if inf_in_dual:\n # print('Inf in dual')\n u = uprev\n v = vprev\n\n break\n if cpt % 10 == 0:\n # we can speed up the process by checking for the error only all\n # the 10th iterations\n if nbb:\n err = np.sum((u - uprev)**2) / np.sum((u)**2) + \\\n np.sum((v - vprev)**2) / np.sum((v)**2)\n else:\n transp = u.reshape(-1, 1) * (K * v)\n err = np.linalg.norm((np.sum(transp, axis=0) - b))**2\n if log:\n log['err'].append(err)\n\n if verbose:\n if cpt % 200 == 0:\n print(\n '{:5s}|{:12s}'.format('It.', 'Err') + '\\n' + '-' * 19)\n print('{:5d}|{:8e}|'.format(cpt, err))\n cpt = cpt + 1\n if log:\n log['u'] = u\n log['v'] = v\n\n if nbb: # return only loss\n res = np.zeros((nbb))\n for i in range(nbb):\n res[i] = np.sum(\n u[:, i].reshape((-1, 1)) * K * v[:, i].reshape((1, -1)) * M)\n if log:\n return res, log\n else:\n return res\n\n else: # return OT matrix\n\n if log:\n return u.reshape((-1, 1)) * K * v.reshape((1, -1)), log\n else:\n return u.reshape((-1, 1)) * K * v.reshape((1, -1))\n\ndef sinkhorn_knopp(a, b, M, reg, numItermax=1000, stopThr=1e-9, verbose=False,log=False,always_raise=False, **kwargs):\n \"\"\"\n Solve the entropic regularization optimal transport problem and return the OT matrix\n The function solves the following optimization problem:\n .. math::\n \\gamma = arg\\min_\\gamma <\\gamma,M>_F + reg\\cdot\\Omega(\\gamma)\n s.t. \\gamma 1 = a\n \\gamma^T 1= b\n \\gamma\\geq 0\n where :\n - M is the (ns,nt) metric cost matrix\n - :math:`\\Omega` is the entropic regularization term :math:`\\Omega(\\gamma)=\\sum_{i,j} \\gamma_{i,j}\\log(\\gamma_{i,j})`\n - a and b are source and target weights (sum to 1)\n The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_\n Parameters\n ----------\n a : np.ndarray (ns,)\n samples weights in the source domain\n b : np.ndarray (nt,) or np.ndarray (nt,nbb)\n samples in the target domain, compute sinkhorn with multiple targets\n and fixed M if b is a matrix (return OT loss + dual variables in log)\n M : np.ndarray (ns,nt)\n loss matrix\n reg : float\n Regularization term >0\n numItermax : int, optional\n Max number of iterations\n stopThr : float, optional\n Stop threshol on error (>0)\n verbose : bool, optional\n Print information along iterations\n log : bool, optional\n record log if True\n Returns\n -------\n gamma : (ns x nt) ndarray\n Optimal transportation matrix for the given parameters\n log : dict\n log dictionary return only if log==True in parameters\n Examples\n --------\n >>> import ot\n >>> a=[.5,.5]\n >>> b=[.5,.5]\n >>> M=[[0.,1.],[1.,0.]]\n >>> ot.sinkhorn(a,b,M,1)\n array([[ 0.36552929, 0.13447071],\n [ 0.13447071, 0.36552929]])\n References\n ----------\n .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013\n See Also\n --------\n ot.lp.emd : Unregularized OT\n ot.optim.cg : General regularized OT\n \"\"\"\n\n a = np.asarray(a, dtype=np.float64)\n b = np.asarray(b, dtype=np.float64)\n M = np.asarray(M, dtype=np.float64)\n\n if len(a) == 0:\n a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0]\n if len(b) == 0:\n b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1]\n\n # init data\n Nini = len(a)\n Nfin = len(b)\n\n if len(b.shape) > 1:\n nbb = b.shape[1]\n else:\n nbb = 0\n\n if log:\n log = {'err': []}\n\n # we assume that no distances are null except those of the diagonal of\n # distances\n if nbb:\n u = np.ones((Nini, nbb)) / Nini\n v = np.ones((Nfin, nbb)) / Nfin\n else:\n u = np.ones(Nini) / Nini\n v = np.ones(Nfin) / Nfin\n\n # print(reg)\n\n K = np.exp(-M / reg)\n # print(np.min(K))\n\n Kp = (1 / a).reshape(-1, 1) * K\n cpt = 0\n err = 1\n while (err > stopThr and cpt < numItermax):\n uprev = u\n vprev = v\n KtransposeU = np.dot(K.T, u)\n v = np.divide(b, KtransposeU)\n u = 1. / np.dot(Kp, v)\n\n zero_in_transp=np.any(KtransposeU == 0)\n nan_in_dual= np.any(np.isnan(u)) or np.any(np.isnan(v))\n inf_in_dual=np.any(np.isinf(u)) or np.any(np.isinf(v))\n if zero_in_transp or nan_in_dual or inf_in_dual:\n # we have reached the machine precision\n # come back to previous solution and quit loop\n print('Warning: numerical errors at iteration', cpt)\n #if zero_in_transp:\n #print('Zero in transp : ',KtransposeU)\n #if nan_in_dual:\n #print('Nan in dual')\n #print('u : ',u)\n #print('v : ',v)\n #print('KtransposeU ',KtransposeU)\n #print('K ',K)\n #print('M ',M)\n\n # if always_raise:\n # raise NanInDualError\n #if inf_in_dual:\n # print('Inf in dual')\n u = uprev\n v = vprev\n\n break\n if cpt % 10 == 0:\n # we can speed up the process by checking for the error only all\n # the 10th iterations\n if nbb:\n err = np.sum((u - uprev)**2) / np.sum((u)**2) + \\\n np.sum((v - vprev)**2) / np.sum((v)**2)\n else:\n transp = u.reshape(-1, 1) * (K * v)\n err = np.linalg.norm((np.sum(transp, axis=0) - b))**2\n if log:\n log['err'].append(err)\n\n if verbose:\n if cpt % 200 == 0:\n print(\n '{:5s}|{:12s}'.format('It.', 'Err') + '\\n' + '-' * 19)\n print('{:5d}|{:8e}|'.format(cpt, err))\n cpt = cpt + 1\n if log:\n log['u'] = u\n log['v'] = v\n\n if nbb: # return only loss\n res = np.zeros((nbb))\n for i in range(nbb):\n res[i] = np.sum(\n u[:, i].reshape((-1, 1)) * K * v[:, i].reshape((1, -1)) * M)\n if log:\n return res, log\n else:\n return res\n\n else: # return OT matrix\n\n if log:\n return u.reshape((-1, 1)) * K * v.reshape((1, -1)), log\n else:\n return u.reshape((-1, 1)) * K * v.reshape((1, -1))\n\n\ndef sinkhorn_stabilized(a, b, M, reg, numItermax=1000, tau=1e3, stopThr=1e-9, warmstart=None, verbose=False, print_period=20, log=False, **kwargs):\n \"\"\"\n Solve the entropic regularization OT problem with log stabilization\n The function solves the following optimization problem:\n .. math::\n \\gamma = arg\\min_\\gamma <\\gamma,M>_F + reg\\cdot\\Omega(\\gamma)\n s.t. \\gamma 1 = a\n \\gamma^T 1= b\n \\gamma\\geq 0\n where :\n - M is the (ns,nt) metric cost matrix\n - :math:`\\Omega` is the entropic regularization term :math:`\\Omega(\\gamma)=\\sum_{i,j} \\gamma_{i,j}\\log(\\gamma_{i,j})`\n - a and b are source and target weights (sum to 1)\n The algorithm used for solving the problem is the Sinkhorn-Knopp matrix\n scaling algorithm as proposed in [2]_ but with the log stabilization\n proposed in [10]_ an defined in [9]_ (Algo 3.1) .\n Parameters\n ----------\n a : np.ndarray (ns,)\n samples weights in the source domain\n b : np.ndarray (nt,)\n samples in the target domain\n M : np.ndarray (ns,nt)\n loss matrix\n reg : float\n Regularization term >0\n tau : float\n thershold for max value in u or v for log scaling\n warmstart : tible of vectors\n if given then sarting values for alpha an beta log scalings\n numItermax : int, optional\n Max number of iterations\n stopThr : float, optional\n Stop threshol on error (>0)\n verbose : bool, optional\n Print information along iterations\n log : bool, optional\n record log if True\n Returns\n -------\n gamma : (ns x nt) ndarray\n Optimal transportation matrix for the given parameters\n log : dict\n log dictionary return only if log==True in parameters\n Examples\n --------\n >>> import ot\n >>> a=[.5,.5]\n >>> b=[.5,.5]\n >>> M=[[0.,1.],[1.,0.]]\n >>> ot.bregman.sinkhorn_stabilized(a,b,M,1)\n array([[ 0.36552929, 0.13447071],\n [ 0.13447071, 0.36552929]])\n References\n ----------\n .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013\n .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.\n .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.\n See Also\n --------\n ot.lp.emd : Unregularized OT\n ot.optim.cg : General regularized OT\n \"\"\"\n\n a = np.asarray(a, dtype=np.float64)\n b = np.asarray(b, dtype=np.float64)\n M = np.asarray(M, dtype=np.float64)\n\n if len(a) == 0:\n a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0]\n if len(b) == 0:\n b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1]\n\n # test if multiple target\n if len(b.shape) > 1:\n nbb = b.shape[1]\n a = a[:, np.newaxis]\n else:\n nbb = 0\n\n # init data\n na = len(a)\n nb = len(b)\n\n cpt = 0\n if log:\n log = {'err': []}\n\n # we assume that no distances are null except those of the diagonal of\n # distances\n if warmstart is None:\n alpha, beta = np.zeros(na), np.zeros(nb)\n else:\n alpha, beta = warmstart\n\n if nbb:\n u, v = np.ones((na, nbb)) / na, np.ones((nb, nbb)) / nb\n else:\n u, v = np.ones(na) / na, np.ones(nb) / nb\n\n def get_K(alpha, beta):\n \"\"\"log space computation\"\"\"\n return np.exp(-(M - alpha.reshape((na, 1)) - beta.reshape((1, nb))) / reg)\n\n def get_Gamma(alpha, beta, u, v):\n \"\"\"log space gamma computation\"\"\"\n return np.exp(-(M - alpha.reshape((na, 1)) - beta.reshape((1, nb))) / reg + np.log(u.reshape((na, 1))) + np.log(v.reshape((1, nb))))\n\n # print(np.min(K))\n\n K = get_K(alpha, beta)\n transp = K\n loop = 1\n cpt = 0\n err = 1\n while loop:\n\n uprev = u\n vprev = v\n\n # sinkhorn update\n v = b / (np.dot(K.T, u) + 1e-16)\n u = a / (np.dot(K, v) + 1e-16)\n\n # remove numerical problems and store them in K\n if np.abs(u).max() > tau or np.abs(v).max() > tau:\n if nbb:\n alpha, beta = alpha + reg * \\\n np.max(np.log(u), 1), beta + reg * np.max(np.log(v))\n else:\n alpha, beta = alpha + reg * np.log(u), beta + reg * np.log(v)\n if nbb:\n u, v = np.ones((na, nbb)) / na, np.ones((nb, nbb)) / nb\n else:\n u, v = np.ones(na) / na, np.ones(nb) / nb\n K = get_K(alpha, beta)\n\n if cpt % print_period == 0:\n # we can speed up the process by checking for the error only all\n # the 10th iterations\n if nbb:\n err = np.sum((u - uprev)**2) / np.sum((u)**2) + \\\n np.sum((v - vprev)**2) / np.sum((v)**2)\n else:\n transp = get_Gamma(alpha, beta, u, v)\n err = np.linalg.norm((np.sum(transp, axis=0) - b))**2\n if log:\n log['err'].append(err)\n\n if verbose:\n if cpt % (print_period * 20) == 0:\n print(\n '{:5s}|{:12s}'.format('It.', 'Err') + '\\n' + '-' * 19)\n print('{:5d}|{:8e}|'.format(cpt, err))\n\n if err <= stopThr:\n loop = False\n\n if cpt >= numItermax:\n loop = False\n\n if np.any(np.isnan(u)) or np.any(np.isnan(v)):\n # we have reached the machine precision\n # come back to previous solution and quit loop\n print('u : ',u)\n print('v : ',v)\n print('K ',K)\n print('M ',M)\n \n print('Warning: numerical errors at iteration', cpt)\n u = uprev\n v = vprev\n\n break\n\n cpt = cpt + 1\n\n # print('err=',err,' cpt=',cpt)\n if log:\n log['logu'] = alpha / reg + np.log(u)\n log['logv'] = beta / reg + np.log(v)\n log['alpha'] = alpha + reg * np.log(u)\n log['beta'] = beta + reg * np.log(v)\n log['warmstart'] = (log['alpha'], log['beta'])\n if nbb:\n res = np.zeros((nbb))\n for i in range(nbb):\n res[i] = np.sum(get_Gamma(alpha, beta, u[:, i], v[:, i]) * M)\n return res, log\n\n else:\n return get_Gamma(alpha, beta, u, v), log\n else:\n if nbb:\n res = np.zeros((nbb))\n for i in range(nbb):\n res[i] = np.sum(get_Gamma(alpha, beta, u[:, i], v[:, i]) * M)\n return res\n else:\n return get_Gamma(alpha, beta, u, v)\n\n\ndef sinkhorn_epsilon_scaling(a, b, M, reg, numItermax=100, epsilon0=1e4, numInnerItermax=100, tau=1e3, stopThr=1e-9, warmstart=None, verbose=False, print_period=10, log=False, **kwargs):\n \"\"\"\n Solve the entropic regularization optimal transport problem with log\n stabilization and epsilon scaling.\n The function solves the following optimization problem:\n .. math::\n \\gamma = arg\\min_\\gamma <\\gamma,M>_F + reg\\cdot\\Omega(\\gamma)\n s.t. \\gamma 1 = a\n \\gamma^T 1= b\n \\gamma\\geq 0\n where :\n - M is the (ns,nt) metric cost matrix\n - :math:`\\Omega` is the entropic regularization term :math:`\\Omega(\\gamma)=\\sum_{i,j} \\gamma_{i,j}\\log(\\gamma_{i,j})`\n - a and b are source and target weights (sum to 1)\n The algorithm used for solving the problem is the Sinkhorn-Knopp matrix\n scaling algorithm as proposed in [2]_ but with the log stabilization\n proposed in [10]_ and the log scaling proposed in [9]_ algorithm 3.2\n Parameters\n ----------\n a : np.ndarray (ns,)\n samples weights in the source domain\n b : np.ndarray (nt,)\n samples in the target domain\n M : np.ndarray (ns,nt)\n loss matrix\n reg : float\n Regularization term >0\n tau : float\n thershold for max value in u or v for log scaling\n tau : float\n thershold for max value in u or v for log scaling\n warmstart : tible of vectors\n if given then sarting values for alpha an beta log scalings\n numItermax : int, optional\n Max number of iterations\n numInnerItermax : int, optional\n Max number of iterationsin the inner slog stabilized sinkhorn\n epsilon0 : int, optional\n first epsilon regularization value (then exponential decrease to reg)\n stopThr : float, optional\n Stop threshol on error (>0)\n verbose : bool, optional\n Print information along iterations\n log : bool, optional\n record log if True\n Returns\n -------\n gamma : (ns x nt) ndarray\n Optimal transportation matrix for the given parameters\n log : dict\n log dictionary return only if log==True in parameters\n Examples\n --------\n >>> import ot\n >>> a=[.5,.5]\n >>> b=[.5,.5]\n >>> M=[[0.,1.],[1.,0.]]\n >>> ot.bregman.sinkhorn_epsilon_scaling(a,b,M,1)\n array([[ 0.36552929, 0.13447071],\n [ 0.13447071, 0.36552929]])\n References\n ----------\n .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013\n .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519.\n See Also\n --------\n ot.lp.emd : Unregularized OT\n ot.optim.cg : General regularized OT\n \"\"\"\n\n a = np.asarray(a, dtype=np.float64)\n b = np.asarray(b, dtype=np.float64)\n M = np.asarray(M, dtype=np.float64)\n\n if len(a) == 0:\n a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0]\n if len(b) == 0:\n b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1]\n\n # init data\n na = len(a)\n nb = len(b)\n\n # nrelative umerical precision with 64 bits\n numItermin = 35\n numItermax = max(numItermin, numItermax) # ensure that last velue is exact\n\n cpt = 0\n if log:\n log = {'err': []}\n\n # we assume that no distances are null except those of the diagonal of\n # distances\n if warmstart is None:\n alpha, beta = np.zeros(na), np.zeros(nb)\n else:\n alpha, beta = warmstart\n\n def get_K(alpha, beta):\n \"\"\"log space computation\"\"\"\n return np.exp(-(M - alpha.reshape((na, 1)) - beta.reshape((1, nb))) / reg)\n\n # print(np.min(K))\n def get_reg(n): # exponential decreasing\n return (epsilon0 - reg) * np.exp(-n) + reg\n\n loop = 1\n cpt = 0\n err = 1\n while loop:\n\n regi = get_reg(cpt)\n\n G, logi = sinkhorn_stabilized(a, b, M, regi, numItermax=numInnerItermax, stopThr=1e-9, warmstart=(\n alpha, beta), verbose=False, print_period=20, tau=tau, log=True)\n\n alpha = logi['alpha']\n beta = logi['beta']\n\n if cpt >= numItermax:\n loop = False\n\n if cpt % (print_period) == 0: # spsion nearly converged\n # we can speed up the process by checking for the error only all\n # the 10th iterations\n transp = G\n err = np.linalg.norm(\n (np.sum(transp, axis=0) - b))**2 + np.linalg.norm((np.sum(transp, axis=1) - a))**2\n if log:\n log['err'].append(err)\n\n if verbose:\n if cpt % (print_period * 10) == 0:\n print(\n '{:5s}|{:12s}'.format('It.', 'Err') + '\\n' + '-' * 19)\n print('{:5d}|{:8e}|'.format(cpt, err))\n\n if err <= stopThr and cpt > numItermin:\n loop = False\n\n cpt = cpt + 1\n # print('err=',err,' cpt=',cpt)\n if log:\n log['alpha'] = alpha\n log['beta'] = beta\n log['warmstart'] = (log['alpha'], log['beta'])\n return G, log\n else:\n return G\n\n\ndef geometricBar(weights, alldistribT):\n \"\"\"return the weighted geometric mean of distributions\"\"\"\n assert(len(weights) == alldistribT.shape[1])\n return np.exp(np.dot(np.log(alldistribT), weights.T))\n\n\ndef geometricMean(alldistribT):\n \"\"\"return the geometric mean of distributions\"\"\"\n return np.exp(np.mean(np.log(alldistribT), axis=1))\n\n\ndef projR(gamma, p):\n \"\"\"return the KL projection on the row constrints \"\"\"\n return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T\n\n\ndef projC(gamma, q):\n \"\"\"return the KL projection on the column constrints \"\"\"\n return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10))\n\n\ndef barycenter(A, M, reg, weights=None, numItermax=1000, stopThr=1e-4, verbose=False, log=False):\n \"\"\"Compute the entropic regularized wasserstein barycenter of distributions A\n The function solves the following optimization problem:\n .. math::\n \\mathbf{a} = arg\\min_\\mathbf{a} \\sum_i W_{reg}(\\mathbf{a},\\mathbf{a}_i)\n where :\n - :math:`W_{reg}(\\cdot,\\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn)\n - :math:`\\mathbf{a}_i` are training distributions in the columns of matrix :math:`\\mathbf{A}`\n - reg and :math:`\\mathbf{M}` are respectively the regularization term and the cost matrix for OT\n The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_\n Parameters\n ----------\n A : np.ndarray (d,n)\n n training distributions of size d\n M : np.ndarray (d,d)\n loss matrix for OT\n reg : float\n Regularization term >0\n numItermax : int, optional\n Max number of iterations\n stopThr : float, optional\n Stop threshol on error (>0)\n verbose : bool, optional\n Print information along iterations\n log : bool, optional\n record log if True\n Returns\n -------\n a : (d,) ndarray\n Wasserstein barycenter\n log : dict\n log dictionary return only if log==True in parameters\n References\n ----------\n .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.\n \"\"\"\n\n if weights is None:\n weights = np.ones(A.shape[1]) / A.shape[1]\n else:\n assert(len(weights) == A.shape[1])\n\n if log:\n log = {'err': []}\n\n # M = M/np.median(M) # suggested by G. Peyre\n K = np.exp(-M / reg)\n\n cpt = 0\n err = 1\n\n UKv = np.dot(K, np.divide(A.T, np.sum(K, axis=0)).T)\n u = (geometricMean(UKv) / UKv.T).T\n\n while (err > stopThr and cpt < numItermax):\n cpt = cpt + 1\n UKv = u * np.dot(K, np.divide(A, np.dot(K, u)))\n u = (u.T * geometricBar(weights, UKv)).T / UKv\n\n if cpt % 10 == 1:\n err = np.sum(np.std(UKv, axis=1))\n\n # log and verbose print\n if log:\n log['err'].append(err)\n\n if verbose:\n if cpt % 200 == 0:\n print(\n '{:5s}|{:12s}'.format('It.', 'Err') + '\\n' + '-' * 19)\n print('{:5d}|{:8e}|'.format(cpt, err))\n\n if log:\n log['niter'] = cpt\n return geometricBar(weights, UKv), log\n else:\n return geometricBar(weights, UKv)\n\n\ndef unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000, stopThr=1e-3, verbose=False, log=False):\n \"\"\"\n Compute the unmixing of an observation with a given dictionary using Wasserstein distance\n The function solve the following optimization problem:\n .. math::\n \\mathbf{h} = arg\\min_\\mathbf{h} (1- \\\\alpha) W_{M,reg}(\\mathbf{a},\\mathbf{Dh})+\\\\alpha W_{M0,reg0}(\\mathbf{h}_0,\\mathbf{h})\n where :\n - :math:`W_{M,reg}(\\cdot,\\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn)\n - :math:`\\mathbf{a}` is an observed distribution, :math:`\\mathbf{h}_0` is aprior on unmixing\n - reg and :math:`\\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting\n - reg0 and :math:`\\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization\n - :math:`\\\\alpha`weight data fitting and regularization\n The optimization problem is solved suing the algorithm described in [4]\n Parameters\n ----------\n a : np.ndarray (d)\n observed distribution\n D : np.ndarray (d,n)\n dictionary matrix\n M : np.ndarray (d,d)\n loss matrix\n M0 : np.ndarray (n,n)\n loss matrix\n h0 : np.ndarray (n,)\n prior on h\n reg : float\n Regularization term >0 (Wasserstein data fitting)\n reg0 : float\n Regularization term >0 (Wasserstein reg with h0)\n alpha : float\n How much should we trust the prior ([0,1])\n numItermax : int, optional\n Max number of iterations\n stopThr : float, optional\n Stop threshol on error (>0)\n verbose : bool, optional\n Print information along iterations\n log : bool, optional\n record log if True\n Returns\n -------\n a : (d,) ndarray\n Wasserstein barycenter\n log : dict\n log dictionary return only if log==True in parameters\n References\n ----------\n .. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016.\n \"\"\"\n\n # M = M/np.median(M)\n K = np.exp(-M / reg)\n\n # M0 = M0/np.median(M0)\n K0 = np.exp(-M0 / reg0)\n old = h0\n\n err = 1\n cpt = 0\n # log = {'niter':0, 'all_err':[]}\n if log:\n log = {'err': []}\n\n while (err > stopThr and cpt < numItermax):\n K = projC(K, a)\n K0 = projC(K0, h0)\n new = np.sum(K0, axis=1)\n # we recombine the current selection from dictionnary\n inv_new = np.dot(D, new)\n other = np.sum(K, axis=1)\n # geometric interpolation\n delta = np.exp(alpha * np.log(other) + (1 - alpha) * np.log(inv_new))\n K = projR(K, delta)\n K0 = np.dot(np.diag(np.dot(D.T, delta / inv_new)), K0)\n\n err = np.linalg.norm(np.sum(K0, axis=1) - old)\n old = new\n if log:\n log['err'].append(err)\n\n if verbose:\n if cpt % 200 == 0:\n print('{:5s}|{:12s}'.format('It.', 'Err') + '\\n' + '-' * 19)\n print('{:5d}|{:8e}|'.format(cpt, err))\n\n cpt = cpt + 1\n\n if log:\n log['niter'] = cpt\n return np.sum(K0, axis=1), log\n else:\n return np.sum(K0, axis=1)\n"
] |
[
[
"numpy.dot",
"numpy.log",
"numpy.isinf",
"numpy.abs",
"numpy.asarray",
"numpy.isnan",
"numpy.ones",
"numpy.std",
"numpy.any",
"numpy.exp",
"numpy.zeros",
"numpy.sum",
"numpy.divide"
]
] |
zaccharieramzi/tf-complex
|
[
"c1e5843bfc7afc9741b4f08fa5890301758ea124"
] |
[
"tf_complex/convolutions.py"
] |
[
"import tensorflow as tf\nfrom tensorflow.keras.layers import Layer, Conv2D\n\nfrom .activations import ComplexActivation\n\nclass ComplexConv2D(Layer):\n r\"\"\"Complex convolution.\n\n This is defined in [C2020].\n Parameters:\n n_filters (int): the equivalent number of filters used for a real\n convolution. As per the convention defined in the code for [C2020],\n this means that each convolution will actually have `n_filters // 2`\n filters.\n kernel_size (int): the size of the convolution kernels.\n activation (str or callable or None): the activation function to use for\n this complex convolution. Must be defined via tf_complex.activations\n is using a string. If None, the linear activation function is used.\n Defaults to None.\n trainable (bool): whether the layer's variables should be trainable.\n Defaults to True.\n name (str): name of the layer. Defaults to None.\n dtype (tf.dtype or str): the dtype of the layer's computations and\n weights. Defaults to None.\n dynamic (bool): if the layer is to be run eargerly. Defaults to False.\n **conv_kwargs: keyword arguments for the convolutions initializations.\n\n Attributes:\n n_filters_total (int): the number of filters in total for the\n convolutions. Corresponds to the parameter `n_filters`.\n activation (tf_complex.activations.ComplexActivation): the activation\n function.\n convs (dict str -> tf.keras.layers.Conv2D): the different convolution\n layers used to perform the underlying complex convolutions.\n \"\"\"\n conv_types = [\n 'real',\n 'imag',\n ]\n def __init__(\n self,\n n_filters,\n kernel_size,\n activation=None,\n use_bias=True,\n trainable=True,\n name=None,\n dtype=None,\n dynamic=False,\n **conv_kwargs,\n ):\n super(ComplexConv2D, self).__init__(\n trainable=trainable,\n name=name,\n dtype=dtype,\n dynamic=dynamic,\n )\n self.activation = ComplexActivation(activation)\n self.use_bias = use_bias\n self.n_filters_total = n_filters\n self.kernel_size = kernel_size\n conv_kwargs.update(dict(\n filters=self.n_filters_total // 2, # we follow the convention\n # established here:\n # https://github.com/MRSRL/complex-networks-release/blob/master/complex_utils.py#L13\n kernel_size=self.kernel_size,\n use_bias=False,\n activation=None,\n ))\n self.convs = {\n conv_type: Conv2D(\n name=f'{conv_type}_conv2d',\n **conv_kwargs,\n ) for conv_type in ComplexConv2D.conv_types\n }\n if self.use_bias:\n self.biases = {\n dense_type: self.add_weight(\n name=f'{dense_type}_dense_bias',\n shape=[self.n_filters_total // 2],\n initializer=conv_kwargs.get('bias_initializer', 'zeros'),\n regularizer=conv_kwargs.get('bias_regularizer', None),\n constraint=conv_kwargs.get('bias_constraint', None),\n ) for dense_type in ComplexConv2D.conv_types\n }\n\n def call(self, inputs):\n real = tf.math.real(inputs)\n imag = tf.math.imag(inputs)\n output_real = self.convs['real'](real) - self.convs['imag'](imag)\n output_imag = self.convs['imag'](real) + self.convs['real'](imag)\n output = tf.complex(output_real, output_imag)\n output = self.activation(output)\n return output\n"
] |
[
[
"tensorflow.complex",
"tensorflow.math.imag",
"tensorflow.math.real",
"tensorflow.keras.layers.Conv2D"
]
] |
corvust/strawberryfields
|
[
"fd1b1aa18f5f7309ced9ca494912b4169bd9d19d"
] |
[
"tests/frontend/compilers/test_gaussianunitary.py"
] |
[
"# Copyright 2019 Xanadu Quantum Technologies Inc.\r\n\r\n# Licensed under the Apache License, Version 2.0 (the \"License\");\r\n# you may not use this file except in compliance with the License.\r\n# You may obtain a copy of the License at\r\n\r\n# http://www.apache.org/licenses/LICENSE-2.0\r\n\r\n# Unless required by applicable law or agreed to in writing, software\r\n# distributed under the License is distributed on an \"AS IS\" BASIS,\r\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n# See the License for the specific language governing permissions and\r\n# limitations under the License.\r\nr\"\"\"Unit tests for the GaussianUnitary class\"\"\"\r\n\r\nimport pytest\r\nimport numpy as np\r\n\r\nimport strawberryfields as sf\r\nimport strawberryfields.ops as ops\r\nfrom strawberryfields.utils import random_symplectic\r\n\r\npytestmark = pytest.mark.frontend\r\n\r\nnp.random.seed(42)\r\n\r\n\r\ndef random_params(size, sq_bound, disp_bound):\r\n \"\"\"Returns random parameters of a Gaussian circuit\r\n\r\n Args:\r\n size (int): number of modes\r\n sq_bound (float): maximum value of the squeezing\r\n disp_bound (float): maximum value of the displacement in absolute value\r\n\r\n Returns:\r\n tuple: Gaussian circuit parameters\r\n\r\n \"\"\"\r\n A = np.random.rand(size, size) + 1j * np.random.rand(size, size)\r\n U, s, V = np.linalg.svd(A)\r\n s = sq_bound * s / (np.max(s))\r\n alphas = disp_bound * ((np.random.rand(size) - 0.5) + 1j * (np.random.rand(size) - 0.5))\r\n return U, s, V, alphas\r\n\r\n\r\[email protected](\"depth\", [1, 3, 6])\r\[email protected](\"width\", [5, 10, 15])\r\ndef test_gaussian_program(depth, width):\r\n \"\"\"Tests that a circuit and its compiled version produce the same Gaussian state\"\"\"\r\n eng = sf.LocalEngine(backend=\"gaussian\")\r\n eng1 = sf.LocalEngine(backend=\"gaussian\")\r\n circuit = sf.Program(width)\r\n with circuit.context as q:\r\n for _ in range(depth):\r\n U, s, V, alphas = random_params(width, 2.0 / depth, 1.0)\r\n ops.Interferometer(U) | q\r\n for i in range(width):\r\n ops.Sgate(s[i]) | q[i]\r\n ops.Interferometer(V) | q\r\n for i in range(width):\r\n ops.Dgate(np.abs(alphas[i]), np.angle(alphas[i])) | q[i]\r\n compiled_circuit = circuit.compile(compiler=\"gaussian_unitary\")\r\n cv = eng.run(circuit).state.cov()\r\n mean = eng.run(circuit).state.means()\r\n\r\n cv1 = eng1.run(compiled_circuit).state.cov()\r\n mean1 = eng1.run(compiled_circuit).state.means()\r\n assert np.allclose(cv, cv1)\r\n assert np.allclose(mean, mean1)\r\n\r\n\r\[email protected](\"depth\", [1, 2, 3])\r\[email protected](\"width\", [5, 10])\r\ndef test_symplectic_composition(depth, width):\r\n \"\"\"Tests that symplectic operations are composed correctly\"\"\"\r\n eng = sf.LocalEngine(backend=\"gaussian\")\r\n eng1 = sf.LocalEngine(backend=\"gaussian\")\r\n circuit = sf.Program(width)\r\n Snet = np.identity(2 * width)\r\n with circuit.context as q:\r\n for _ in range(depth):\r\n S = random_symplectic(width, scale = 0.2)\r\n Snet = S @ Snet\r\n ops.GaussianTransform(S) | q\r\n compiled_circuit = circuit.compile(compiler=\"gaussian_unitary\")\r\n assert np.allclose(compiled_circuit.circuit[0].op.p[0], Snet)\r\n\r\n\r\[email protected](\"depth\", [1, 2, 3])\r\ndef test_modes_subset(depth):\r\n \"\"\"Tests that the compiler recognizes which modes are not being modified and acts accordingly\"\"\"\r\n\r\n width = 10\r\n eng = sf.LocalEngine(backend=\"gaussian\")\r\n eng1 = sf.LocalEngine(backend=\"gaussian\")\r\n circuit = sf.Program(width)\r\n indices = (1, 4, 2, 6, 7)\r\n active_modes = len(indices)\r\n with circuit.context as q:\r\n for _ in range(depth):\r\n U, s, V, _ = random_params(active_modes, 2.0 / depth, 1.0)\r\n ops.Interferometer(U) | tuple(q[i] for i in indices)\r\n for i, index in enumerate(indices):\r\n ops.Sgate(s[i]) | q[index]\r\n ops.Interferometer(V) | tuple(q[i] for i in indices)\r\n compiled_circuit = circuit.compile(compiler=\"gaussian_unitary\")\r\n cv = eng.run(circuit).state.cov()\r\n mean = eng.run(circuit).state.means()\r\n\r\n cv1 = eng1.run(compiled_circuit).state.cov()\r\n mean1 = eng1.run(compiled_circuit).state.means()\r\n assert np.allclose(cv, cv1)\r\n assert np.allclose(mean, mean1)\r\n assert len(compiled_circuit.circuit[0].reg) == 5\r\n indices = [compiled_circuit.circuit[0].reg[i].ind for i in range(5)]\r\n assert indices == sorted(list(indices))\r\n\r\n\r\ndef test_non_primitive_gates():\r\n \"\"\"Tests that the compiler is able to compile a number of non-primitive Gaussian gates\"\"\"\r\n\r\n width = 6\r\n eng = sf.LocalEngine(backend=\"gaussian\")\r\n eng1 = sf.LocalEngine(backend=\"gaussian\")\r\n circuit = sf.Program(width)\r\n A = np.random.rand(width, width) + 1j * np.random.rand(width, width)\r\n A = A + A.T\r\n valsA = np.linalg.svd(A, compute_uv=False)\r\n A = A / 2 * np.max(valsA)\r\n B = np.random.rand(width // 2, width // 2) + 1j * np.random.rand(width // 2, width // 2)\r\n valsB = np.linalg.svd(B, compute_uv=False)\r\n B = B / 2 * valsB\r\n B = np.block([[0 * B, B], [B.T, 0 * B]])\r\n with circuit.context as q:\r\n ops.GraphEmbed(A) | q\r\n ops.BipartiteGraphEmbed(B) | q\r\n ops.Pgate(0.1) | q[1]\r\n ops.CXgate(0.2) | (q[0], q[1])\r\n ops.MZgate(0.4, 0.5) | (q[2], q[3])\r\n ops.Fourier | q[0]\r\n ops.Xgate(0.4) | q[1]\r\n ops.Zgate(0.5) | q[3]\r\n compiled_circuit = circuit.compile(compiler=\"gaussian_unitary\")\r\n cv = eng.run(circuit).state.cov()\r\n mean = eng.run(circuit).state.means()\r\n\r\n cv1 = eng1.run(compiled_circuit).state.cov()\r\n mean1 = eng1.run(compiled_circuit).state.means()\r\n assert np.allclose(cv, cv1)\r\n assert np.allclose(mean, mean1)\r\n\r\n\r\n\r\[email protected](\"depth\", [1, 3, 6])\r\[email protected](\"width\", [5, 10, 15])\r\ndef test_displacements_only(depth, width):\r\n \"\"\"Tests that a circuit and its compiled version produce\r\n the same Gaussian state when there are only displacements\"\"\"\r\n eng = sf.LocalEngine(backend=\"gaussian\")\r\n eng1 = sf.LocalEngine(backend=\"gaussian\")\r\n circuit = sf.Program(width)\r\n with circuit.context as q:\r\n for _ in range(depth):\r\n alphas = np.random.rand(width)+1j*np.random.rand(width)\r\n for i in range(width):\r\n ops.Dgate(np.abs(alphas[i]), np.angle(alphas[i])) | q[i]\r\n compiled_circuit = circuit.compile(compiler=\"gaussian_unitary\")\r\n cv = eng.run(circuit).state.cov()\r\n mean = eng.run(circuit).state.means()\r\n\r\n cv1 = eng1.run(compiled_circuit).state.cov()\r\n mean1 = eng1.run(compiled_circuit).state.means()\r\n assert np.allclose(cv, cv1)\r\n assert np.allclose(mean, mean1)\r\n"
] |
[
[
"numpy.linalg.svd",
"numpy.allclose",
"numpy.random.seed",
"numpy.abs",
"numpy.max",
"numpy.block",
"numpy.identity",
"numpy.random.rand",
"numpy.angle"
]
] |
hishamelreedy/innovatefpga-GestureRecognitionAccelerator
|
[
"576e432875f5736f71cf915187ea6b42f376089a"
] |
[
"bin/imgtocodev3.py"
] |
[
"#some set up\nimport numpy as np\nfrom PIL import Image\n\n# load the test image\nim_path = r'circle.jpg'\nim = Image.open(im_path)\n\n# Read Image into Numpy Array\nim_input = np.asarray(im)\n\n# Reshape Input to be (3,224,224) instead of (224,224,3)\ntmp = np.zeros((3,224,224))\nfor i in range(0,224):\n for j in range(0,224):\n for k in range(0,3):\n tmp[k][i][j] = im_input[i][j][k]\n#add a new axis for pytorch model\nim_input = tmp[np.newaxis,:]\nprint(im_input.shape)\n#preprocess of the input image\ny = np.zeros((1,3,224,224))\nfor i in range(0, 3):\n for j in range(0, 224):\n for k in range(0, 224):\n y[0][i][j][k] = (im_input[0][i][j][k]/255 - 0.5)/0.5\n\n# Collect data in rows to be written into file\nx=[]\nfor i in range(0, 3):\n for j in range(0, 224):\n for k in range(0, 224):\n x.append(str(y[0][i][j][k])[:8])\na=np.array(x).reshape(18816,8)\n\nwith open('pic.txt', 'w') as testfile:\n for row in range(0,len(a)):\n for x in range(0, len(a[row])):\n testfile.write(a[row][x])\n testfile.write('\\n')\n"
] |
[
[
"numpy.asarray",
"numpy.array",
"numpy.zeros"
]
] |
wusunlab/chflux
|
[
"e6d24017fe8d692b3b05733508ff6db06a49ae76"
] |
[
"chflux/io/parsers.py"
] |
[
"\"\"\"PyChamberFlux I/O module containing a collection of data parsers.\"\"\"\nimport pandas as pd\n\n\n# A collection of parsers for timestamps stored in multiple columns.\n# Supports only the ISO 8601 format (year-month-day).\n# Does not support month-first (American) or day-first (European) format.\ntimestamp_parsers = {\n # date only\n 'ymd': lambda s: pd.to_datetime(s, format='%Y %m %d'),\n\n # down to minute\n 'ymdhm': lambda s: pd.to_datetime(s, format='%Y %m %d %H %M'),\n\n # down to second\n 'ymdhms': lambda s: pd.to_datetime(s, format='%Y %m %d %H %M %S'),\n\n # down to nanosecond\n 'ymdhmsf': lambda s: pd.to_datetime(s, format='%Y %m %d %H %M %S %f')\n}\n\n\ndef parse_timestamp():\n pass\n"
] |
[
[
"pandas.to_datetime"
]
] |
dstansby/cellfinder-core
|
[
"740dae17d862a9c5e7278044d0bb7238e54205e3"
] |
[
"src/cellfinder_core/train/train_yml.py"
] |
[
"\"\"\"\nmain\n===============\n\nTrains a network based on a yaml file specifying cubes of cells/non cells.\n\nN.B imports are within functions to prevent tensorflow being imported before\nit's warnings are silenced\n\"\"\"\n\n\nimport logging\nimport os\nfrom argparse import (\n ArgumentDefaultsHelpFormatter,\n ArgumentParser,\n ArgumentTypeError,\n)\nfrom datetime import datetime\nfrom pathlib import Path\n\nfrom fancylog import fancylog\nfrom imlib.general.numerical import check_positive_float, check_positive_int\nfrom imlib.general.system import ensure_directory_exists\nfrom imlib.IO.cells import find_relevant_tiffs\nfrom imlib.IO.yaml import read_yaml_section\nfrom sklearn.model_selection import train_test_split\n\nimport cellfinder_core as program_for_log\n\nhome = Path.home()\ninstall_path = home / \".cellfinder\"\n\ntf_suppress_log_messages = [\n \"sample_weight modes were coerced from\",\n \"multiprocessing can interact badly with TensorFlow\",\n]\n\nmodels = {\n \"18\": \"18-layer\",\n \"34\": \"34-layer\",\n \"50\": \"50-layer\",\n \"101\": \"101-layer\",\n \"152\": \"152-layer\",\n}\n\n\ndef valid_model_depth(depth):\n \"\"\"\n Ensures a correct existing_model is chosen\n :param value: Input value\n :param models: Dict of allowed models\n :return: Input value, if it corresponds to a valid existing_model\n \"\"\"\n\n if depth in models.keys():\n return depth\n else:\n raise ArgumentTypeError(\n f\"Model depth: {depth} is not valid. Please \"\n f\"choose one of: {list(models.keys())}\"\n )\n\n\ndef misc_parse(parser):\n misc_parser = parser.add_argument_group(\"Misc options\")\n misc_parser.add_argument(\n \"--n-free-cpus\",\n dest=\"n_free_cpus\",\n type=check_positive_int,\n default=2,\n help=\"The number of CPU cores on the machine to leave \"\n \"unused by the program to spare resources.\",\n )\n misc_parser.add_argument(\n \"--max-ram\",\n dest=\"max_ram\",\n type=check_positive_float,\n default=None,\n help=\"Maximum amount of RAM to use (in GB) - not currently fully \"\n \"implemented for all parts of cellfinder\",\n )\n misc_parser.add_argument(\n \"--save-csv\",\n dest=\"save_csv\",\n action=\"store_true\",\n help=\"Save .csv files of cell locations (in addition to xml).\"\n \"Useful for importing into other software.\",\n )\n misc_parser.add_argument(\n \"--debug\",\n dest=\"debug\",\n action=\"store_true\",\n help=\"Debug mode. Will increase verbosity of logging and save all \"\n \"intermediate files for diagnosis of software issues.\",\n )\n misc_parser.add_argument(\n \"--sort-input-file\",\n dest=\"sort_input_file\",\n action=\"store_true\",\n help=\"If set to true, the input text file will be sorted using \"\n \"natural sorting. This means that the file paths will be \"\n \"sorted as would be expected by a human and \"\n \"not purely alphabetically\",\n )\n return parser\n\n\ndef training_parse():\n from cellfinder_core.download.cli import (\n download_directory_parser,\n model_parser,\n )\n\n training_parser = ArgumentParser(\n formatter_class=ArgumentDefaultsHelpFormatter\n )\n training_parser.add_argument(\n \"-y\",\n \"--yaml\",\n dest=\"yaml_file\",\n nargs=\"+\",\n required=True,\n type=str,\n help=\"The path to the yaml run file.\",\n )\n training_parser.add_argument(\n \"-o\",\n \"--output-dir\",\n dest=\"output_dir\",\n required=True,\n type=str,\n help=\"Output directory for the final model.\",\n )\n training_parser.add_argument(\n \"--continue-training\",\n dest=\"continue_training\",\n action=\"store_true\",\n help=\"Continue training from an existing trained model. If no model \"\n \"or model weights are specified, this will continue from the \"\n \"included model.\",\n )\n training_parser.add_argument(\n \"--trained-model\",\n dest=\"trained_model\",\n type=str,\n help=\"Path to the trained model\",\n )\n training_parser.add_argument(\n \"--model-weights\",\n dest=\"model_weights\",\n type=str,\n help=\"Path to existing model weights\",\n )\n training_parser.add_argument(\n \"--network-depth\",\n dest=\"network_depth\",\n type=valid_model_depth,\n default=\"50\",\n help=\"Resnet depth (based on He et al. (2015)\",\n )\n training_parser.add_argument(\n \"--batch-size\",\n dest=\"batch_size\",\n type=check_positive_int,\n default=16,\n help=\"Training batch size\",\n )\n training_parser.add_argument(\n \"--epochs\",\n dest=\"epochs\",\n type=check_positive_int,\n default=100,\n help=\"Number of training epochs\",\n )\n training_parser.add_argument(\n \"--test-fraction\",\n dest=\"test_fraction\",\n type=float,\n default=0.1,\n help=\"Fraction of training data to use for validation\",\n )\n training_parser.add_argument(\n \"--learning-rate\",\n dest=\"learning_rate\",\n type=check_positive_float,\n default=0.0001,\n help=\"Learning rate for training the model\",\n )\n training_parser.add_argument(\n \"--no-augment\",\n dest=\"no_augment\",\n action=\"store_true\",\n help=\"Don't apply data augmentation\",\n )\n training_parser.add_argument(\n \"--save-weights\",\n dest=\"save_weights\",\n action=\"store_true\",\n help=\"Only store the model weights, and not the full model. Useful to \"\n \"save storage space.\",\n )\n training_parser.add_argument(\n \"--no-save-checkpoints\",\n dest=\"no_save_checkpoints\",\n action=\"store_true\",\n help=\"Store the model at intermediate points during training\",\n )\n training_parser.add_argument(\n \"--tensorboard\",\n action=\"store_true\",\n help=\"Log to output_directory/tensorboard\",\n )\n training_parser.add_argument(\n \"--save-progress\",\n dest=\"save_progress\",\n action=\"store_true\",\n help=\"Save training progress to a .csv file\",\n )\n\n training_parser = misc_parse(training_parser)\n training_parser = model_parser(training_parser)\n training_parser = download_directory_parser(training_parser)\n args = training_parser.parse_args()\n\n return args\n\n\ndef parse_yaml(yaml_files, section=\"data\"):\n data = []\n for yaml_file in yaml_files:\n data.extend(read_yaml_section(yaml_file, section))\n return data\n\n\ndef get_tiff_files(yaml_contents):\n from cellfinder_core.tools.tiff import TiffDir, TiffList\n\n tiff_lists = []\n for d in yaml_contents:\n if d[\"bg_channel\"] < 0:\n channels = [d[\"signal_channel\"]]\n else:\n channels = [d[\"signal_channel\"], d[\"bg_channel\"]]\n if \"cell_def\" in d and d[\"cell_def\"]:\n ch1_tiffs = [\n os.path.join(d[\"cube_dir\"], f)\n for f in os.listdir(d[\"cube_dir\"])\n if f.endswith(\"Ch\" + str(channels[0]) + \".tif\")\n ]\n tiff_lists.append(\n TiffList(\n find_relevant_tiffs(ch1_tiffs, d[\"cell_def\"]),\n channels,\n d[\"type\"],\n )\n )\n else:\n tiff_lists.append(TiffDir(d[\"cube_dir\"], channels, d[\"type\"]))\n\n tiff_files = [tiff_dir.make_tifffile_list() for tiff_dir in tiff_lists]\n return tiff_files\n\n\ndef cli():\n args = training_parse()\n ensure_directory_exists(args.output_dir)\n\n fancylog.start_logging(\n args.output_dir,\n program_for_log,\n variables=[args],\n log_header=\"CELLFINDER TRAINING LOG\",\n )\n\n output_dir = Path(args.output_dir)\n run(\n output_dir,\n args.yaml_file,\n n_free_cpus=args.n_free_cpus,\n trained_model=args.trained_model,\n model_weights=args.model_weights,\n install_path=args.install_path,\n model=args.model,\n network_depth=args.network_depth,\n learning_rate=args.learning_rate,\n continue_training=args.continue_training,\n test_fraction=args.test_fraction,\n batch_size=args.batch_size,\n no_augment=args.no_augment,\n tensorboard=args.tensorboard,\n save_weights=args.save_weights,\n no_save_checkpoints=args.no_save_checkpoints,\n save_progress=args.save_progress,\n epochs=args.epochs,\n )\n\n\ndef run(\n output_dir,\n yaml_file,\n n_free_cpus=2,\n trained_model=None,\n model_weights=None,\n install_path=install_path,\n model=\"resnet50_tv\",\n network_depth=\"50\",\n learning_rate=0.0001,\n continue_training=False,\n test_fraction=0.1,\n batch_size=16,\n no_augment=False,\n tensorboard=False,\n save_weights=False,\n no_save_checkpoints=False,\n save_progress=False,\n epochs=100,\n):\n\n from cellfinder_core.main import suppress_tf_logging\n\n suppress_tf_logging(tf_suppress_log_messages)\n\n from tensorflow.keras.callbacks import (\n CSVLogger,\n ModelCheckpoint,\n TensorBoard,\n )\n\n from cellfinder_core.classify.cube_generator import CubeGeneratorFromDisk\n from cellfinder_core.classify.tools import get_model, make_lists\n from cellfinder_core.tools.prep import prep_training\n\n start_time = datetime.now()\n\n ensure_directory_exists(output_dir)\n model_weights = prep_training(\n n_free_cpus, trained_model, model_weights, install_path, model\n )\n\n yaml_contents = parse_yaml(yaml_file)\n\n tiff_files = get_tiff_files(yaml_contents)\n logging.info(\n f\"Found {sum(len(imlist) for imlist in tiff_files)} images \"\n f\"from {len(yaml_contents)} datasets \"\n f\"in {len(yaml_file)} yaml files\"\n )\n\n model = get_model(\n existing_model=trained_model,\n model_weights=model_weights,\n network_depth=models[network_depth],\n learning_rate=learning_rate,\n continue_training=continue_training,\n )\n\n signal_train, background_train, labels_train = make_lists(tiff_files)\n\n if test_fraction > 0:\n logging.info(\"Splitting data into training and validation datasets\")\n (\n signal_train,\n signal_test,\n background_train,\n background_test,\n labels_train,\n labels_test,\n ) = train_test_split(\n signal_train,\n background_train,\n labels_train,\n test_size=test_fraction,\n )\n\n logging.info(\n f\"Using {len(signal_train)} images for training and \"\n f\"{len(signal_test)} images for validation\"\n )\n validation_generator = CubeGeneratorFromDisk(\n signal_test,\n background_test,\n labels=labels_test,\n batch_size=batch_size,\n train=True,\n )\n\n # for saving checkpoints\n base_checkpoint_file_name = \"-epoch.{epoch:02d}-loss-{val_loss:.3f}.h5\"\n\n else:\n logging.info(\"No validation data selected.\")\n validation_generator = None\n base_checkpoint_file_name = \"-epoch.{epoch:02d}.h5\"\n\n training_generator = CubeGeneratorFromDisk(\n signal_train,\n background_train,\n labels=labels_train,\n batch_size=batch_size,\n shuffle=True,\n train=True,\n augment=not no_augment,\n )\n callbacks = []\n\n if tensorboard:\n logdir = output_dir / \"tensorboard\"\n ensure_directory_exists(logdir)\n tensorboard = TensorBoard(\n log_dir=logdir,\n histogram_freq=0,\n write_graph=True,\n update_freq=\"epoch\",\n )\n callbacks.append(tensorboard)\n\n if not no_save_checkpoints:\n if save_weights:\n filepath = str(output_dir / (\"weight\" + base_checkpoint_file_name))\n else:\n filepath = str(output_dir / (\"model\" + base_checkpoint_file_name))\n\n checkpoints = ModelCheckpoint(\n filepath,\n save_weights_only=save_weights,\n )\n callbacks.append(checkpoints)\n\n if save_progress:\n filepath = str(output_dir / \"training.csv\")\n csv_logger = CSVLogger(filepath)\n callbacks.append(csv_logger)\n\n logging.info(\"Beginning training.\")\n model.fit(\n training_generator,\n validation_data=validation_generator,\n use_multiprocessing=False,\n epochs=epochs,\n callbacks=callbacks,\n )\n\n if save_weights:\n logging.info(\"Saving model weights\")\n model.save_weights(str(output_dir / \"model_weights.h5\"))\n else:\n logging.info(\"Saving model\")\n model.save(output_dir / \"model.h5\")\n\n logging.info(\n \"Finished training, \" \"Total time taken: %s\",\n datetime.now() - start_time,\n )\n\n\nif __name__ == \"__main__\":\n cli()\n"
] |
[
[
"tensorflow.keras.callbacks.TensorBoard",
"tensorflow.keras.callbacks.ModelCheckpoint",
"tensorflow.keras.callbacks.CSVLogger",
"sklearn.model_selection.train_test_split"
]
] |
bilalmoiz/ai-platform
|
[
"8da01fa7a8339eec269d64a4e2cbd9b25509cd5e"
] |
[
"tasks/computer-vision/image-classification/pneumonia_model.py"
] |
[
"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Aug 31 13:08:05 2019\r\n\r\n@author: firstname.lastname\r\n\"\"\"\r\n\r\nimport numpy as np # linear algebra\r\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\r\nimport mlflow\r\nimport mlflow.keras\r\nimport keras\r\nfrom tensorflow.python.keras import *\r\nfrom tensorflow.python.keras.layers import *\r\nfrom keras.preprocessing.image import ImageDataGenerator, load_img\r\nfrom keras.applications.resnet50 import preprocess_input\r\nfrom keras.applications import ResNet50\r\n\r\nfrom keras import optimizers\r\nfrom keras import metrics\r\nfrom PIL import Image\r\nimport matplotlib.pyplot as plt \r\nimport sys\r\n\r\n\r\n#model parameters for easy tuning'\r\n \r\n\r\ndef build_compile_model(nodes):\r\n xray_model = Sequential()\r\n xray_model.add(Conv2D(32,(3,3), activation='relu',input_shape=(img_size,img_size,3)))\r\n xray_model.add(MaxPooling2D(pool_size=(2,2)))\r\n \r\n xray_model.add(Conv2D(32, (3, 3), activation=\"relu\")) \r\n xray_model.add(MaxPooling2D(pool_size=(2,2))) \r\n \r\n xray_model.add(Conv2D(32, (3, 3), activation=\"relu\")) \r\n xray_model.add(MaxPooling2D(pool_size=(2,2))) \r\n \r\n xray_model.add(Flatten())\r\n \r\n xray_model.add(Dense(activation='relu',units=nodes)) \r\n xray_model.add(Dense(activation='sigmoid',units=1))\r\n \r\n \r\n xray_model.compile(optimizer='adam', loss='binary_crossentropy',metrics=['accuracy'])\r\n \r\n \r\n xray_model.summary() \r\n\r\n return xray_model\r\n\r\ndef gen_data(): \r\n\r\n train_path = \"chest-xray-pneumonia/chest_xray/chest_xray/train/\"\r\n test_path = \"chest-xray-pneumonia/chest_xray/chest_xray/val/\"\r\n val_path = \"chest-xray-pneumonia/chest_xray/chest_xray/test/\"\r\n \r\n \r\n # generate the training data\r\n train_imagegen = ImageDataGenerator(rescale = 1./255, shear_range = 0.2, zoom_range = 0.3, height_shift_range = 0.1, width_shift_range = 0.05, horizontal_flip=True)\r\n training_data = train_imagegen.flow_from_directory(train_path, target_size = (img_size,img_size), batch_size = batch_size, class_mode = 'binary')\r\n \r\n # generate the validation data\r\n val_imagegen = ImageDataGenerator(rescale = 1./255)\r\n val_data = val_imagegen.flow_from_directory(val_path, target_size = (img_size,img_size), batch_size = batch_size, class_mode = 'binary')\r\n \r\n # generate the test data\r\n test_imagegen = ImageDataGenerator(rescale = 1./255)\r\n test_data = test_imagegen.flow_from_directory(test_path, target_size = (img_size,img_size), batch_size = batch_size, class_mode = 'binary')\r\n \r\n return [training_data, val_data, test_data]\r\n \r\ndef graph_data(final_model, run_uuid):\r\n \r\n plt.plot(final_model.history['val_loss'])\r\n plt.plot(final_model.history['loss'])\r\n plt.legend(['Training','Test'])\r\n plt.xlabel('# of epoch')\r\n plt.ylabel('Loss')\r\n plt.savefig(\"graphs/graph\"+ run_uuid, bbox_inches = \"tight\")\r\n # plt.show()\r\n\r\nif __name__ == \"__main__\":\r\n \r\n \r\n \r\n if len(sys.argv) < 2:\r\n print(\"Using defaults parameters only\")\r\n else: \r\n print(\"Using experimental parameters\" )\r\n \r\n batch_size = int(sys.argv[1]) if len(sys.argv) > 1 else 32\r\n img_size = int(sys.argv[2]) if len(sys.argv) > 2 else 64\r\n epoch = int(sys.argv[3]) if len(sys.argv) > 3 else 20\r\n nodes = int(sys.argv[4]) if len(sys.argv) > 4 else 120\r\n steps_per_epoch = 163\r\n \r\n # build model and customize number of nodes\r\n xray_model = build_compile_model(nodes)\r\n \r\n data = gen_data()\r\n \r\n #train model with parameters\r\n trained_model = xray_model.fit_generator(data[0], steps_per_epoch = steps_per_epoch, epochs = epoch, validation_data = data[1], validation_steps = 624//batch_size)\r\n scores = xray_model.evaluate_generator(data[2], 12)\r\n \r\n\r\n \r\n with mlflow.start_run():\r\n run_uuid = mlflow.active_run().info.run_uuid\r\n print(\"MLflow Run ID: %s\" % run_uuid)\r\n mlflow.keras.log_model(xray_model, \"models\")\r\n \r\n \r\n mlflow.log_param('Batch Size', batch_size)\r\n mlflow.log_param('Image size', img_size)\r\n mlflow.log_param('Epochs', epoch)\r\n mlflow.log_param('Number of Nodes in FC layer', nodes)\r\n \r\n \r\n mlflow.log_metric('Average Loss', trained_model.history['loss'][-1])\r\n mlflow.log_metric('Validation Loss', trained_model.history['val_loss'][-1])\r\n mlflow.log_metric('Accuracy', trained_model.history['acc'][-1])\r\n mlflow.log_metric('Validation Accuracy', trained_model.history['val_acc'][-1])\r\n \r\n graphs = graph_data(trained_model,run_uuid)\r\n mlflow.log_artifact(\"graphs/graph\" + run_uuid + \".png\")\r\n\r\n \r\n \r\n \r\n \r\n\r\n\r\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.ylabel"
]
] |
acl21/good-init-al
|
[
"da7a8b95b84ca0b78ccb7dc424303b7f24cb0fe1"
] |
[
"Unsupervised-Classification/kmeans/kmeans_pytorch/__init__.py"
] |
[
"from functools import partial\n\nimport numpy as np\nimport torch\nfrom tqdm import tqdm\n\nfrom .soft_dtw_cuda import SoftDTW\n\n\ndef initialize(X, num_clusters):\n \"\"\"\n initialize cluster centers\n :param X: (torch.tensor) matrix\n :param num_clusters: (int) number of clusters\n :return: (np.array) initial state\n \"\"\"\n num_samples = len(X)\n indices = np.random.choice(num_samples, num_clusters, replace=False)\n initial_state = X[indices]\n return initial_state\n\n\ndef kmeans(\n X,\n num_clusters,\n distance='euclidean',\n cluster_centers=[],\n tol=1e-4,\n tqdm_flag=True,\n iter_limit=0,\n device=torch.device('cpu'),\n gamma_for_soft_dtw=0.001\n):\n \"\"\"\n perform kmeans\n :param X: (torch.tensor) matrix\n :param num_clusters: (int) number of clusters\n :param distance: (str) distance [options: 'euclidean', 'cosine'] [default: 'euclidean']\n :param tol: (float) threshold [default: 0.0001]\n :param device: (torch.device) device [default: cpu]\n :param tqdm_flag: Allows to turn logs on and off\n :param iter_limit: hard limit for max number of iterations\n :param gamma_for_soft_dtw: approaches to (hard) DTW as gamma -> 0\n :return: (torch.tensor, torch.tensor) cluster ids, cluster centers\n \"\"\"\n print(f'running k-means on {device}..')\n\n if distance == 'euclidean':\n pairwise_distance_function = partial(pairwise_distance, device=device)\n elif distance == 'cosine':\n pairwise_distance_function = partial(pairwise_cosine, device=device)\n elif distance == 'soft_dtw':\n sdtw = SoftDTW(use_cuda=device.type == 'cuda', gamma=gamma_for_soft_dtw)\n pairwise_distance_function = partial(pairwise_soft_dtw, sdtw=sdtw, device=device)\n else:\n raise NotImplementedError\n\n # convert to float\n X = X.float()\n\n # transfer to device\n X = X.to(device)\n\n # initialize\n if type(cluster_centers) == list: # ToDo: make this less annoyingly weird\n initial_state = initialize(X, num_clusters)\n else:\n print('resuming')\n # find data point closest to the initial cluster center\n initial_state = cluster_centers\n dis = pairwise_distance_function(X, initial_state)\n choice_points = torch.argmin(dis, dim=0)\n initial_state = X[choice_points]\n initial_state = initial_state.to(device)\n\n iteration = 0\n if tqdm_flag:\n tqdm_meter = tqdm(desc='[running kmeans]')\n while True:\n\n dis = pairwise_distance_function(X, initial_state)\n\n choice_cluster = torch.argmin(dis, dim=1)\n\n initial_state_pre = initial_state.clone()\n\n for index in range(num_clusters):\n selected = torch.nonzero(choice_cluster == index).squeeze().to(device)\n\n selected = torch.index_select(X, 0, selected)\n\n # https://github.com/subhadarship/kmeans_pytorch/issues/16\n if selected.shape[0] == 0:\n selected = X[torch.randint(len(X), (1,))]\n\n initial_state[index] = selected.mean(dim=0)\n\n center_shift = torch.sum(\n torch.sqrt(\n torch.sum((initial_state - initial_state_pre) ** 2, dim=1)\n ))\n\n # increment iteration\n iteration = iteration + 1\n\n # update tqdm meter\n if tqdm_flag:\n tqdm_meter.set_postfix(\n iteration=f'{iteration}',\n center_shift=f'{center_shift ** 2:0.6f}',\n tol=f'{tol:0.6f}'\n )\n tqdm_meter.update()\n if center_shift ** 2 < tol:\n break\n if iter_limit != 0 and iteration >= iter_limit:\n break\n\n return choice_cluster.cpu(), initial_state.cpu()\n\n\ndef kmeans_predict(\n X,\n cluster_centers,\n distance='euclidean',\n device=torch.device('cpu'),\n gamma_for_soft_dtw=0.001\n):\n \"\"\"\n predict using cluster centers\n :param X: (torch.tensor) matrix\n :param cluster_centers: (torch.tensor) cluster centers\n :param distance: (str) distance [options: 'euclidean', 'cosine'] [default: 'euclidean']\n :param device: (torch.device) device [default: 'cpu']\n :param gamma_for_soft_dtw: approaches to (hard) DTW as gamma -> 0\n :return: (torch.tensor) cluster ids\n \"\"\"\n print(f'predicting on {device}..')\n\n if distance == 'euclidean':\n pairwise_distance_function = partial(pairwise_distance, device=device)\n elif distance == 'cosine':\n pairwise_distance_function = partial(pairwise_cosine, device=device)\n elif distance == 'soft_dtw':\n sdtw = SoftDTW(use_cuda=device.type == 'cuda', gamma=gamma_for_soft_dtw)\n pairwise_distance_function = partial(pairwise_soft_dtw, sdtw=sdtw, device=device)\n else:\n raise NotImplementedError\n\n # convert to float\n X = X.float()\n\n # transfer to device\n X = X.to(device)\n\n dis = pairwise_distance_function(X, cluster_centers)\n choice_cluster = torch.argmin(dis, dim=1)\n\n return choice_cluster.cpu()\n\n\ndef pairwise_distance(data1, data2, device=torch.device('cpu')):\n# print(f'device is :{device}')\n \n # transfer to device\n data1, data2 = data1.to(device), data2.to(device)\n\n # N*1*M\n A = data1.unsqueeze(dim=1)\n\n # 1*N*M\n B = data2.unsqueeze(dim=0)\n\n dis = (A - B) ** 2.0\n # return N*N matrix for pairwise distance\n dis = dis.sum(dim=-1).squeeze()\n return dis\n\n\ndef pairwise_cosine(data1, data2, device=torch.device('cpu')):\n # transfer to device\n data1, data2 = data1.to(device), data2.to(device)\n\n # N*1*M\n A = data1.unsqueeze(dim=1)\n\n # 1*N*M\n B = data2.unsqueeze(dim=0)\n\n # normalize the points | [0.3, 0.4] -> [0.3/sqrt(0.09 + 0.16), 0.4/sqrt(0.09 + 0.16)] = [0.3/0.5, 0.4/0.5]\n A_normalized = A / A.norm(dim=-1, keepdim=True)\n B_normalized = B / B.norm(dim=-1, keepdim=True)\n\n cosine = A_normalized * B_normalized\n\n # return N*N matrix for pairwise distance\n cosine_dis = 1 - cosine.sum(dim=-1).squeeze()\n return cosine_dis\n\n\ndef pairwise_soft_dtw(data1, data2, sdtw=None, device=torch.device('cpu')):\n if sdtw is None:\n raise ValueError('sdtw is None - initialize it with SoftDTW')\n\n # transfer to device\n data1, data2 = data1.to(device), data2.to(device)\n\n # (batch_size, seq_len, feature_dim=1)\n A = data1.unsqueeze(dim=2)\n\n # (cluster_size, seq_len, feature_dim=1)\n B = data2.unsqueeze(dim=2)\n\n distances = []\n for b in B:\n # (1, seq_len, 1)\n b = b.unsqueeze(dim=0)\n A, b = torch.broadcast_tensors(A, b)\n # (batch_size, 1)\n sdtw_distance = sdtw(b, A).view(-1, 1)\n distances.append(sdtw_distance)\n\n # (batch_size, cluster_size)\n dis = torch.cat(distances, dim=1)\n return dis\n"
] |
[
[
"torch.cat",
"numpy.random.choice",
"torch.broadcast_tensors",
"torch.argmin",
"torch.sum",
"torch.nonzero",
"torch.device",
"torch.index_select"
]
] |
eawag-rdm/savReaderWriter
|
[
"e766a38e20c09eb565ccfbe9064a7c557cc66baa"
] |
[
"savReaderWriter/unit_tests/test_SavWriter_writerows_arrays_etc.py"
] |
[
"# -*- coding: utf-8 -*-\n\"\"\"\nWriting rows from arrays et al.\n\"\"\"\n\n\nimport os\nimport re\nfrom os.path import join\nfrom tempfile import gettempdir\nfrom collections import namedtuple\nfrom unittest.case import SkipTest\n\nimport nose\nfrom nose.tools import with_setup, assert_raises\n\ntry:\n pandasOK = True\n import pandas as pd\nexcept ImportError:\n pandasOK = False\ntry:\n numpyOK = True\n import numpy as np\nexcept ImportError:\n numpyOK = False\n \nimport savReaderWriter as srw\nfrom py3k import *\n \n\nargs = ( [\"v1\", \"v2\"], dict(v1=0, v2=0) )\ndesired = [[None, 1.0], [2.0, 3.0], [4.0, 5.0], [6.0, 7.0], \n [8.0, 9.0], [10.0, 11.0], [12.0, 13.0], [14.0, 15.0], \n [16.0, 17.0], [18.0, 19.0]]\n \nskip = any([not pandasOK, not numpyOK, not isCPython]) # --> pypy\n\n\ndef setUp():\n os.chdir(gettempdir())\n \ndef tearDown():\n for item in os.listdir(\".\"):\n if re.match(r\"output_*\\.sav\", item):\n os.remove(item)\n \n@with_setup(setUp, tearDown)\ndef test_writerows_numpy():\n if skip:\n raise SkipTest\n data = [range(10), range(10, 20)]\n array = np.array(data, dtype=np.float64).reshape(10, 2)\n array[0, 0] = np.nan\n savFileName = \"output_np.sav\"\n with srw.SavWriter(savFileName, *args) as writer:\n writer.writerows(array)\n with srw.SavReader(savFileName, recodeSysmisTo=None) as reader:\n actual = reader.all(False)\n assert actual == desired, actual\n \ndef test_writerows_pandas():\n if skip:\n raise SkipTest\n df = pd.DataFrame({\"a\": range(0, 20, 2), \"b\": range(1, 20, 2)})\n df.loc[0, \"a\"] = np.nan\n savFileName = \"output_pd.sav\"\n with srw.SavWriter(savFileName, *args) as writer:\n writer.writerows(df)\n with srw.SavReader(savFileName) as reader:\n actual = reader.all(False)\n assert actual == desired, actual\n\ndef test_writerows_namedtuple():\n Record = namedtuple(\"Record\", args[0])\n records = [Record(*record) for record in desired]\n savFileName = \"output_namedtuple.sav\"\n with srw.SavWriter(savFileName, *args) as writer:\n writer.writerows(records)\n with srw.SavReader(savFileName) as reader:\n actual = reader.all(False)\n assert actual == desired, actual\n \ndef test_writerows_tuple():\n records = tuple([tuple(record) for record in desired])\n savFileName = \"output_tuple.sav\"\n with srw.SavWriter(savFileName, *args) as writer:\n writer.writerows(records)\n with srw.SavReader(savFileName) as reader:\n actual = reader.all(False)\n assert actual == desired, actual\n\ndef test_writerows_erroneous_flat_n():\n records = [0, 1] # wrong!,\n savFileName = \"output_error1.sav\"\n with srw.SavWriter(savFileName, *args) as writer:\n assert_raises(TypeError, writer.writerows, records)\n\ndef test_writerows_erroneous_flat_s():\n records = [\"a\", \"b\"] # wrong!\n string_args = [\"v1\", \"v2\"], dict(v1=1, v2=1)\n savFileName = \"output_error2.sav\"\n with srw.SavWriter(savFileName, *string_args) as writer:\n assert_raises(TypeError, writer.writerows, records)\n\ndef test_writerows_erroneous_flat_empty():\n records = [] # wrong!\n string_args = [\"v1\", \"v2\"], dict(v1=1, v2=1)\n savFileName = \"output_error3.sav\"\n with srw.SavWriter(savFileName, *string_args) as writer:\n assert_raises(ValueError, writer.writerows, records)\n \nif __name__ == \"__main__\":\n\n nose.main()\n"
] |
[
[
"numpy.array"
]
] |
uon-language/uon-parser
|
[
"666894cf4917d8da01512918a147882550382269"
] |
[
"uontypes/scalars/uon_float.py"
] |
[
"import numpy as np\n\nfrom uontypes.scalars.uon_numeric import UonNumeric\n\n\nclass UonFloat(UonNumeric):\n \"\"\"A Uon type to represent floats.\n In reality, the float represented by this class are what\n we refer to as decimal real in the uon specification.\n \"\"\"\n def __init__(self, value, uon_type, precision, unit=None,\n presentation_properties={}):\n super().__init__(value, uon_type, precision, unit,\n presentation_properties)\n\n\nclass Float16(UonFloat):\n \"\"\"\n https://stackoverflow.com/questions/38975770/python-numpy-float16-datatype-operations-and-float8\n \"\"\"\n pass\n\n\nclass Float32(UonFloat):\n def __init__(self, value, unit=None, presentation_properties={}):\n v = np.float32(value)\n super().__init__(v, \"float32\", 32, unit, presentation_properties)\n\n def to_binary(self):\n return b\"\\x23\" + super().to_binary()\n\n\nclass Float64(UonFloat):\n def __init__(self, value, unit=None, presentation_properties={}):\n v = np.float64(value)\n super().__init__(v, \"float64\", 64, unit, presentation_properties)\n\n def to_binary(self):\n return b\"\\x24\" + super().to_binary()\n\n\nclass Float128(UonFloat):\n def __init__(self, value, unit=None, presentation_properties={}):\n v = np.float128(value)\n super().__init__(v, \"float128\", 128, unit, presentation_properties)\n\n def to_binary(self):\n return b\"\\x25\" + super().to_binary()\n"
] |
[
[
"numpy.float64",
"numpy.float32",
"numpy.float128"
]
] |
TekNCode/cuda_tensorflow_opencv
|
[
"a532c869115bdb13d18d0e2495d5bb6d9b133e01"
] |
[
"test/tf_hw.py"
] |
[
"import tensorflow as tf\nfrom tensorflow.python.client import device_lib\n\nprint(\"*** Tensorflow version : \", tf.__version__)\nprint(\"*** Tensorflow Keras : \", tf.keras.__version__)\n\nprint(\"*** TF Builf with cuda : \", tf.test.is_built_with_cuda())\nprint(\"*** TF compile flags : \", tf.sysconfig.get_compile_flags())\nprint(\"*** TF include : \", tf.sysconfig.get_include())\nprint(\"*** TF lib : \", tf.sysconfig.get_lib())\nprint(\"*** TF link flags : \", tf.sysconfig.get_link_flags())\n\nimport cv2\nprint(\"*** OpenCV version : \", cv2.__version__)\n\nimport keras\nprint(\"*** Keras version : \", keras.__version__)\n\nimport torch\nprint(\"*** PyTorch version : \", torch.__version__)\n\nimport torchaudio\nprint(\" *** PyTorch Audio : \", torchaudio.__version__)\n\nimport torchvision\nprint(\" *** PyTorch Vision : \", torchvision.__version__)\n\n\nimport pandas\nprint(\"*** pandas version : \", pandas.__version__)\n\nimport sklearn\nprint(\"*** scikit-learn version : \", sklearn.__version__)\n\nprint(\"\")\nprint(\"(!! the following is build device specific, and here only to confirm hardware availability, ignore !!)\")\nprint(\"--- All seen hardware :\\n\", device_lib.list_local_devices())\nprint(\"--- TF GPU Available :\\n\", tf.config.experimental.list_physical_devices('GPU'))\n\n"
] |
[
[
"tensorflow.python.client.device_lib.list_local_devices",
"tensorflow.sysconfig.get_link_flags",
"tensorflow.test.is_built_with_cuda",
"tensorflow.config.experimental.list_physical_devices",
"tensorflow.sysconfig.get_lib",
"tensorflow.sysconfig.get_include",
"tensorflow.sysconfig.get_compile_flags"
]
] |
yidan216home/TensorFlowOnSpark
|
[
"42606480125e0cd163fdf5e8ef977b0ced61beb3"
] |
[
"src/com/yahoo/ml/tf/dfutil.py"
] |
[
"# Copyright 2017 Yahoo Inc.\n# Licensed under the terms of the Apache 2.0 license.\n# Please see LICENSE file in the project root for terms.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\ndef toTFExample(dtypes):\n \"\"\"Helper function to convert a Spark DataFrame into serialized `tf.train.Example` bytestring.\n\n Note that `tf.train.Example` is a fairly flat structure with limited datatypes, e.g. `tf.train.FloatList`,\n `tf.train.Int64List`, and `tf.train.BytesList`, so most DataFrame types will be converted into one of these types.\n\n Args:\n dtypes: the `DataFrame.dtypes` of the source DataFrame.\n\n Returns:\n A mapPartition lambda function which converts the source DataFrame into `tf.train.Example` bytestring\n \"\"\"\n def _toTFExample(iter):\n import tensorflow as tf\n\n # supported type mappings between DataFrame.dtypes and tf.train.Feature types\n float_dtypes = ['float', 'double']\n int64_dtypes = ['boolean', 'tinyint', 'smallint', 'int', 'bigint', 'long']\n bytes_dtypes = ['string']\n float_list_dtypes = ['array<float>', 'array<double>']\n int64_list_dtypes = ['array<boolean>', 'array<tinyint>', 'array<smallint>', 'array<int>', 'array<bigint>', 'array<long>']\n\n def _toTFFeature(name, dtype, row):\n feature = None\n if dtype in float_dtypes:\n feature = (name, tf.train.Feature(float_list=tf.train.FloatList(value=[row[name]])))\n elif dtype in int64_dtypes:\n feature = (name, tf.train.Feature(int64_list=tf.train.Int64List(value=[row[name]])))\n elif dtype in bytes_dtypes:\n feature = (name, tf.train.Feature(bytes_list=tf.train.BytesList(value=[str(row[name])])))\n elif dtype in float_list_dtypes:\n feature = (name, tf.train.Feature(float_list=tf.train.FloatList(value=row[name])))\n elif dtype in int64_list_dtypes:\n feature = (name, tf.train.Feature(int64_list=tf.train.Int64List(value=row[name])))\n else:\n raise Exception(\"Unsupported dtype: {0}\".format(dtype))\n return feature\n\n results = []\n for row in iter:\n features = dict([_toTFFeature(name, dtype, row) for name, dtype in dtypes])\n example = tf.train.Example(features=tf.train.Features(feature=features))\n results.append(example.SerializeToString())\n return results\n\n return _toTFExample\n\ndef fromTFExample(bytestr):\n \"\"\"Helper function to deserialize a `tf.train.Example` from a bytestring.\"\"\"\n import tensorflow as tf\n example = tf.train.Example()\n example.ParseFromString(bytestr)\n return example\n"
] |
[
[
"tensorflow.train.Int64List",
"tensorflow.train.FloatList",
"tensorflow.train.Features",
"tensorflow.train.Example"
]
] |
Pratyush1991/crop-type-mapping
|
[
"d9d99ec92c3a090ec5576f9e46c89dfcc6f50cf3"
] |
[
"src/models/TransformerEncoder.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.utils.data\nimport os\nfrom models.ClassificationModel import ClassificationModel\nfrom models.transformer.Models import Encoder\n\nSEQUENCE_PADDINGS_VALUE=-1\n\nclass TransformerEncoder(ClassificationModel):\n def __init__(self, in_channels=13, len_max_seq=100,\n d_word_vec=512, d_model=512, d_inner=2048,\n n_layers=6, n_head=8, d_k=64, d_v=64,\n dropout=0.2, nclasses=6):\n\n self.d_model = d_model\n\n super(TransformerEncoder, self).__init__()\n\n self.inlayernorm = nn.LayerNorm(in_channels)\n self.convlayernorm = nn.LayerNorm(d_model)\n self.outlayernorm = nn.LayerNorm(d_model)\n\n self.inconv = torch.nn.Conv1d(in_channels, d_model, 1)\n\n self.encoder = Encoder(\n n_src_vocab=None, len_max_seq=len_max_seq,\n d_word_vec=d_word_vec, d_model=d_model, d_inner=d_inner,\n n_layers=n_layers, n_head=n_head, d_k=d_k, d_v=d_v,\n dropout=dropout)\n\n self.outlinear = nn.Linear(d_model, nclasses, bias=False)\n\n self.tempmaxpool = nn.MaxPool1d(int(len_max_seq))\n\n self.logsoftmax = nn.LogSoftmax(dim=-1)\n\n def _logits(self, x):\n # b,d,t - > b,t,d\n x = x.transpose(1,2)\n\n x = self.inlayernorm(x)\n\n # b,\n x = self.inconv(x.transpose(1,2)).transpose(1,2)\n\n x = self.convlayernorm(x)\n\n batchsize, seq, d = x.shape\n src_pos = torch.arange(1, seq + 1, dtype=torch.long).expand(batchsize, seq)\n\n if torch.cuda.is_available():\n src_pos = src_pos.cuda()\n\n enc_output, enc_slf_attn_list = self.encoder.forward(src_seq=x, src_pos=src_pos, return_attns=True)\n\n enc_output = self.outlayernorm(enc_output)\n\n enc_output = self.tempmaxpool(enc_output.transpose(1, 2)).squeeze(-1)\n\n logits = self.outlinear(enc_output)\n\n return logits, None, None, None\n\n def forward(self, x):\n\n logits, *_ = self._logits(x)\n\n logprobabilities = self.logsoftmax(logits)\n\n return logprobabilities, None, None, None\n\n def save(self, path=\"model.pth\", **kwargs):\n print(\"\\nsaving model to \"+path)\n model_state = self.state_dict()\n os.makedirs(os.path.dirname(path), exist_ok=True)\n torch.save(dict(model_state=model_state,**kwargs),path)\n\n def load(self, path):\n print(\"loading model from \"+path)\n snapshot = torch.load(path, map_location=\"cpu\")\n model_state = snapshot.pop('model_state', snapshot)\n self.load_state_dict(model_state)\n return snapshot\n\n"
] |
[
[
"torch.nn.LogSoftmax",
"torch.load",
"torch.arange",
"torch.nn.LayerNorm",
"torch.nn.Linear",
"torch.cuda.is_available",
"torch.nn.Conv1d"
]
] |
zmitchell/trcdproc
|
[
"dbae216deeb56774bdeba18b92657118f83928f5"
] |
[
"tests/test_compute_absorp.py"
] |
[
"from os import remove\n\nimport h5py\nimport numpy as np\nfrom pytest import fixture, raises\n\nimport trcdproc.compute.absorp as compute\n\n\n@fixture(scope='function')\ndef delta_a_clean_input_data():\n \"\"\"Constructs an HDF5 file with specific values for the different signals for the sake of\n testing the correctness of the computed change in absorption\n\n The change in absorption (dA) is calculated by with the following equation:\n dA = -log10(\n (probe with pump) / (ref with pump)\n /\n (probe without pump) / (ref without pump)\n )\n\n The test should reveal whether the correct value is being produced, and whether the probe\n signals are being divided by their corresponding reference signals. For this reason the\n following values have been chosen for the various signals:\n probe with pump = 300 (both perp and par)\n reference with pump = 3\n probe without pump = 20 (both per and par)\n reference without pump = 2\n For these values the expected change in absorption is -1.\n \"\"\"\n filename = 'delta_a_inputs.h5'\n file = h5py.File(filename, 'w', libver='latest')\n group = file.require_group('/rounds/round000/76487')\n pump = group.create_group('pump')\n nopump = group.create_group('nopump')\n # create the data for the dA calculations\n probe_with_pump_value = 300\n ref_with_pump_value = 3\n probe_without_pump_value = 20\n ref_without_pump_value = 2\n time_data = np.arange(0, 101, 1, dtype=np.float64)\n points = 100\n probe_with_pump = np.empty(points, dtype=np.float64)\n probe_with_pump.fill(probe_with_pump_value)\n probe_without_pump = np.empty(points, dtype=np.float64)\n probe_without_pump.fill(probe_without_pump_value)\n ref_with_pump = np.empty(points, dtype=np.float64)\n ref_with_pump.fill(ref_with_pump_value)\n ref_without_pump = np.empty(points, dtype=np.float64)\n ref_without_pump.fill(ref_without_pump_value)\n pump.create_dataset('time', data=time_data, dtype=np.float64)\n pump.create_dataset('perp', data=probe_with_pump, dtype=np.float64)\n pump.create_dataset('par', data=probe_with_pump, dtype=np.float64)\n pump.create_dataset('ref', data=ref_with_pump, dtype=np.float64)\n nopump.create_dataset('time', data=time_data, dtype=np.float64)\n nopump.create_dataset('perp', data=probe_without_pump, dtype=np.float64)\n nopump.create_dataset('par', data=probe_without_pump, dtype=np.float64)\n nopump.create_dataset('ref', data=ref_without_pump, dtype=np.float64)\n yield file\n # clean up\n file.close()\n remove(filename)\n\n\n@fixture(scope='function')\ndef data_for_baseline_adjustment():\n \"\"\"Produces an HDF5 file with constant data in each channel for testing whether the baseline\n adjustment works properly.\n \"\"\"\n filename = 'baseline.h5'\n file = h5py.File(filename, 'w', libver='latest')\n wav_group = file.require_group('/rounds/round000/76487')\n # generate the data\n time_data = np.ones(50_000, dtype=np.float64)\n perp_data = np.ones(50_000, dtype=np.float64)\n par_data = np.empty(50_000, dtype=np.float64)\n par_data.fill(2.0)\n wav_group.create_dataset('time', data=time_data, dtype=np.float64)\n wav_group.create_dataset('perp', data=perp_data, dtype=np.float64)\n wav_group.create_dataset('par', data=par_data, dtype=np.float64)\n yield file\n # clean up\n file.close()\n remove(filename)\n\n\n@fixture(scope='function')\ndef data_for_collapse():\n filename = 'collapse.h5'\n file = h5py.File(filename, 'w', libver='latest')\n time_data = np.asarray([1, 2, 3, 4, 5, 6], dtype=np.float64)\n abs_data = np.asarray([1, 2, 3, 1, 2, 3], dtype=np.float64)\n file.create_dataset('time', data=time_data, dtype=np.float64)\n file.create_dataset('perp', data=abs_data, dtype=np.float64)\n yield file\n # clean up\n file.close()\n remove(filename)\n\n\ndef test_compute_single_clean_delta_a(delta_a_clean_input_data, starts_empty):\n \"\"\"Verifies that the expected change in absorption is calculated with clean data\n i.e. data that does not produce NaN when the logarithm is computed\n \"\"\"\n wavelength_group = delta_a_clean_input_data['rounds/round000/76487']\n compute.compute_single_delta_a(wavelength_group, starts_empty)\n perp_delta_a = starts_empty['perp'][0]\n par_delta_a = starts_empty['par'][0]\n assert perp_delta_a < -0.99\n assert perp_delta_a > -1.01\n assert par_delta_a < -0.99\n assert par_delta_a > -1.01\n\n\ndef test_compute_single_delta_a_with_nans(delta_a_clean_input_data, starts_empty):\n \"\"\"Verifies that no NaNs make it into the output when the logarithm is taken of\n a negative number.\n \"\"\"\n wavelength_group = delta_a_clean_input_data['rounds/round000/76487']\n wavelength_group['pump/perp'][...] *= -1\n compute.compute_single_delta_a(wavelength_group, starts_empty)\n should_be_zero = starts_empty['perp'][0]\n assert should_be_zero == 0\n\n\ndef test_compute_all_delta_a(delta_a_clean_input_data, starts_empty):\n \"\"\"Verifies that all of the data in the original file makes it into the new file\n \"\"\"\n rounds_root = delta_a_clean_input_data['rounds']\n rounds_root.copy(rounds_root['round000/76487'], rounds_root['round000'], name='76715')\n rounds_root.copy(rounds_root['round000'], rounds_root, name='round001')\n compute.compute_all_delta_a(delta_a_clean_input_data, starts_empty)\n for rnd in ['round000', 'round001']:\n for wav in ['76487', '76715']:\n for sig in ['perp', 'par']:\n path = f'rounds/{rnd}/{wav}/{sig}'\n delta_a = starts_empty[path][0]\n assert delta_a < -0.99\n assert delta_a > -1.01\n\n\ndef test_compute_only_good_delta_a(delta_a_clean_input_data, starts_empty):\n \"\"\"Verifies that the change in absorption is calculated for wavelength groups that have a value\n of `False` for the `isbad` attribute.\n \"\"\"\n rounds_root = delta_a_clean_input_data['rounds']\n rounds_root.copy(rounds_root['round000/76487'], rounds_root['round000'], name='76715')\n rounds_root['round000/76487'].attrs['isbad'] = True\n rounds_root['round000/76715'].attrs['isbad'] = False\n compute.compute_only_good_delta_a(delta_a_clean_input_data, starts_empty)\n with raises(KeyError):\n does_not_exist = starts_empty['rounds/round000/76487'] # noqa\n delta_a = starts_empty['rounds/round000/76715/perp'][0]\n assert delta_a < -0.99\n assert delta_a > -1.01\n\n\ndef test_baseline_adjustment(data_for_baseline_adjustment, starts_empty):\n \"\"\"Verifies that the baseline adjustment is done properly for each channel individually.\n \"\"\"\n compute.adjust_baseline(data_for_baseline_adjustment, starts_empty)\n for chan in ['time', 'perp', 'par']:\n path = f'rounds/round000/76487/{chan}'\n if chan == 'time':\n assert starts_empty[path][0] > 0.99 # time shouldn't be adjusted\n assert starts_empty[path][0] < 1.01\n else:\n assert starts_empty[path][0] > -0.01\n assert starts_empty[path][0] < 0.01\n\n\ndef test_collapse_single(data_for_collapse):\n \"\"\"Verifies that the collapse algorithm works as intended.\n \"\"\"\n time_data = data_for_collapse['time']\n abs_data = data_for_collapse['perp']\n collapsed_time, collapsed_abs = compute.collapse(time_data, abs_data, 3)\n for a in collapsed_abs:\n assert a > 1.99\n assert a < 2.01\n assert collapsed_time[0] > 1.99\n assert collapsed_time[0] < 2.01\n assert collapsed_time[1] > 4.99\n assert collapsed_time[1] < 5.01\n"
] |
[
[
"numpy.asarray",
"numpy.arange",
"numpy.empty",
"numpy.ones"
]
] |
g8a9/interpretable-trading
|
[
"f2f345a0ddf20f556a0b128972cc001691bb9513"
] |
[
"src/models/lstm.py"
] |
[
"import numpy as np\nfrom pytorch_lightning import callbacks\nimport torch\nimport pytorch_lightning as pl\nfrom torch.utils.data import Dataset, DataLoader\nfrom sklearn.model_selection import train_test_split\nfrom torch import nn\nfrom collections import Counter\nimport os\nimport torchmetrics as tm\nfrom pytorch_lightning.loggers import CometLogger\n\n\nclass LSTMClassifier(pl.LightningModule):\n def __init__(\n self,\n input_size,\n hidden_size,\n num_layers,\n num_classes,\n batch_size,\n learning_rate,\n reduce_lr=False,\n bidirectional=False,\n stateful=False,\n class_weights=None,\n ):\n super().__init__()\n\n self.num_directions = (\n 2 if bidirectional else 1\n ) # TODO I don't think this can be bidirectional though\n\n self.save_hyperparameters()\n\n self.lstm = nn.LSTM(\n input_size,\n hidden_size,\n num_layers,\n dropout=0.1,\n batch_first=True,\n bidirectional=bidirectional,\n )\n self.dropout = nn.Dropout(0.1)\n\n if bidirectional:\n self.linear = nn.Linear(hidden_size * 2, num_classes)\n else:\n self.linear = nn.Linear(hidden_size, num_classes)\n\n if stateful:\n h_n, c_n = self.init_hidden()\n self.register_buffer(\"hidden_h_n\", h_n)\n self.register_buffer(\"hidden_c_n\", c_n)\n\n self.loss_fct = nn.CrossEntropyLoss(weight=class_weights)\n\n self.val_F1 = tm.F1(num_classes=num_classes, average=\"weighted\")\n self.val_acc = tm.Accuracy(num_classes=num_classes, average=\"weighted\")\n\n def save_last_hidden(self):\n self.last_hidden = (self.hidden_h_n.detach(), self.hidden_c_n.detach())\n\n def init_hidden(self):\n # save last hidden states right before wiping them\n return (\n torch.zeros(\n self.hparams.num_layers * self.num_directions,\n self.hparams.batch_size,\n self.hparams.hidden_size,\n ),\n torch.zeros(\n self.hparams.num_layers * self.num_directions,\n self.hparams.batch_size,\n self.hparams.hidden_size,\n ),\n )\n\n def forward(self, inputs):\n if self.hparams.stateful and getattr(self, \"hidden\", None):\n # TODO this won't work if the batch_size is not a dividend of the dataset length\n out, (h_n, c_n) = self.lstm(inputs, (self.hidden_h_n, self.hidden_c_n))\n else:\n out, (h_n, c_n) = self.lstm(inputs)\n\n # keep states between batches\n if self.hparams.stateful:\n self.hidden_h_n = h_n.detach()\n self.hidden_c_n = c_n.detach()\n\n batch_size = inputs.shape[0]\n\n if self.num_directions == 1:\n h_n = h_n.view(\n self.hparams.num_layers,\n self.num_directions,\n batch_size,\n self.hparams.hidden_size,\n )\n\n # use only the last output\n last_hidden = h_n[-1, :, :]\n last_hidden = last_hidden.transpose(0, 1).squeeze(1)\n last_hidden = self.dropout(last_hidden)\n out = self.linear(last_hidden)\n else:\n h_n = h_n.view(\n self.hparams.num_layers,\n batch_size,\n self.hparams.hidden_size * 2,\n )\n # use only the last output\n last_hidden = h_n[-1, :, :]\n last_hidden = self.dropout(last_hidden)\n out = self.linear(last_hidden)\n\n return out\n\n def training_step(self, batch, batch_idx):\n X, y = batch\n out = self(X)\n loss = self.loss_fct(out, y)\n self.log(\"train_loss\", loss, prog_bar=True)\n return loss\n\n def validation_step(self, batch, batch_idx):\n X, y = batch\n out = self(X)\n loss = self.loss_fct(out, y)\n\n self.val_acc(out.argmax(-1), y)\n self.val_F1(out.argmax(-1), y)\n\n self.log(\"val_loss\", loss)\n self.log(\"val_acc\", self.val_acc, on_step=False, on_epoch=True)\n self.log(\"val_F1\", self.val_F1, on_step=False, on_epoch=True)\n\n def test_step(self, batch, batch_idx):\n X, y = batch\n out = self(X)\n loss = self.loss_fct(out, y)\n self.log(\"test_loss\", loss)\n\n def training_epoch_end(self, outputs):\n if self.hparams.stateful:\n self.save_last_hidden()\n self.hidden_h_n, self.hidden_c_n = self.init_hidden()\n\n def validation_epoch_end(self, outputs):\n if self.hparams.stateful:\n self.save_last_hidden()\n self.hidden_h_n, self.hidden_c_n = self.init_hidden()\n\n def configure_optimizers(self):\n optimizer = torch.optim.Adam(self.parameters(), lr=self.hparams.learning_rate)\n\n if self.hparams.reduce_lr > 0:\n return {\n \"optimizer\": optimizer,\n \"lr_scheduler\": {\n \"scheduler\": torch.optim.lr_scheduler.ReduceLROnPlateau(\n optimizer, patience=self.hparams.reduce_lr\n ),\n \"monitor\": \"val_loss\",\n },\n }\n else:\n return optimizer\n\n\ndef labels_to_torchlabels(labels):\n d = {-1: 0, 0: 1, 1: 2}\n return np.vectorize(d.get)(labels)\n\n\ndef torchlabels_to_labels(labels):\n d = {0: -1, 1: 0, 2: 1}\n return np.vectorize(d.get)(labels)\n\n\ndef create_examples(data: np.array, targets: np.array, seq_length):\n data_len = data.shape[0]\n\n seqs = list()\n for i in range(data_len - seq_length):\n X = torch.from_numpy(data[i : i + seq_length, :]).float()\n y = torch.tensor(targets[i + seq_length], dtype=torch.long)\n seqs.append((X, y))\n\n print(f\"Created {len(seqs)} sequences\")\n return seqs\n\n\ndef get_class_weights(labels):\n counter = Counter(labels)\n class_weights = list()\n for c in sorted(list(counter.keys())):\n class_weights.append(1 - counter[c] / len(labels))\n\n weights = torch.tensor(class_weights, dtype=torch.float)\n return weights\n\n\nclass SequenceDataset(Dataset):\n def __init__(self, sequences):\n self.sequences = sequences\n\n def __len__(self):\n return len(self.sequences)\n\n def __getitem__(self, idx):\n return self.sequences[idx]\n\n\ndef train(\n X_train: np.array,\n y_train: np.array,\n num_classes,\n seq_length,\n batch_size,\n max_epochs,\n lr,\n reduce_lr,\n gpus,\n seed,\n early_stop,\n stateful,\n **kwargs,\n):\n pl.seed_everything(seed)\n\n # y_train = y_train.to_numpy()\n # y_test = y_test.to_numpy()\n\n # if num_classes == 3:\n # # use only labels >= 0\n # y_train = labels_to_torchlabels(y_train)\n # y_test = labels_to_torchlabels(y_test)\n\n class_weights = get_class_weights(y_train)\n\n # TODO can we modify class weights in a better way?\n # class_weights[0] *= 2\n # class_weights[2] *= 2\n\n X_train = X_train.to_numpy()\n y_train = y_train.to_numpy()\n\n print(\"Class weights computed:\", class_weights)\n\n # create the sequences for LSTM\n sequences = create_examples(X_train, y_train, seq_length)\n\n # use 20% of the training set for validation\n train, val = train_test_split(\n sequences, train_size=0.9, shuffle=False, random_state=42\n )\n\n train_dataloader = DataLoader(\n SequenceDataset(train), batch_size=batch_size, shuffle=False\n )\n val_dataloader = DataLoader(\n SequenceDataset(val), batch_size=batch_size, shuffle=False\n )\n\n model = LSTMClassifier(\n input_size=X_train.shape[1],\n hidden_size=512,\n num_layers=2,\n num_classes=num_classes,\n batch_size=batch_size,\n stateful=stateful,\n class_weights=class_weights,\n learning_rate=lr,\n reduce_lr=reduce_lr,\n bidirectional=False,\n )\n\n model_checkpoint = pl.callbacks.ModelCheckpoint(\n monitor=\"val_loss\",\n dirpath=kwargs[\"model_dir\"],\n filename=f\"{kwargs['tick']}-\" + \"-{epoch}-{val_loss:.3f}-{train_loss:.3f}\",\n )\n callbacks = [model_checkpoint]\n\n if early_stop > 0:\n callbacks.append(pl.callbacks.EarlyStopping(\"val_loss\", patience=early_stop))\n\n # loggers\n if kwargs[\"comet_experiment\"]:\n comet_logger = CometLogger(\n save_dir=\".\",\n workspace=\"trading\", # Optional\n project_name=\"interpretable-trading\", # Optional\n )\n comet_logger.experiment = kwargs[\"comet_experiment\"]\n else:\n comet_logger = None\n\n # Initialize a trainer\n trainer = pl.Trainer(\n gpus=gpus, max_epochs=max_epochs, callbacks=callbacks, logger=comet_logger\n )\n\n # Train the model ⚡\n trainer.fit(model, train_dataloader, val_dataloader)\n\n return model_checkpoint.best_model_path\n\n\ndef test(model_path, X_train, X_test, y_train, y_test, seq_length, batch_size):\n X_train = X_train.to_numpy()\n X_test = X_test.to_numpy()\n y_train = y_train.to_numpy()\n y_test = y_test.to_numpy()\n\n # Create the test sequences. TODO Is this correct?\n test_sequences = create_examples(\n np.concatenate((X_train[-seq_length:, :], X_test), axis=0),\n np.concatenate((y_train[-seq_length:], y_test), axis=0),\n seq_length,\n )\n\n test_dataloader = DataLoader(\n SequenceDataset(test_sequences), batch_size=batch_size, shuffle=False\n )\n\n # Load the model and predict the test set\n best_model = LSTMClassifier.load_from_checkpoint(model_path).eval()\n\n with torch.no_grad():\n y_preds = list()\n\n for batch in test_dataloader:\n X, y = batch\n out = best_model(X)\n y_preds.append(out.argmax(-1)) # batch x 1\n\n y_preds = torch.cat(y_preds).squeeze(-1).numpy()\n\n return y_preds\n"
] |
[
[
"torch.nn.CrossEntropyLoss",
"torch.nn.Dropout",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"torch.nn.LSTM",
"torch.zeros",
"torch.cat",
"sklearn.model_selection.train_test_split",
"torch.from_numpy",
"torch.tensor",
"numpy.concatenate",
"torch.nn.Linear",
"numpy.vectorize",
"torch.no_grad"
]
] |
jaeseoko/16833_ParticleFilter
|
[
"77fbff72800726e7198984c23a4990c6cd525580"
] |
[
"problem_set/code/sensor_model.py"
] |
[
"'''\n Adapted from course 16831 (Statistical Techniques).\n Initially written by Paloma Sodhi ([email protected]), 2018\n Updated by Wei Dong ([email protected]), 2021\n'''\n\n# import cv2\nfrom tqdm import tqdm\nimport numpy as np\nimport math\nimport time\nfrom matplotlib import pyplot as plt\nfrom scipy.stats import norm\n\nfrom map_reader import MapReader\n\n# variables :\n#LaserReadings = [x, y, theta, xl, yl, thetal, r1......r180]\n#\n# parameters :\n#zHit, zRand, zShort, zMax, sigmaHit, lambdaShort\n#L = 25 , n = laser beam numbers\n\n\ndef occupancy(x, resolution, occupancy_map):\n xMap = int(math.floor(x[0]//resolution))\n yMap = int(math.floor(x[1]//resolution))\n return occupancy_map[xMap,yMap]\n\ndef inBound(x, resolution, mapSize):\n xMap = math.floor(x[0]//resolution)\n \n yMap = math.floor(x[1]//resolution)\n \n if (xMap>=0) and (xMap< mapSize) and (yMap >=0) and (yMap<mapSize):\n return True\n else:\n return False \n\n\n\nclass SensorModel:\n \"\"\"\n References: Thrun, Sebastian, Wolfram Burgard, and Dieter Fox. Probabilistic robotics. MIT press, 2005.\n [Chapter 6.3]\n \"\"\"\n def __init__(self, occupancy_map):\n \"\"\"\n TODO : Tune Sensor Model parameters here\n The original numbers are for reference but HAVE TO be tuned.\n \"\"\"\n # self._z_hit = 1*100\n # self._z_short = 0.1\n # self._z_max = 0.1*10\n # self._z_rand = 100*10\n # # # self._z_rand = 100\n # self._sigma_hit = 50*10\n # self._lambda_short = 0.1\n \n '''\n sort of working numbers >>\n '''\n self._z_hit = 1500\n self._z_short = 175\n self._z_max = 150\n self._z_rand = 200\n self._sigma_hit = 100\n self._lambda_short = 15\n '''\n << sort of working numbers\n '''\n\n self.norm = norm\n\n # self._max_range = 8183\n self._min_probability = 0.35\n self._subsampling = 2\n\n # self._norm_wts = 1.0\n '''\n actual laser max range is 8183 but this is tunable and so far this number works >>\n '''\n self.laserMax = 2183\n '''\n <<< actual laser max range is 8183 but this is tunable and so far this number works\n '''\n # self.laserMax = 1000\n self.OccMap = occupancy_map\n self.OccMapSize = np.size(occupancy_map)\n\n self.nLaser = 30\n\n self.laserX = np.zeros((self.nLaser,1))\n self.laserY = np.zeros((self.nLaser,1))\n self.beamsRange = np.zeros((self.nLaser,1))\n\n self.resolution = 10\n \n # print(\"OCCUPANCY MAP size : \\n\", np.shape(self.OccMap))\n # print(\"OccMapSize Initialized: \", self.OccMapSize)\n def WrapToPi(self,angle):\n \n angle_wrapped = angle - 2*np.pi * np.floor((angle + np.pi) / (2*np.pi))\n return angle_wrapped\n\n # def WrapAngle(self,angle): # -2pi to 2pi\n # if angle >= 2*np.pi:\n # angle -= (angle // (2*np.pi))*2*np.pi\n\n # elif angle <= -2*np.pi:\n # angle += (np.abs(angle) // (2*np.pi))*2*np.pi\n \n # return angle\n\n # def ConvTo90(self,angle): # -pi/2 to pi/2\n # if angle >= np.pi/2:\n # angle -= (angle // (np.pi/2))*np.pi/2\n # elif angle <= - np.pi/2:\n # angle += (angle // (np.pi/2))*np.pi/2\n # return angle\n\n # def getQuad(self,angle):\n # if (angle>=0 and angle<np.pi/2) or (angle>=-2*np.pi and angle <-3*np.pi/2):\n # quad = 1\n # elif (angle>=np.pi/2 and angle <np.pi) or (angle >= -3*np.pi/2 and angle < -np.pi):\n # quad = 2\n # elif (angle >= 3*np.pi/2 and angle <2*np.pi) or (angle >= -np.pi/2 and angle <0):\n # quad = 4\n # else:\n # quad = 3\n # return quad\n\n\n def getProbability_A(self, z_star, z_reading):\n # Hit\n if 0 < z_reading < self.laserMax:\n gauss_norm = self.norm.cdf(self.laserMax, loc=z_star, scale=self._sigma_hit) - self.norm.cdf(0,loc=z_star, scale=self._sigma_hit)\n gauss = self.norm.pdf(z_reading,loc=z_star, scale=self._sigma_hit) / gauss_norm\n else:\n gauss = 0\n \n # short\n if 0 < z_reading < z_star:\n exp = self._lambda_short*np.exp(-self._lambda_short*z_reading)\n exp *= 1/(1-np.exp(-self._lambda_short*z_star))\n else:\n exp = 0\n \n # Max\n if z_reading >= self.laserMax:\n p_max = 1\n else:\n p_max = 0\n \n # random\n if (z_reading > 0 and z_reading < self.laserMax):\n p_rand = 1/self.laserMax\n else:\n p_rand = 0\n p = self._z_hit*gauss + self._z_short*exp + self._z_max*p_max + self._z_rand*p_rand\n p /= (self._z_hit + self._z_short + self._z_max + self._z_rand)\n \n return p\n def getProbability_B(self, z_star, z_reading):\n # hit\n if z_reading >= 0 and z_reading <= self.laserMax:\n pHit = np.exp(-1/2 * (z_reading - z_star)**2 / (self._sigma_hit **2))\n pHit = pHit/(np.sqrt(2*np.pi*self._sigma_hit**2))\n \n else:\n pHit = 0\n\n # short\n if z_reading >= 0 and z_reading <= z_star:\n # eta = 1.0/(1-np.exp(-lambdaShort*z_star))\n eta = 1\n pShort = eta*self._lambda_short*np.exp(-self._lambda_short*z_reading)\n \n else:\n pShort = 0\n\n # max\n if z_reading >= self.laserMax:\n pMax = self.laserMax\n else:\n pMax = 0\n # rand\n if z_reading >=0 and z_reading < self.laserMax:\n pRand = 1/self.laserMax\n else:\n pRand = 0\n p = self._z_hit*pHit + self._z_short*pShort+ self._z_max*pMax + self._z_rand*pRand\n p /= (self._z_hit + self._z_short + self._z_max + self._z_rand)\n return p ,pHit, pShort, pMax, pRand\n\n def rayCast(self,x_t1,resolution):\n \n\n '''\n vectorizing (mask) ---\n '''\n # beamsRange = np.zeros(self.nLaser)\n # laserX = np.zeros(self.nLaser)\n # laserY = np.zeros(self.nLaser)\n # angs = np.zeros(self.nLaser)\n # L = 25\n\n # xc = x_t1[0]\n # yc = x_t1[1]\n # myPhi = x_t1[2]\n # ang = myPhi - np.pi/2\n # ang =self.WrapToPi(ang)\n # offSetX = xc + L* np.cos(ang)\n # offSetY = yc + L* np.sin(ang)\n \n # angStep = np.pi/self.nLaser\n # r = np.linspace(0,self.laserMax,500)\n \n # for i in range(self.nLaser):\n \n # ang += angStep*i\n # ang = self.WrapToPi(ang)\n # # casting rays\n # x = offSetX + r * np.cos(ang)\n # y = offSetY + r * np.sin(ang)\n\n # xInt = np.floor(x/self.resolution).astype(int)\n # yInt = np.floor(y/self.resolution).astype(int)\n\n \n # # mask = np.zeros_like(xInt).astype(bool)\n # # mask1= np.zeros_like(xInt).astype(bool)\n # # mask1[(xInt < 800) & (xInt>=0) & (yInt>=0) & (yInt < 800)] == True\n # # print(\"x\",xInt[mask1].shape,yInt[mask1].shape)\n # # print(\"asdfsaf\",self.OccMap[yInt[mask1],xInt[mask1]])\n\n # xWithin = np.argwhere(xInt<800)\n # yWithin = np.argwhere(yInt<800)\n # within = np.intersect1d(xWithin,yWithin)\n # hitInd = np.\n\n # ii = 0\n # for xx, yy in zip(xInt[mask1], yInt[mask1]):\n # if((np.abs(self.OccMap[yInt[xx],xInt[yy]]) > 0.35)):\n # idx = ii \n # break\n # ii+=1\n\n # idx = np.argwhere(mask1==True)[ii]\n # mask[(np.abs(self.OccMap[yInt[mask1],xInt[mask1]]) > 0.35)] == True\n # mask[((xInt < 800) & (yInt < 800)) & (np.abs(self.OccMap[yInt,xInt]) > 0.35)] == True\n # laserX[idx] = x[idx]\n # laserY[idx] = y[idx]\n\n # beamsRange = r[idx]\n \n\n ''' \n normal looping -----\n '''\n\n beamsRange = np.zeros(self.nLaser)\n laserX = np.zeros(self.nLaser)\n laserY = np.zeros(self.nLaser)\n angs = np.zeros(self.nLaser)\n L = 25\n\n xc = x_t1[0]\n yc = x_t1[1]\n myPhi = x_t1[2]\n ang = myPhi - np.pi/2\n ang =self.WrapToPi(ang)\n offSetX = xc + L* np.cos(ang)\n offSetY = yc + L* np.sin(ang)\n \n angStep = np.pi/self.nLaser\n \n '''\n set ray step size\n '''\n r = np.linspace(0,self.laserMax,200)\n \n for i in range(self.nLaser):\n \n ang += angStep\n # print(ang*180/np.pi)\n ang = self.WrapToPi(ang)\n # print(\"angle after wrapped: \",ang*180/np.pi)\n # print(\"current angle:\", ang*180/np.pi)\n # for idx, rs in enumerate(r):\n for rs in r:\n \n \n x = offSetX + rs*np.cos(ang)\n y = offSetY + rs*np.sin(ang)\n\n\n xInt = np.floor(x/self.resolution).astype(int)\n yInt = np.floor(y/self.resolution).astype(int)\n\n if xInt < 800 and yInt < 800 and np.abs(self.OccMap[yInt,xInt]) > 0.35:\n beamsRange[i] = rs\n phi = np.arctan2((offSetY -yInt), (offSetX - xInt)) #phase\n angs[i] = ang\n laserX[i] = xInt\n laserY[i] = yInt\n break\n # print(x,\",\",y)\n # print(np.abs(angs[0]*180/np.pi-angs[-1]*180/np.pi))\n\n \n \n # print(beamsRange)\n \n \n return beamsRange,laserX,laserY\n\n\n \n def beam_range_finder_model(self, z_t1_arr, x_t1):\n # print(\"\\n ---------\\nBEAM RANGE FINDER MODEL CALLED\\n ---------\\n\")\n\n \"\"\"\n param[in] z_t1_arr : laser range readings [array of 180 values] at time t\n param[in] x_t1 : particle state belief [x, y, theta] at time t [world_frame]\n param[out] prob_zt1 : likelihood of a range scan zt1 at time t\n \"\"\"\n \"\"\"\n TODO : Add your code here\n \"\"\"\n # q = 1\n \n\n '''\n q = 0\n # zt_star,self.laserX,self.laserY = rayCast(x_t1,resolution,nLaser,self.OccMap)\n \n # for i in range(nLaser):\n\n # pHit = pHitFun(z_t1_arr[i],zt_star[i],self._sigma_hit)\n # pShort = pShortFun(z_t1_arr[i],zt_star[i],self._lambda_short)\n # pMax = pMaxFun(z_t1_arr[i],self._z_max)\n # pRand = pRandFun(z_t1_arr[i],self._z_max)\n\n # p = self._z_hit*pHit + self._z_short*pShort + self._z_max*pMax + self._z_rand*pRand\n \n # q = q*p\n \n # if q==0:\n # q = 1e-20\n # return q\n '''\n # q = 1\n q = 0\n \n step = int(180/self.nLaser)\n z_reading = [z_t1_arr[n] for n in range(0,180,step)]\n # print(\"measure----\")\n # print(z_reading)\n zt_star,laserX,laserY = self.rayCast(x_t1,self.resolution)\n # print(\"my cast----\")\n # print(zt_star)\n '''\n # diff = z_reading - zt_star\n # print(\"difference = \")\n # print(diff)\n '''\n # print(np.size(z_reading))\n probs = np.zeros(self.nLaser)\n for i in range(self.nLaser):\n probs[i] ,pHit,pShort,pMax,Prand = self.getProbability_B(zt_star[i],z_reading[i])\n q += np.log(probs[i])\n # q = q*probs[i]\n q = 1.0/np.abs(q)\n return q, probs ,laserX, laserY\n \n # prob_zt1 = 1.0\n # return prob_zt1"
] |
[
[
"numpy.log",
"numpy.abs",
"numpy.linspace",
"numpy.sqrt",
"numpy.cos",
"numpy.sin",
"numpy.arctan2",
"numpy.size",
"numpy.floor",
"numpy.exp",
"numpy.zeros"
]
] |
adityaalifn/CSH3L3-Machine-Learning
|
[
"54cc6f0fda8f846c2577a0be21529aaa121b0631"
] |
[
"Support Vector Machine/Source Code/fun.py"
] |
[
"import matplotlib.pyplot as plt\nimport matplotlib\n\n\ndef scatter3d_visualize(X, y, title=\"\"):\n # Soal A nomer 1\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n for i in range(len(X)):\n xs = X[i][0]\n ys = X[i][1]\n zs = X[i][2]\n \n if y[i] == 0:\n bundar = ax.scatter(xs, ys, zs, c=\"r\", marker=\"o\", label=\"Kelas 0\")\n elif y[i] == 1:\n kotak = ax.scatter(xs, ys, zs, c=\"g\", marker=\"s\", label=\"Kelas 1\")\n elif y[i] == 2:\n segitiga = ax.scatter(\n xs, ys, zs, c=\"b\", marker=\"^\", label=\"Kelas 2\")\n\n ax.set_xlabel('X Label')\n ax.set_ylabel('Y Label')\n ax.set_zlabel('Z Label')\n plt.legend(handles=[bundar, kotak, segitiga])\n plt.title(title)\n plt.show()\n\n\ndef count_accuracy(y_pred, y_test):\n correctness = 0\n for yp, yt in zip(y_pred, y_test):\n if yp == yt:\n correctness += 1\n return correctness / len(y_pred) * 100\n"
] |
[
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.show",
"matplotlib.pyplot.title",
"matplotlib.pyplot.figure"
]
] |
aitoralmeida/lus_stratification
|
[
"8153a2dd4ddd49bac8c7d36269762ddd9207d72f"
] |
[
"convert_model/old/convert_keras_to_tflite_optimized.py"
] |
[
"import tensorflow as tf\nimport keras as k\n\nmodel = k.models.load_model('/results/covid19_model')\nconverter = tf.lite.TFLiteConverter.from_keras_model(model)\nconverter.optimizations = [tf.lite.Optimize.DEFAULT]\ntflite_model = converter.convert()\nopen(\"/results/covid19_model_optimized.tflite\", \"wb\").write(tflite_model)\n"
] |
[
[
"tensorflow.lite.TFLiteConverter.from_keras_model"
]
] |
salernoa/examples
|
[
"09354427ec282fc46037ffb1af7aea2eda63a167"
] |
[
"tensorflow_examples/lite/model_maker/core/task/image_classifier_test.py"
] |
[
"# Copyright 2019 The TensorFlow Authors. All Rights Reserved.\n#\n# Licensed under the Apache License, Version 2.0 (the 'License');\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an 'AS IS' BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport filecmp\nimport os\n\nimport numpy as np\nimport tensorflow.compat.v2 as tf\nfrom tensorflow_examples.lite.model_maker.core import compat\nfrom tensorflow_examples.lite.model_maker.core import model_export_format as mef\nfrom tensorflow_examples.lite.model_maker.core import test_util\nfrom tensorflow_examples.lite.model_maker.core.data_util import image_dataloader\nfrom tensorflow_examples.lite.model_maker.core.task import image_classifier\nfrom tensorflow_examples.lite.model_maker.core.task import metadata\nfrom tensorflow_examples.lite.model_maker.core.task import model_spec\n\n\ndef _fill_image(rgb, image_size):\n r, g, b = rgb\n return np.broadcast_to(\n np.array([[[r, g, b]]], dtype=np.uint8),\n shape=(image_size, image_size, 3))\n\n\nclass ImageClassifierTest(tf.test.TestCase):\n IMAGE_SIZE = 24\n IMAGES_PER_CLASS = 20\n CMY_NAMES_AND_RGB_VALUES = (('cyan', (0, 255, 255)),\n ('magenta', (255, 0, 255)), ('yellow', (255, 255,\n 0)))\n\n def _gen(self):\n for i, (_, rgb) in enumerate(self.CMY_NAMES_AND_RGB_VALUES):\n for _ in range(self.IMAGES_PER_CLASS):\n yield (_fill_image(rgb, self.IMAGE_SIZE), i)\n\n def _gen_cmy_data(self):\n ds = tf.data.Dataset.from_generator(\n self._gen, (tf.uint8, tf.int64), (tf.TensorShape(\n [self.IMAGE_SIZE, self.IMAGE_SIZE, 3]), tf.TensorShape([])))\n data = image_dataloader.ImageClassifierDataLoader(\n ds, self.IMAGES_PER_CLASS * 3, 3, ['cyan', 'magenta', 'yellow'])\n return data\n\n def setUp(self):\n super(ImageClassifierTest, self).setUp()\n all_data = self._gen_cmy_data()\n # Splits data, 90% data for training, 10% for testing\n self.train_data, self.test_data = all_data.split(0.9)\n\n @test_util.test_in_tf_2\n def test_mobilenetv2_model(self):\n model = image_classifier.create(\n self.train_data,\n mef.ModelExportFormat.TFLITE,\n model_spec.mobilenet_v2_spec,\n epochs=2,\n batch_size=4,\n shuffle=True)\n self._test_accuracy(model)\n self._test_export_to_tflite(model)\n self._test_predict_top_k(model)\n self._test_export_to_tflite_quantized(model, self.train_data)\n self._test_export_to_tflite_with_metadata(model)\n\n @test_util.test_in_tf_1\n def test_mobilenetv2_model_create_v1_incompatible(self):\n with self.assertRaisesRegex(ValueError, 'Incompatible versions'):\n _ = image_classifier.create(self.train_data, mef.ModelExportFormat.TFLITE,\n model_spec.mobilenet_v2_spec)\n\n @test_util.test_in_tf_1and2\n def test_efficientnetlite0_model_with_model_maker_retraining_lib(self):\n model = image_classifier.create(\n self.train_data,\n mef.ModelExportFormat.TFLITE,\n model_spec.efficientnet_lite0_spec,\n epochs=2,\n batch_size=4,\n shuffle=True,\n use_hub_library=False)\n self._test_accuracy(model)\n self._test_export_to_tflite(model)\n\n @test_util.test_in_tf_1and2\n def test_efficientnetlite0_model(self):\n model = image_classifier.create(\n self.train_data,\n mef.ModelExportFormat.TFLITE,\n model_spec.efficientnet_lite0_spec,\n epochs=2,\n batch_size=4,\n shuffle=True)\n self._test_accuracy(model)\n self._test_export_to_tflite(model)\n\n @test_util.test_in_tf_2\n def test_resnet_50_model(self):\n model = image_classifier.create(\n self.train_data,\n mef.ModelExportFormat.TFLITE,\n model_spec.resnet_50_spec,\n epochs=2,\n batch_size=4,\n shuffle=True)\n self._test_accuracy(model)\n self._test_export_to_tflite(model)\n\n def _test_predict_top_k(self, model, threshold=0.7):\n topk = model.predict_top_k(self.test_data, batch_size=4)\n for i, (_, label) in enumerate(self.test_data.dataset):\n predict_label, predict_prob = topk[i][0][0], topk[i][0][1]\n self.assertEqual(model.index_to_label[label], predict_label)\n self.assertGreater(predict_prob, threshold)\n\n def _test_accuracy(self, model, threashold=0.8):\n _, accuracy = model.evaluate(self.test_data)\n self.assertGreater(accuracy, threashold)\n\n def _load_labels(self, filename):\n with tf.io.gfile.GFile(filename, 'r') as f:\n return [label.strip() for label in f]\n\n def _load_lite_model(self, filename):\n self.assertTrue(os.path.isfile(filename))\n with tf.io.gfile.GFile(filename, 'rb') as f:\n model_content = f.read()\n interpreter = tf.lite.Interpreter(model_content=model_content)\n\n def lite_model(images):\n interpreter.allocate_tensors()\n input_index = interpreter.get_input_details()[0]['index']\n interpreter.set_tensor(input_index, images)\n interpreter.invoke()\n output_index = interpreter.get_output_details()[0]['index']\n return interpreter.get_tensor(output_index)\n\n return lite_model\n\n def _test_export_to_tflite(self, model):\n tflite_output_file = os.path.join(self.get_temp_dir(), 'model.tflite')\n labels_output_file = os.path.join(self.get_temp_dir(), 'label')\n model.export(tflite_output_file, labels_output_file)\n labels = self._load_labels(labels_output_file)\n self.assertEqual(labels, ['cyan', 'magenta', 'yellow'])\n lite_model = self._load_lite_model(tflite_output_file)\n\n test_ds = model._gen_dataset(\n self.test_data, batch_size=1, is_training=False)\n if compat.get_tf_behavior() == 1:\n iterator = test_ds.make_one_shot_iterator()\n image_tensor, label_tensor = iterator.get_next()\n with tf.compat.v1.Session() as sess:\n for _ in range(self.test_data.size):\n image, label = sess.run((image_tensor, label_tensor))\n output_batch = lite_model(image)\n prediction = np.argmax(output_batch[0])\n label = np.argmax(label[0])\n self.assertEqual(label, prediction)\n else:\n for image, label in test_ds:\n output_batch = lite_model(image.numpy())\n prediction = np.argmax(output_batch[0])\n label = np.argmax(label.numpy()[0])\n self.assertEqual(label, prediction)\n\n def _test_export_to_tflite_quantized(self, model, representative_data):\n # Just test whether quantization will crash, can't guarantee the result.\n tflite_output_file = os.path.join(self.get_temp_dir(),\n 'model_quantized.tflite')\n labels_output_file = os.path.join(self.get_temp_dir(), 'label')\n model.export(\n tflite_output_file,\n labels_output_file,\n quantized=True,\n representative_data=representative_data)\n self.assertTrue(os.path.isfile(tflite_output_file))\n self.assertGreater(os.path.getsize(tflite_output_file), 0)\n labels = self._load_labels(labels_output_file)\n self.assertEqual(labels, ['cyan', 'magenta', 'yellow'])\n\n def _test_export_to_tflite_with_metadata(self, model):\n model_name = 'model_with_metadata'\n tflite_output_file = os.path.join(self.get_temp_dir(),\n '%s.tflite' % model_name)\n json_output_file = os.path.join(self.get_temp_dir(), '%s.json' % model_name)\n labels_output_file = os.path.join(self.get_temp_dir(), 'label.txt')\n\n model.export(\n tflite_output_file,\n labels_output_file,\n with_metadata=True,\n export_metadata_json_file=True)\n\n self.assertTrue(os.path.isfile(tflite_output_file))\n self.assertGreater(os.path.getsize(tflite_output_file), 0)\n\n labels = self._load_labels(labels_output_file)\n self.assertEqual(labels, ['cyan', 'magenta', 'yellow'])\n\n if not metadata.TFLITE_SUPPORT_TOOLS_INSTALLED:\n return\n\n expected_json_file = test_util.get_test_data_path(\n 'mobilenet_v2_metadata.json')\n self.assertTrue(filecmp.cmp(json_output_file, expected_json_file))\n\n\nif __name__ == '__main__':\n compat.setup_tf_behavior(tf_version=2)\n tf.test.main()\n"
] |
[
[
"tensorflow.compat.v2.test.main",
"tensorflow.compat.v2.io.gfile.GFile",
"tensorflow.compat.v2.lite.Interpreter",
"numpy.argmax",
"tensorflow.compat.v2.compat.v1.Session",
"tensorflow.compat.v2.TensorShape",
"numpy.array"
]
] |
twesterhout/nqs-playground
|
[
"9fbb65a0631f2a0898effe5bfb1bbb41966cce65"
] |
[
"distributed_example.py"
] |
[
"import os\nimport re\nimport socket\nimport torch\nimport torch.distributed\n# import torch.multipro\n\ndef init_slurm(fn, backend=\"gloo\"):\n slurm_nodelist = os.environ[\"SLURM_NODELIST\"]\n root_node = slurm_nodelist.split(\" \")[0].split(\",\")[0]\n if \"[\" in root_node:\n name, numbers = root_node.split(\"[\", maxsplit=1)\n number = numbers.split(\",\", maxsplit=1)[0]\n if \"-\" in number:\n number = number.split(\"-\")[0]\n number = re.sub(\"[^0-9]\", \"\", number)\n root_node = name + number\n os.environ[\"MASTER_ADDR\"] = root_node\n\n port = os.environ[\"SLURM_JOB_ID\"]\n port = port[-4:] # use the last 4 numbers in the job id as the id\n port = int(port) + 15000 # all ports should be in the 10k+ range\n os.environ[\"MASTER_PORT\"] = str(port)\n\n rank = int(os.environ[\"SLURM_PROCID\"])\n world_size = int(os.environ[\"SLURM_NTASKS\"])\n torch.distributed.init_process_group(backend, rank=rank, world_size=world_size)\n fn()\n\ndef _local_init_process(rank, size, fn, backend):\n os.environ[\"MASTER_ADDR\"] = \"127.0.0.1\"\n os.environ[\"MASTER_PORT\"] = \"12910\"\n torch.distributed.init_process_group(backend, rank=rank, world_size=size)\n fn()\n\ndef init_local(size, fn, backend=\"gloo\"):\n import torch.multiprocessing\n\n processes = []\n torch.multiprocessing.set_start_method(\"spawn\")\n for rank in range(size):\n p = torch.multiprocessing.Process(target=_local_init_process, args=(rank, size, fn, backend))\n p.start()\n processes.append(p)\n\n for p in processes:\n p.join()\n\n\ndef run():\n print(\n \"Hello from process {} on node {} out of {}\"\n \"\".format(torch.distributed.get_rank(), socket.gethostname(), torch.distributed.get_world_size())\n )\n\ndef main():\n if \"SLURM_JOB_ID\" in os.environ:\n init_slurm(run)\n else:\n init_local(torch.cuda.device_count(), run)\n\nif __name__ == '__main__':\n main()\n"
] |
[
[
"torch.multiprocessing.set_start_method",
"torch.distributed.init_process_group",
"torch.cuda.device_count",
"torch.distributed.get_rank",
"torch.distributed.get_world_size",
"torch.multiprocessing.Process"
]
] |
La-fe/mmdetection
|
[
"4fbdc662a05349fc8813825b5b0011c91d184090"
] |
[
"my_util/data2coco_offical.py"
] |
[
"import os\nimport json\nimport numpy as np\nimport shutil\nimport pandas as pd\n\ndefect_name2label = {\n '破洞': 1, '水渍': 2, '油渍': 2, '污渍': 2, '三丝': 3, '结头': 4, '花板跳': 5, '百脚': 6, '毛粒': 7,\n '粗经': 8, '松经': 9, '断经': 10, '吊经': 11, '粗维': 12, '纬缩': 13, '浆斑': 14, '整经结': 15, '星跳': 16, '跳花': 16,\n '断氨纶': 17, '稀密档': 18, '浪纹档': 18, '色差档': 18, '磨痕': 19, '轧痕': 19, '修痕': 19, '烧毛痕': 19, '死皱': 20, '云织': 20,\n '双纬': 20, '双经': 20, '跳纱': 20, '筘路': 20, '纬纱不良': 20,\n}\n\nclass Fabric2COCO:\n\n def __init__(self,mode=\"train\"):\n self.images = []\n self.annotations = []\n self.categories = []\n self.img_id = 0\n self.ann_id = 0\n self.mode =mode\n if not os.path.exists(\"coco/images/{}\".format(self.mode)):\n os.makedirs(\"coco/images/{}\".format(self.mode))\n\n def to_coco(self, anno_file,img_dir):\n self._init_categories()\n for i in range(len(anno_file)):\n anno_f = anno_file[i]\n anno_result= pd.read_json(open(anno_f,\"r\"))\n name_list=anno_result[\"name\"].unique()\n for img_name in name_list:\n img_anno = anno_result[anno_result[\"name\"] == img_name]\n bboxs = img_anno[\"bbox\"].tolist()\n defect_names = img_anno[\"defect_name\"].tolist()\n assert img_anno[\"name\"].unique()[0] == img_name\n\n img_path=os.path.join(img_dir,img_name)\n # img =cv2.imread(img_path)\n # h,w,c=img.shape\n h,w=1000,2446\n self.images.append(self._image(img_path,h, w))\n\n # self._cp_img(img_path)\n\n for bbox, defect_name in zip(bboxs, defect_names):\n label= defect_name2label[defect_name]\n annotation = self._annotation(label, bbox)\n self.annotations.append(annotation)\n self.ann_id += 1\n self.img_id += 1\n\n train_num = int(self.img_id/5*4)\n print(\"There are %d train data\"%train_num)\n print(\"There are %d val data\"% (self.img_id - train_num))\n train_instance = {}\n train_instance['info'] = 'fabric defect'\n train_instance['license'] = ['none']\n train_instance['images'] = self.images[:train_num]\n train_instance['annotations'] = self.annotations[:train_num]\n train_instance['categories'] = self.categories[:train_num]\n\n val_instance = {}\n val_instance['info'] = 'fabric defect'\n val_instance['license'] = ['none']\n val_instance['images'] = self.images[train_num:]\n val_instance['annotations'] = self.annotations[train_num:]\n val_instance['categories'] = self.categories[train_num:]\n\n return train_instance,val_instance\n\n def _init_categories(self):\n for v in range(1, 21):\n print(v)\n category = {}\n category['id'] = v\n category['name'] = str(v)\n category['supercategory'] = 'defect_name'\n self.categories.append(category)\n # for k, v in defect_name2label.items():\n # category = {}\n # category['id'] = v\n # category['name'] = k\n # category['supercategory'] = 'defect_name'\n # self.categories.append(category)\n\n def _image(self, path, h, w):\n image = {}\n image['height'] = h\n image['width'] = w\n image['id'] = self.img_id\n image['file_name'] = os.path.basename(path)\n return image\n\n def _annotation(self, label, bbox):\n area = (bbox[2] - bbox[0]) * (bbox[3] - bbox[1])\n points = [[bbox[0], bbox[1]], [bbox[2], bbox[1]], [bbox[2], bbox[3]], [bbox[0], bbox[3]]]\n annotation = {}\n annotation['id'] = self.ann_id\n annotation['image_id'] = self.img_id\n annotation['category_id'] = label\n annotation['segmentation'] = [np.asarray(points).flatten().tolist()]\n annotation['bbox'] = self._get_box(points)\n annotation['iscrowd'] = 0\n annotation['area'] = area\n return annotation\n\n def _cp_img(self, img_path):\n shutil.copy(img_path, os.path.join(\"coco/images/{}\".format(self.mode), os.path.basename(img_path)))\n\n def _get_box(self, points):\n min_x = min_y = np.inf\n max_x = max_y = 0\n for x, y in points:\n min_x = min(min_x, x)\n min_y = min(min_y, y)\n max_x = max(max_x, x)\n max_y = max(max_y, y)\n '''coco,[x,y,w,h]'''\n return [min_x, min_y, max_x - min_x, max_y - min_y]\n\n def save_coco_json(self, instance, save_path):\n import json\n with open(save_path, 'w') as fp:\n json.dump(instance, fp, indent=1, separators=(',', ': '))\n\n'''转换有瑕疵的样本为coco格式'''\nimg_dir = \"/home/remo/Desktop/cloth_flaw_detection/guangdong1_round1_train2_20190828/defect_Images\"\nanno_dir=[\n # \"/home/remo/Desktop/cloth_flaw_detection/guangdong1_round1_train1_20190818/Annotations/anno_train.json\",\n # '/home/remo/Desktop/cloth_flaw_detection/guangdong1_round1_train2_20190828/Annotations/anno_train.json',\n # '/home/remo/Desktop/cloth_flaw_detection/Dataset/COCO_format/Aug_json.json',\n '/home/remo/Desktop/cloth_flaw_detection/Dataset/COCO_format/Aug_invert_json.json'\n ]\nsave_dir = \"/home/remo/Desktop/cloth_flaw_detection/Dataset/COCO_format/\"\nfabric2coco = Fabric2COCO()\ntrain_instance,val_instance = fabric2coco.to_coco(anno_dir,img_dir)\n# if not os.path.exists(\"coco/annotations/\"):\n# os.makedirs(\"coco/annotations/\")\nfabric2coco.save_coco_json(train_instance, save_dir+'instances_invert_{}.json'.format(\"train\"))\nfabric2coco.save_coco_json(val_instance, save_dir+'instances_invert_{}.json'.format(\"val\"))"
] |
[
[
"numpy.asarray"
]
] |
erjihaoshi/audio
|
[
"b5dd693a396d18b8388548dc0caa94af23975dd3"
] |
[
"test/test_kaldi_io.py"
] |
[
"import os\nimport torch\nimport torchaudio.kaldi_io as kio\nimport unittest\nimport test.common_utils\n\n\nclass Test_KaldiIO(unittest.TestCase):\n data1 = [[1, 2, 3], [11, 12, 13], [21, 22, 23]]\n data2 = [[31, 32, 33], [41, 42, 43], [51, 52, 53]]\n test_dirpath, test_dir = test.common_utils.create_temp_assets_dir()\n\n def _test_helper(self, file_name, expected_data, fn, expected_dtype):\n \"\"\" Takes a file_name to the input data and a function fn to extract the\n data. It compares the extracted data to the expected_data. The expected_dtype\n will be used to check that the extracted data is of the right type.\n \"\"\"\n test_filepath = os.path.join(self.test_dirpath, \"assets\", file_name)\n expected_output = {'key' + str(idx + 1): torch.tensor(val, dtype=expected_dtype)\n for idx, val in enumerate(expected_data)}\n\n for key, vec in fn(test_filepath):\n self.assertTrue(key in expected_output)\n self.assertTrue(isinstance(vec, torch.Tensor))\n self.assertEqual(vec.dtype, expected_dtype)\n self.assertTrue(torch.all(torch.eq(vec, expected_output[key])))\n\n def test_read_vec_int_ark(self):\n self._test_helper(\"vec_int.ark\", self.data1, kio.read_vec_int_ark, torch.int32)\n\n def test_read_vec_flt_ark(self):\n self._test_helper(\"vec_flt.ark\", self.data1, kio.read_vec_flt_ark, torch.float32)\n\n def test_read_mat_ark(self):\n self._test_helper(\"mat.ark\", [self.data1, self.data2], kio.read_mat_ark, torch.float32)\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"torch.eq",
"torch.tensor"
]
] |
YaNgZhAnG-V5/RoarTorch
|
[
"c994e16f956f1a76edda9bb1cca5998cb06f1ce3"
] |
[
"src/attribution_methods/constant_class_mask_margin.py"
] |
[
"import numpy as np\nimport torch\nfrom skimage.draw import circle\nfrom skimage import filters\n\n\ndef compute_constant_class_mask_margin(model, preprocessed_image, label, baseline=0.1, size=0.2):\n # Baselines is the margin between circle center and edge\n # margin insert mask to keep a margin to the edge of the image\n assert preprocessed_image.shape[-2] == preprocessed_image.shape[-1], \"the image has different length and height\"\n\n # get num of classes\n num_of_classes = model(preprocessed_image).shape[1]\n\n # get label\n label_idx = label.item()\n\n # get image length\n grad = torch.zeros_like(preprocessed_image).detach().cpu().clone().numpy().squeeze()\n image_length = list(grad.shape)[-1]\n\n # construct circle based on label\n class_per_edge = torch.ceil(torch.tensor([num_of_classes/4.], dtype=torch.float64)).item()\n margin = int(image_length * baseline)\n stride = int((image_length - 2 * margin)/class_per_edge)\n edge_index = label_idx//class_per_edge\n position_index = label_idx % class_per_edge\n if edge_index == 0:\n center_x = margin\n center_y = margin\n center_x = center_x + stride * position_index\n elif edge_index == 1:\n center_x = image_length - margin\n center_y = margin\n center_y = center_y + stride * position_index\n elif edge_index == 2:\n center_x = image_length - margin\n center_y = image_length - margin\n center_x = center_x - stride * position_index\n elif edge_index == 3:\n center_x = margin\n center_y = image_length - margin\n center_y = center_y - stride * position_index\n rr, cc = circle(center_x, center_y, int(image_length * size), shape=(grad.shape[1], grad.shape[2]))\n grad[:, rr, cc] = 1\n\n # blur the mask\n grad = filters.gaussian(grad)\n return grad\n"
] |
[
[
"torch.zeros_like",
"torch.tensor"
]
] |
DigZator/gym-minigrid
|
[
"d0fe2577ea9687141599907c2ed4956c62fa85e0"
] |
[
"senor_sarsa_graphs.py"
] |
[
"#!/usr/bin/env python3\n\nimport time\nimport argparse\nimport numpy as np\nimport gym\nimport gym_minigrid\nfrom gym_minigrid.wrappers import *\nfrom gym_minigrid.window import Window\nfrom gym_minigrid.register import env_list\nimport matplotlib\n#matplotlib.use('TkAgg')\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"--env\",\n help=\"gym environment to load\",\n default='MiniGrid-FourRooms-v0'#MiniGrid-Empty-16x16-v0,MiniGrid-FourRooms-v0\n)\nparser.add_argument(\n \"--seed\",\n type=int,\n help=\"random seed to generate the environment with\",\n default=-1\n)\nparser.add_argument(\n \"--tile_size\",\n type=int,\n help=\"size at which to render tiles\",\n default=32\n)\nparser.add_argument(\n '--agent_view',\n default=False,\n help=\"draw the agent sees (partially observable view)\",\n action='store_true'\n)\n \nargs = parser.parse_args()\n\nenv = gym.make(args.env)\nobs = env.reset()\n\ndef step(action):\n obs, reward, done, info = env.step(action)\n return obs, reward, done, info\n\n#Number of Actions selector\n#nA = 7\nnA = 3\n\nenv.reset()\n\ndef senor_sarsa(α = 0.35,lmbd = 0.9,gamma = 0.9,n_attempts = 1000,n_steps = 1000,lim = True):\n\n #Initialize Q(s,a) arbitrarily, for all s in S, a in A(s)\n Q = {(env.agent_pos[0],env.agent_pos[1]) : {dirc : {a : 0 for a in range(nA)} for dirc in range(4)}}\n #Q[(1,2)] = {dirc : {a : 0 for a in range(7)} for dirc in range(4)} - How to add key to a dictionary\n #Q: Loc: Dir: A: (Q)\n \n #left = 0\n #right = 1\n #forward = 2\n #pickup = 3\n #drop = 4\n #toggle = 5\n #done = 6\n \n #Initialized policy\n Pol = {(env.agent_pos[0],env.agent_pos[1]): {dirc : 0 for dirc in range(4)}}\n\n #Repeat (for each episode)\n attempts = 0 #Episode counter\n sbe = []\n end = False\n while (not end):\n #E(s,a) = 0, for all s in S, a in A(s)\n E = {(env.agent_pos[0],env.agent_pos[1]) : {dirc : {a : 0 for a in range(nA)} for dirc in range(4)}}\n for adloc in Q:\n E[adloc] = {dirc : {a : 0 for a in range(nA)} for dirc in range(4)}\n\n #Initialze S,A\n loc = (env.agent_pos[0],env.agent_pos[1])\n dire = env.agent_dir\n A = 0\n\n steps = 1 #Step counter\n done = False #Terminal\n\n while((not done) and (steps < n_steps)):\n #if ((attempts == 1) or (attempts == 10) or (attempts == 50) or (attempts == 500)):\n # env.render()\n #Action Picker acc to ε-greedy\n A = np.random.randint(0,nA)\n ε = 100/((attempts)+100)\n #print(Pol, loc, dire)\n if Pol.get(loc) is None:\n Pol[loc] = {dirc : 0 for dirc in range(4)}\n A = Pol[loc][dire] if (np.random.random_sample() > (ε)) else A\n\n #Observe R, S'\n Obs,R,done,info = step(A)\n nloc = (env.agent_pos[0], env.agent_pos[1])\n ndire = env.agent_dir\n\n #Add state if it doesn't exist\n if Q.get(loc) is None:\n Q[loc] = {dirc : {a : 0 for a in range(nA)} for dirc in range(4)}\n if Q.get(nloc) is None:\n Q[nloc] = {dirc : {a : 0 for a in range(nA)} for dirc in range(4)}\n if E.get(nloc) is None:\n E[nloc] = {dirc : {a : 0 for a in range(nA)} for dirc in range(4)}\n if Pol.get(nloc) is None:\n Pol[nloc] = {dirc : 0 for dirc in range(4)}\n \n #Target\n targe = R + (gamma*Q[nloc][ndire][Pol[nloc][ndire]]) - Q[loc][dire][A]\n\n #Spike Eligibility\n E[loc][dire][A] = E[loc][dire][A] + 1\n\n #Update Q with backward view, Reduce the Eligibility Traces, Get the new Policy\n for sloc in Q: #Sweep_loc\n for sdire in Q[sloc]: #Sweep_direction\n mA = Pol[sloc][sdire] #Max_Action\n for sA in Q[sloc][sdire]: #Sweep_Action\n Q[sloc][sdire][sA] = Q[sloc][sdire][sA] + (α*targe*E[sloc][sdire][sA])\n E[sloc][sdire][sA] = gamma*lmbd*E[sloc][sdire][sA]\n mA = sA if (Q[sloc][sdire][sA] > Q[sloc][sdire][mA]) else mA\n Pol[sloc][sdire] = mA\n #S ← S'; A ← A'\n loc = nloc\n dire = ndire\n #Step Increment\n steps = steps + 1\n #Step End\n\n attempts = attempts + 1\n end = True if (attempts > n_attempts) else False #Loop Terminator/Number of Episodes dial\n n_steps = steps if (lim == True) else n_steps\n print(attempts,steps)\n env.reset()\n sbe.append(steps)\n #Attempt End\n return sbe\n #Senor_sarsa end\n\n#sbe = senor_sarsa(0.35,0.9,0.9,1000,1000,True)\n#episodes = list(range(1,len(sbe)+1))\n#matplotlib.pyplot.plot(episodes, sbe, label = \"Limiting Steps\")\n#\n#sbe = senor_sarsa(0.35,0.9,0.9,1000,1000,False)\n#episodes = list(range(1,len(sbe)+1))\n#matplotlib.pyplot.plot(episodes, sbe, label = \"Not Limiting Steps\")\n\n#for α in range(0.05,1,0.05):\n# sbe = senor_sarsa(α,0.9,0.9,1000,1000,True)\n# episodes = list(range(1,len(sbe)+1))\n# matplotlib.pyplot.plot(episodes, sbe, label = \"α = {}\".format(i))\n\nα = 0.1\nwhile (α<1):\n sbe = senor_sarsa(α,0.9,0.9,1000,1000,True)\n episodes = list(range(1,len(sbe)+1))\n matplotlib.pyplot.plot(episodes, sbe, label = \"α = {}\".format(α))\n α = α + 0.1\n\nmatplotlib.pyplot.xlabel(\"Episodes\")\nmatplotlib.pyplot.ylabel(\"Number of steps in Episode\")\nmatplotlib.pyplot.legend()\nmatplotlib.pyplot.show()"
] |
[
[
"matplotlib.pyplot.legend",
"numpy.random.random_sample",
"matplotlib.pyplot.ylabel",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"numpy.random.randint"
]
] |
complexly/py-ecomplexity
|
[
"772fbae9eaa4f995be725d05eed9a6fa6a7c7156"
] |
[
"ecomplexity/ecomplexity.py"
] |
[
"import numpy as np\nimport pandas as pd\nfrom ecomplexity.calc_proximity import calc_discrete_proximity\nfrom ecomplexity.calc_proximity import calc_continuous_proximity\nfrom ecomplexity.ComplexityData import ComplexityData\nfrom ecomplexity.density import calc_density\nfrom ecomplexity.coicog import calc_coi_cog\n\ndef reshape_output_to_data(cdata, t):\n \"\"\"Reshape output ndarrays to df\"\"\"\n diversity = cdata.diversity_t[:, np.newaxis].repeat(\n cdata.mcp_t.shape[1], axis=1).ravel()\n ubiquity = cdata.ubiquity_t[np.newaxis, :].repeat(\n cdata.mcp_t.shape[0], axis=0).ravel()\n eci = cdata.eci_t[:, np.newaxis].repeat(\n cdata.mcp_t.shape[1], axis=1).ravel()\n pci = cdata.pci_t[np.newaxis, :].repeat(\n cdata.mcp_t.shape[0], axis=0).ravel()\n coi = cdata.coi_t[:, np.newaxis].repeat(\n cdata.mcp_t.shape[1], axis=1).ravel()\n\n out_dict = {'diversity': diversity,\n 'ubiquity': ubiquity,\n 'mcp': cdata.mcp_t.ravel(),\n 'eci': eci,\n 'pci': pci,\n 'density': cdata.density_t.ravel(),\n 'coi': coi,\n 'cog': cdata.cog_t.ravel()}\n\n if hasattr(cdata, 'rpop_t'):\n out_dict['rca'] = cdata.rca_t.ravel()\n out_dict['rpop'] = cdata.rpop_t.ravel()\n\n elif hasattr(cdata, 'rca_t'):\n out_dict['rca'] = cdata.rca_t.ravel()\n\n output = pd.DataFrame.from_dict(out_dict).reset_index(drop=True)\n\n cdata.data_t['time'] = t\n cdata.output_t = pd.concat([cdata.data_t.reset_index(), output], axis=1)\n cdata.output_list.append(cdata.output_t)\n return(cdata)\n\n\ndef conform_to_original_data(cdata, cols_input, data):\n \"\"\"Reset column names and add dropped columns back\"\"\"\n cdata.output = cdata.output.rename(columns=cols_input)\n cdata.output = cdata.output.merge(\n data, how=\"outer\", on=list(cols_input.values()))\n return(cdata)\n\ndef calc_eci_pci(cdata):\n # Calculate ECI and PCI eigenvectors\n mcp1 = (cdata.mcp_t / cdata.diversity_t[:, np.newaxis])\n mcp2 = (cdata.mcp_t / cdata.ubiquity_t[np.newaxis, :])\n # These matrix multiplication lines are very slow\n Mcc = mcp1 @ mcp2.T\n Mpp = mcp2.T @ mcp1\n\n # Calculate eigenvectors\n eigvals, eigvecs = np.linalg.eig(Mpp)\n eigvecs = np.real(eigvecs)\n # Get eigenvector corresponding to second largest eigenvalue\n eig_index = eigvals.argsort()[-2]\n kp = eigvecs[:, eig_index]\n kc = mcp1 @ kp\n\n # Adjust sign of ECI and PCI so it makes sense, as per book\n s1 = np.sign(np.corrcoef(cdata.diversity_t, kc)[0, 1])\n eci_t = s1 * kc\n pci_t = s1 * kp\n\n return(eci_t, pci_t)\n\n\ndef ecomplexity(data, cols_input, presence_test=\"rca\", val_errors_flag='coerce',\n rca_mcp_threshold=1, rpop_mcp_threshold=1, pop=None,\n continuous=False, asymmetric=False):\n \"\"\"Complexity calculations through the ComplexityData class\n\n Args:\n data: pandas dataframe containing production / trade data.\n Including variables indicating time, location, product and value\n cols_input: dict of column names for time, location, product and value.\n Example: {'time':'year', 'loc':'origin', 'prod':'hs92', 'val':'export_val'}\n presence_test: str for test used for presence of industry in location.\n One of \"rca\" (default), \"rpop\", \"both\", or \"manual\".\n Determines which values are used for M_cp calculations.\n If \"manual\", M_cp is taken as given from the \"value\" column in data\n val_errors_flag: {'coerce','ignore','raise'}. Passed to pd.to_numeric\n *default* coerce.\n rca_mcp_threshold: numeric indicating RCA threshold beyond which mcp is 1.\n *default* 1.\n rpop_mcp_threshold: numeric indicating RPOP threshold beyond which mcp is 1.\n *default* 1. Only used if presence_test is not \"rca\".\n pop: pandas df, with time, location and corresponding population, in that order.\n Not required if presence_test is \"rca\" (default).\n continuous: Used to calculate product proximities, indicates whether\n to consider correlation of every product pair (True) or product\n co-occurrence (False). *default* False.\n asymmetric: Used to calculate product proximities, indicates whether\n to generate asymmetric proximity matrix (True) or symmetric (False).\n *default* False.\n\n Returns:\n Pandas dataframe containing the data with the following additional columns:\n - diversity: k_c,0\n - ubiquity: k_p,0\n - rca: Balassa's RCA\n - rpop: (available if presence_test!=\"rca\") RPOP\n - mcp: MCP used for complexity calculations\n - eci: Economic complexity index\n - pci: Product complexity index\n - density: Density of the network around each product\n - coi: Complexity Outlook Index\n - cog: Complexity Outlook Gain\n\n \"\"\"\n cdata = ComplexityData(data, cols_input, val_errors_flag)\n\n cdata.output_list = []\n\n # Iterate over time stamps\n for t in cdata.data.index.unique(\"time\"):\n print(t)\n # Rectangularize df\n cdata.create_full_df(t)\n\n # Check if Mcp is pre-computed\n if presence_test != \"manual\":\n cdata.calculate_rca()\n cdata.calculate_mcp(rca_mcp_threshold, rpop_mcp_threshold,\n presence_test, pop, t)\n else:\n cdata.calculate_manual_mcp()\n\n # Calculate diversity and ubiquity\n cdata.diversity_t = np.nansum(cdata.mcp_t, axis=1)\n cdata.ubiquity_t = np.nansum(cdata.mcp_t, axis=0)\n\n # Calculate ECI and PCI\n cdata.eci_t, cdata.pci_t = calc_eci_pci(cdata)\n\n # Calculate proximity and density\n if continuous == False:\n prox_mat = calc_discrete_proximity(cdata.mcp_t, cdata.ubiquity_t,\n asymmetric)\n cdata.density_t = calc_density(cdata.mcp_t, prox_mat)\n elif continuous == True and presence_test == \"rpop\":\n prox_mat = calc_continuous_proximity(cdata.rpop_t, cdata.ubiquity_t)\n cdata.density_t = calc_density(cdata.rpop_t, prox_mat)\n elif continuous == True and presence_test != \"rpop\":\n prox_mat = calc_continuous_proximity(cdata.rca_t, cdata.ubiquity_t)\n cdata.density_t = calc_density(cdata.rca_t, prox_mat)\n\n # Calculate COI and COG\n cdata.coi_t, cdata.cog_t = calc_coi_cog(cdata, prox_mat)\n\n # Normalize variables as per STATA package\n cdata.pci_t = (cdata.pci_t - cdata.eci_t.mean()) / cdata.eci_t.std()\n cdata.cog_t = cdata.cog_t / cdata.eci_t.std()\n cdata.eci_t = (cdata.eci_t - cdata.eci_t.mean()) / cdata.eci_t.std()\n \n cdata.coi_t = (cdata.coi_t - cdata.coi_t.mean()) / cdata.coi_t.std()\n\n # Reshape ndarrays to df\n cdata = reshape_output_to_data(cdata, t)\n\n cdata.output = pd.concat(cdata.output_list)\n cdata = conform_to_original_data(cdata, cols_input, data)\n\n return(cdata.output)\n"
] |
[
[
"pandas.concat",
"numpy.linalg.eig",
"numpy.real",
"numpy.nansum",
"pandas.DataFrame.from_dict",
"numpy.corrcoef"
]
] |
alandegenhart/neuropy
|
[
"a9f7b735da78a5296f648cb3bb94c1c31843c668"
] |
[
"neuropy/mathutil.py"
] |
[
"\"\"\"AIBS math module\n\nThis module contains assorted math functions.\n\n\"\"\"\n# Import\nimport numpy as np\n\n\ndef ismember_rows(a, b):\n \"\"\"Return rows of one matrix present in another.\n \n This function finds the rows of a that are equal to b. This function\n requires one of the two input arrays to have a single row.\n \"\"\"\n \n # Make sure both a and b are two-dimensional. Also check to make sure one\n # of the two arrays has only one row.\n assert(a.ndim == 2 & b.ndim == 2)\n assert(a.shape[0] == 1 or b.shape[0] == 1)\n \n # Check to determine which mode the function is operating. If a is a single\n # row, then the output will be a single boolean indicating if a is a row in\n # b. If b is a row, then the function should return a boolean indicating\n # which rows (if any) in a are equal to b.\n if a.shape[0] == 1:\n mode = 'any'\n else:\n mode = 'all'\n \n # Find matrix of boolean values. Note this uses broadcasting.\n c = np.all(a == b, axis=1)\n \n # If the first argument is a single row, check to see if any of the element\n # s in c are True. If so, a is a row in b.\n if mode == 'any':\n c = np.any(c)\n \n return c\n\n\ndef logdet(A):\n \"\"\"Computes log(det(A)) where A is positive-definite\n\n This is faster and more stable than computing log(det(A)) directly.\n\n Adapted from logdet.m by Tom Minka\n \"\"\"\n from scipy.linalg import cholesky\n\n U = cholesky(A)\n y = 2 * np.sum(np.log(np.diag(U)))\n return y\n\n\ndef fisher_lda(X, classes):\n \"\"\"Fisher linear discriminant analysis.\n\n Inputs:\n :X -- Design matrix of activity (dim x observations)\n :cond_code -- Condition code for each column in X\n\n Outputs:\n :D -- Projection vectors\n :J -- Discriminant\n \"\"\"\n\n # Import\n from scipy import linalg\n\n # Transpose input data to row-vector form (rows are now observations)\n X = X.T\n n_dims = X.shape[1]\n unique_classes = set(classes)\n n_classes = len(unique_classes)\n\n # Initialize within-class scatter\n SS_within = np.zeros([n_dims, n_dims])\n\n # Iterate over classes\n class_means = np.zeros((n_classes, n_dims))\n for idx, u_cls in enumerate(unique_classes):\n # Get observations for current label\n label_mask = [True if u_cls == cls else False for cls in classes]\n X_class = X[label_mask, :]\n\n # Calculate mean and covariance\n class_means[idx, :] = X_class.mean(axis=0, keepdims=True)\n SS_within = SS_within + np.cov(X_class.T)\n\n # Calculate between-class scatter and eigenvalues/vectors\n SS_between = np.cov(class_means.T)\n eig_vals, eig_vecs = linalg.eig(SS_between, SS_within)\n eig_vals = np.real(eig_vals)\n\n # Get diagonal of eigenvalue matrix and sort\n sort_idx = np.argsort(eig_vals) # should be ascending order\n sort_idx = np.flip(sort_idx) # Now in descending order\n eig_vecs = eig_vecs[:, sort_idx] # Sorted eigenvectors\n\n # Truncate eigenvectors to number of classes - 1 and calculate discriminant\n n_return_dims = n_classes - 1\n D = eig_vecs[:, 0:n_return_dims]\n eig_within, _ = np.linalg.eig(SS_within)\n eig_between, _ = np.linalg.eig(SS_between)\n J = np.sum(eig_between)/np.sum(eig_within)\n\n # TODO: would be good to verify that the discriminant is being calculated\n # correctly -- the way to do this might be to generate data with\n # different covariance values but the same means and show that the\n # discriminant value changes accordingly.\n\n return D, J\n"
] |
[
[
"numpy.diag",
"numpy.linalg.eig",
"numpy.all",
"numpy.real",
"numpy.cov",
"scipy.linalg.cholesky",
"numpy.any",
"numpy.argsort",
"numpy.flip",
"numpy.zeros",
"numpy.sum",
"scipy.linalg.eig"
]
] |
liuyngchng/Tetris-Python
|
[
"24027e261e24c7c54fe07b46984a2025cf174b5a"
] |
[
"player.py"
] |
[
"\"\"\"\nThis controls games key and aims to get a high score\n\"\"\"\nfrom copy import copy, deepcopy\nfrom numpy import array, mean\nfrom random import choice\nfrom functions import Status\nfrom squares import Squares\n\n\nclass AI:\n def __init__(self):\n self.direction = None\n\n def control(self, sqs_given: Squares, status: Status):\n if sqs_given.curr_sq == sqs_given.st.new:\n self.direction = make_choice(sqs_given)\n # print(self.direction, type(self.direction))\n # self.direction = {'all_pos': [[17, 0], [16, 0], [15, 0], [18, 0]], 'center': [17, 0],\n # 'rotate': 1, 'mark': 22.4875}\n # type(self.direction) = <class 'dict'>\n else:\n move(sqs_given, self.direction, status)\n\n\n\"\"\"\ndirection = {'all_pos': [[17, 0], [16, 0], [15, 0], [18, 0]], 'center': [17, 0], 'rotate': 1, 'mark': 22.4875}\n\"\"\"\n\n\ndef move(sqs_given: Squares, direction, status: Status):\n # rotation\n if sqs_given.rotate_curr != direction['rotate']:\n status.rotate = True\n else:\n status.rotate = False\n # horizontal left\n if sqs_given.curr_sq[1] > direction['center'][1]:\n status.left = True\n # horizontal right\n elif sqs_given.curr_sq[1] < direction['center'][1]:\n status.right = True\n # horizontal stop\n else:\n status.left = False\n status.right = False\n # vertical drop\n if sqs_given.curr_sq[0] != direction['center'][0]:\n status.down = True\n else:\n status.down = False\n\n\ndef make_choice(sqs_given: Squares) -> dict:\n \"\"\"return one direction to go\"\"\"\n sqs = copy_sqs(sqs_given)\n pos_data = get_all_possible_pos(sqs)\n # print('make_choice_pos_data:', pos_data)\n evaluate_full_situation(sqs, pos_data)\n all_highest = get_all_highest(pos_data)\n return choice(all_highest)\n\n\ndef get_all_highest(pos_data) -> list:\n \"\"\"highest marks might not be distinct, so return all of them\"\"\"\n # find highest mark\n highest_key = lambda dict: dict['mark']\n max_data = max(pos_data, key=highest_key)\n max_mark = max_data['mark']\n # get all data with this mark\n all_highest = []\n for data in pos_data:\n if data['mark'] == max_mark:\n all_highest.append(data)\n return all_highest\n\n\ndef get_all_possible_pos(sqs_given: Squares):\n # copy given sqs for safety\n sqs_origin = copy_sqs(sqs_given)\n # reset rotation\n sqs_origin.curr_shape = sqs_origin.origin_shape\n sqs_origin.rotate_curr = 1\n # generate pos\n pos = []\n for rotate in range(sqs_origin.rotate_limit):\n sqs = copy_sqs(sqs_origin)\n sqs_origin.rotate(sqs_origin)\n get_end_pos_with_rotate(pos, sqs)\n return pos\n\n\ndef get_end_pos_with_rotate(pos, sqs):\n move_sq_to_left(sqs)\n old_sq = None\n # move to right and record each position with drop to the end\n while old_sq != sqs.curr_sq:\n sqs_curr = copy_sqs(sqs)\n sqs_curr.drop_straight(sqs_curr)\n record_curr_pos(pos, sqs_curr)\n old_sq = sqs.curr_sq\n sqs.right(sqs)\n\n\ndef copy_sqs(sqs: Squares):\n \"\"\"this copies sqs safely\"\"\"\n sqs_copy = copy(sqs)\n sqs_copy.squares = deepcopy(sqs.squares)\n sqs_copy.curr_sq = deepcopy(sqs.curr_sq)\n sqs_copy.curr_shape = deepcopy(sqs.curr_shape)\n return sqs_copy\n\n\ndef move_sq_to_left(sqs):\n old_sq = None\n while old_sq != sqs.curr_sq:\n old_sq = sqs.curr_sq\n sqs.left(sqs)\n\n\ndef record_curr_pos(pos, sqs):\n \"\"\"record all active squares\"\"\"\n all_pos = []\n y = sqs.curr_sq[0]\n x = sqs.curr_sq[1]\n all_pos.append([y, x])\n for sq in sqs.curr_shape:\n all_pos.append([y + sq[0], x + sq[1]])\n pos.append({'all_pos': all_pos, 'center': sqs.curr_sq, 'rotate': sqs.rotate_curr})\n\n\ndef evaluate_full_situation(sqs, positions):\n for pos_data in positions:\n pos = pos_data['all_pos']\n sqs_curr = copy_sqs(sqs)\n map_pos_to_sqs(sqs_curr, pos)\n pos_data['mark'] = evaluate_situation(sqs_curr)\n\n\ndef evaluate_situation(sqs):\n full_lines = evaluate_full_lines(sqs)\n sqs.clean_full_lines(sqs)\n squares = array(sqs.squares).T # convert rows to colomns\n hidden_squares = evaluate_hidden_squares(squares)\n lowest_column, average_column, absolute_diff = evaluate_column(squares)\n return evaluate_mark(full_lines, hidden_squares, lowest_column, average_column, absolute_diff)\n\n\ndef evaluate_full_lines(sqs_given):\n sqs = copy_sqs(sqs_given)\n full_lines = 0\n for line in sqs.squares:\n if line.count('none') == 0:\n full_lines += 1\n return full_lines\n\n\ndef evaluate_hidden_squares(squares):\n \"\"\"find the number of non-squares under squares\"\"\"\n hidden_squares = 0\n for colomn in squares:\n found_first_sq = False\n for sq in colomn:\n # find first square\n if not found_first_sq:\n if sq != 'none':\n found_first_sq = True\n else:\n continue\n # find hidden squares\n if sq == 'none':\n hidden_squares += 1\n return hidden_squares\n\n\ndef evaluate_column(squares):\n \"\"\"count lowest and average space left in every column\"\"\"\n space_left = []\n for column in squares:\n appended = False\n for index, sq in enumerate(column):\n # check every square\n if sq != 'none':\n space_left.append(index)\n appended = True\n break\n if not appended:\n space_left.append(len(column))\n return min(space_left), mean(space_left), max(space_left) - min(space_left)\n\n\ndef evaluate_mark(full_lines, hidden_squares, lowest_column, average_column, absolute_diff):\n # weights, set manually\n full_line_weight = 20\n hidden_squares_weight = -2\n lowest_column_weight = 0.3\n average_column_weight = 0.15\n absolute_diff_weight = -1\n mark = 0\n mark += full_lines * full_line_weight\n mark += hidden_squares * hidden_squares_weight\n mark += lowest_column * lowest_column_weight\n mark += average_column * average_column_weight\n mark += absolute_diff * absolute_diff_weight\n return mark\n\n\ndef map_pos_to_sqs(sqs: Squares, positions: list):\n # <squares.Squares object>, [[16, 6], [15, 6], [16, 5], [15, 7]]\n for pos in positions:\n \"\"\"\n 将二维矩阵中的某个元素的值设置为'map'\n [['none','map',... 'yellow', 'yellow'],...]\n \"\"\"\n sqs.squares[pos[0]][pos[1]] = 'map'\n"
] |
[
[
"numpy.array",
"numpy.mean"
]
] |
Kushal-S-Bastakoti/Password_Generator
|
[
"73f92889d8b70ec0ada0ac1e9f5cffddbe368466"
] |
[
"pwd_generator.py"
] |
[
"#Simple Password Generator created by Kushal Sharma Bastakoti\n#Contact me on instagram at kushal.bastakoti\n\n#You can customize the weight,ratio and number of digits by just editing some values below \n\n#To use custom value run as python pwd_generator.py number1\n#number1 is the number of digits you want\n\n#to customize ratio of strings letters and digits\n#run python pwd_generator.py num1 num2 num3 num4\n#num1 is digits \n#num2 is weight of strings\n#num3 is weight of numbers\n#num3 is weight of symbols\n\nimport numpy as np\nimport random as rm\nimport sys\n\n\n#List for base_digits\nword_list = np.array(['a', 'A', 'b', 'B', 'c', 'C', 'd', 'D', 'e', 'E', 'f', 'F','g', 'G', 'h', 'H', 'i', 'I', 'j', 'J', 'k', 'K', 'l', 'L','m', 'M', 'n', 'N', 'o', 'O', 'p', 'P', 'q', 'Q', 'r', 'R','s', 'S', 't', 't', 'T', 'u', 'U', 'v', 'V', 'w', 'W', 'x', 'X', 'y', 'Y', 'z', 'Z', ])\n \nnumber_list = np.array(['1', '2', '3' , '4', '5', '6', '7','8', '9'])\n\nsymbol_list = np.array(['!','@','#','$','%','^','&','*'])\n\n\n#for 16 digits take 60% digits string, take 25% numbers and 15 % symbols; \n#Defalut Values\nif len(sys.argv) == 1:\n word_count = 16\n weight_string = 60\n weight_number = 25\n weight_symbols = 15\n\nelif len(sys.argv) == 2 :\n word_count = int(sys.argv[1])\n weight_string = 60\n weight_number = 25\n weight_symbols = 15\nelif len(sys.argv) == 5:\n word_count = int(sys.argv[1])\n weight_string = int(sys.argv[2])\n weight_number = int(sys.argv[3])\n weight_symbols = int(sys.argv[4])\nelse:\n print(\"Invalid number of Arguments\")\n exit(0)\n\n\nratio_total = weight_number+weight_string+weight_symbols\n\nif ratio_total == word_count:\n ratio_string = weight_string\n ratio_numbers = weight_number\n ratio_symbols = weight_symbols\nelse:\n ratio_string = (word_count * weight_string)/ ratio_total\n ratio_numbers = (word_count * weight_number)/ratio_total\n ratio_symbols = (word_count * weight_symbols)/ratio_total\n\n#print(\" \",ratio_string,\" \",ratio_numbers,\" \",ratio_symbols)\n\n#Code for filling in any gaps that occured when creating integer ratios\nwhile (ratio_numbers + ratio_string + ratio_symbols < word_count):\n \n ratio_increase = rm.choice([1,2,3])\n \n if ratio_increase == 1:\n ratio_string += 1\n elif ratio_increase == 2:\n ratio_numbers += 1\n else:\n ratio_symbols += 1\n\n\n#raw_password: meaning a list of selected strings, numbers and symbols to create pwd from\nraw_password = np.array([])\n\nwhile (raw_password.size < ratio_string):\n raw_password = np.append(raw_password,rm.choice(word_list))\nwhile (raw_password.size - ratio_string < ratio_numbers):\n raw_password = np.append(raw_password, rm.choice(number_list))\nwhile (raw_password.size -ratio_numbers -ratio_string < ratio_symbols):\n raw_password = np.append(raw_password, rm.choice(symbol_list))\n\n\n#Dictionary to avoid repitition\ndict1 ={k:np.count_nonzero(raw_password == k) for k in raw_password}\n\npassword = np.array([])\n\n#Final Password\nwhile(password.size < word_count):\n a = rm.choice(raw_password)\n if(dict1[a] != 0 ):\n password = np.append(password,a)\n dict1[a] -= 1\n\n\n# print (raw_password)\n# print (password)\n\n\nprint(\"\".join(password))\n\n"
] |
[
[
"numpy.append",
"numpy.array",
"numpy.count_nonzero"
]
] |
ndiamant/marchent
|
[
"70d44e314897c98692fbdb98e847c382b7a43853"
] |
[
"marchent/marcher.py"
] |
[
"from dataclasses import dataclass\nfrom typing import Callable, List\nfrom enum import Enum\nimport colorsys\n\nimport numpy as np\n\n\nclass MarcherState(Enum):\n RUNNING = 0\n SPLITTING = 1\n STOPPING = 2\n\n\ndef assert_valid_distribution(x: np.ndarray):\n np.testing.assert_allclose(x.sum(axis=1), 1)\n\n\n@dataclass\nclass Marcher:\n x: int\n y: int\n move_transitions: np.ndarray # (num global states) x 4\n state_transitions: np.ndarray # (num global states) x (num marcher states)\n color: np.ndarray # (3,)\n\n # these are used to create a new marcher on splitting\n split_color: Callable[[np.ndarray], np.ndarray] = lambda c: c.copy()\n split_move_transitions: Callable[[np.ndarray], np.ndarray] = lambda x: x.copy()\n split_state_transitions: Callable[[np.ndarray], np.ndarray] = lambda x: x.copy()\n\n def __post_init__(self):\n assert self.move_transitions.shape[1] == 4 # 4 direction choices\n assert self.state_transitions.shape[1] == len(MarcherState)\n assert_valid_distribution(self.move_transitions)\n assert_valid_distribution(self.state_transitions)\n assert self.color.shape == (3,) # 3 channel color\n assert not (self.color == 0).all() # can't be collision color\n\n def step(self, state: int) -> MarcherState:\n move_choice = np.random.choice(4, p=self.move_transitions[state])\n if move_choice == 0:\n self.x += 1\n elif move_choice == 1:\n self.x -= 1\n elif move_choice == 2:\n self.y += 1\n elif move_choice == 3:\n self.y -= 1\n\n return MarcherState(\n np.random.choice(\n len(MarcherState),\n p=self.state_transitions[state],\n )\n )\n\n def split(self) -> \"Marcher\":\n return Marcher(\n x=self.x, y=self.y,\n move_transitions=self.split_move_transitions(self.move_transitions),\n state_transitions=self.split_state_transitions(self.state_transitions),\n color=self.split_color(self.color),\n split_move_transitions=self.split_move_transitions,\n split_state_transitions=self.split_state_transitions,\n split_color=self.split_color,\n )\n\n @property\n def expected_angle(self) -> np.ndarray:\n \"\"\"expected movement angle per global state measured in degrees\"\"\"\n return np.arctan2(\n self.move_transitions[:, 3] - self.move_transitions[:, 2],\n self.move_transitions[:, 0] - self.move_transitions[:, 1]\n ) / (2 * np.pi) * 360\n\n\n# color rules\ndef rand_color(c: np.ndarray = None) -> np.ndarray:\n return np.random.randint(0, 256, size=3).astype(np.uint8)\n\n\ndef next_hsv(c: np.ndarray) -> np.ndarray:\n h, s, v = colorsys.rgb_to_hls(c[0] / 255, c[1] / 255, c[2] / 255)\n h += .05\n h %= 1\n r, g, b = colorsys.hsv_to_rgb(h, s, v)\n return (np.array([r, g, b]) * 255).astype(np.uint8)\n\n\ndef lighten(c: np.ndarray) -> np.ndarray:\n H, L, S = colorsys.rgb_to_hls(c[0] / 255, c[1] / 255, c[2] / 255)\n L += .01 * (1 - L)\n r, g, b = colorsys.hls_to_rgb(H, L, S)\n return np.clip((np.array([r, g, b]) * 255).astype(np.uint8), 1, 255)\n\n\ndef turn_color(c: np.ndarray, next_colors: List[np.ndarray]) -> np.ndarray:\n return next_colors[np.random.randint(len(next_colors))]\n\n\n# move rules\ndef ortho_split(x: np.ndarray) -> np.ndarray:\n z = x.copy()\n if np.random.rand() > .5:\n # right, left, down, up\n z[:, 0] = x[:, 2]\n z[:, 1] = x[:, 3]\n z[:, 2] = x[:, 1]\n z[:, 3] = x[:, 0]\n else:\n z[:, 0] = x[:, 3]\n z[:, 1] = x[:, 2]\n z[:, 2] = x[:, 0]\n z[:, 3] = x[:, 1]\n return z\n\n\ndef angle_split(x: np.ndarray, theta: float) -> np.ndarray:\n ortho = ortho_split(x)\n return np.sin(theta)**2 * ortho + np.cos(theta)**2 * x\n"
] |
[
[
"numpy.random.choice",
"numpy.cos",
"numpy.sin",
"numpy.arctan2",
"numpy.random.rand",
"numpy.array",
"numpy.random.randint"
]
] |
abhimandal/aneurysm-segmentation
|
[
"d491f2397e66b012a59b9a3f46a68550e0d5cd9d"
] |
[
"aneurysm_segmentation3d/scripts/modelling/model.py"
] |
[
"import os, sys\nimport torch\nimport pyvista as pv\nimport pandas as pd\nimport numpy as np\n\nsys.path.append(os.getcwd())\n\nfrom torch_points3d.applications.kpconv import KPConv\nfrom torch_points3d.core.common_modules.base_modules import (\n MultiHeadClassifier,\n)\n\n\nclass PartSegKPConv(torch.nn.Module):\n def __init__(self, cat_to_seg, input_nc):\n super().__init__()\n self.unet = KPConv(\n architecture=\"unet\",\n input_nc=input_nc,\n num_layers=4,\n in_grid_size=0.02,\n )\n self.classifier = MultiHeadClassifier(\n self.unet.output_nc, cat_to_seg\n )\n\n @property\n def conv_type(self):\n \"\"\" This is needed by the dataset to infer which batch collate should be used\"\"\"\n return self.unet.conv_type\n\n def get_batch(self):\n return self.batch\n\n def get_output(self):\n \"\"\" This is needed by the tracker to get access to the ouputs of the network\"\"\"\n return self.output\n\n def get_labels(self):\n \"\"\" Needed by the tracker in order to access ground truth labels\"\"\"\n return self.labels\n\n def get_current_losses(self):\n \"\"\" Entry point for the tracker to grab the loss \"\"\"\n return {\"loss_seg\": float(self.loss_seg)}\n\n def forward(self, data):\n self.labels = data.y\n self.batch = data.batch\n\n # Forward through unet and classifier\n data_features = self.unet(data)\n self.output = self.classifier(data_features.x, data.category)\n\n # Set loss for the backward pass\n self.loss_seg = torch.nn.functional.nll_loss(\n self.output, self.labels\n )\n return self.output\n\n def get_spatial_ops(self):\n return self.unet.get_spatial_ops()\n\n def backward(self):\n self.loss_seg.backward()\n\n"
] |
[
[
"torch.nn.functional.nll_loss"
]
] |
gurkirt/realtime-action-detection
|
[
"9dd8e1b5642c7cb3170a31cc3ec5a3c586a3b261"
] |
[
"layers/modules/multibox_loss.py"
] |
[
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom data import v2 as cfg\nfrom ..box_utils import match, log_sum_exp\n\nclass MultiBoxLoss(nn.Module):\n \"\"\"SSD Weighted Loss Function\n Compute Targets:\n 1) Produce Confidence Target Indices by matching ground truth boxes\n with (default) 'priorboxes' that have jaccard index > threshold parameter\n (default threshold: 0.5).\n 2) Produce localization target by 'encoding' variance into offsets of ground\n truth boxes and their matched 'priorboxes'.\n 3) Hard negative mining to filter the excessive number of negative examples\n that comes with using a large number of default bounding boxes.\n (default negative:positive ratio 3:1)\n Objective Loss:\n L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N\n Where, Lconf is the CrossEntropy Loss and Lloc is the SmoothL1 Loss\n weighted by α which is set to 1 by cross val.\n Args:\n c: class confidences,\n l: predicted boxes,\n g: ground truth boxes\n N: number of matched default boxes\n See: https://arxiv.org/pdf/1512.02325.pdf for more details.\n \"\"\"\n\n def __init__(self, num_classes, overlap_thresh, prior_for_matching,\n bkg_label, neg_mining, neg_pos, neg_overlap, encode_target,\n use_gpu=True):\n super(MultiBoxLoss, self).__init__()\n self.use_gpu = use_gpu\n self.num_classes = num_classes\n self.threshold = overlap_thresh\n self.background_label = bkg_label\n self.encode_target = encode_target\n self.use_prior_for_matching = prior_for_matching\n self.do_neg_mining = neg_mining\n self.negpos_ratio = neg_pos\n self.neg_overlap = neg_overlap\n self.variance = cfg['variance']\n\n def forward(self, predictions, targets):\n \"\"\"Multibox Loss\n Args:\n predictions (tuple): A tuple containing loc preds, conf preds,\n and prior boxes from SSD net.\n conf shape: torch.size(batch_size,num_priors,num_classes)\n loc shape: torch.size(batch_size,num_priors,4)\n priors shape: torch.size(num_priors,4)\n\n ground_truth (tensor): Ground truth boxes and labels for a batch,\n shape: [batch_size,num_objs,5] (last idx is the label).\n \"\"\"\n loc_data, conf_data, priors = predictions\n num = loc_data.size(0)\n priors = priors[:loc_data.size(1), :]\n num_priors = (priors.size(0))\n num_classes = self.num_classes\n\n # match priors (default boxes) and ground truth boxes\n with torch.no_grad():\n if self.use_gpu:\n loc_t = torch.cuda.FloatTensor(num, num_priors, 4)\n conf_t = torch.cuda.LongTensor(num, num_priors)\n else:\n loc_t = torch.Tensor(num, num_priors, 4)\n conf_t = torch.LongTensor(num, num_priors)\n for idx in range(num):\n truths = targets[idx][:, :-1].data\n labels = targets[idx][:, -1].data\n defaults = priors.data\n match(self.threshold, truths, defaults, self.variance, labels,\n loc_t, conf_t, idx)\n if self.use_gpu:\n loc_t = loc_t.cuda()\n conf_t = conf_t.cuda()\n # wrap targets\n # loc_t = Variable(loc_t, requires_grad=False)\n # conf_t = Variable(conf_t, requires_grad=False)\n\n pos = conf_t > 0\n #num_pos = pos.sum(keepdim=True)\n\n # Localization Loss (Smooth L1)\n # Shape: [batch,num_priors,4]\n pos_idx = pos.unsqueeze(pos.dim()).expand_as(loc_data)\n loc_p = loc_data[pos_idx].view(-1, 4)\n loc_t = loc_t[pos_idx].view(-1, 4)\n loss_l = F.smooth_l1_loss(loc_p, loc_t, reduction='sum')\n with torch.no_grad():\n # Compute max conf across batch for hard negative mining\n batch_conf = conf_data.view(-1, self.num_classes)\n\n loss_c = log_sum_exp(batch_conf) - batch_conf.gather(1, conf_t.view(-1, 1))\n\n # Hard Negative Mining\n loss_c[pos.view(-1,1)] = 0 # filter out pos boxes for now\n loss_c = loss_c.view(num, -1)\n _, loss_idx = loss_c.sort(1, descending=True)\n _, idx_rank = loss_idx.sort(1)\n num_pos = pos.long().sum(1, keepdim=True)\n num_neg = torch.clamp(self.negpos_ratio*num_pos, max=pos.size(1)-1)\n neg = idx_rank < num_neg.expand_as(idx_rank)\n\n # Confidence Loss Including Positive and Negative Examples\n pos_idx = pos.unsqueeze(2).expand_as(conf_data)\n neg_idx = neg.unsqueeze(2).expand_as(conf_data)\n\n conf_p = conf_data[(pos_idx+neg_idx).gt(0)].view(-1, self.num_classes)\n targets_weighted = conf_t[(pos+neg).gt(0)]\n loss_c = F.cross_entropy(conf_p, targets_weighted, reduction='sum')\n\n # Sum of losses: L(x,c,l,g) = (Lconf(x, c) + αLloc(x,l,g)) / N\n\n N = float(num_pos.data.sum())\n loss_l /= N\n loss_c /= N\n return loss_l, loss_c\n"
] |
[
[
"torch.LongTensor",
"torch.Tensor",
"torch.nn.functional.cross_entropy",
"torch.cuda.LongTensor",
"torch.cuda.FloatTensor",
"torch.no_grad",
"torch.nn.functional.smooth_l1_loss"
]
] |
zhouzhouxpyf/CFN-softbio
|
[
"21e4f4845e7a49c97f4ed2b0aa78a7eb831f6bcc"
] |
[
"examples/autonomous/ErrorPlotter.py"
] |
[
"#!/usr/bin/python3\n\nimport numpy as np\nimport matplotlib as mpl\nmpl.rcParams['mathtext.fontset'] = 'cm'\nimport pylab as plt\n\n# Helpers\n########################################\n# TODO: DEPRECATED in favor of tools.val_stats\ndef print_d(d, i=4):\n '''Simple helper to print a dictionary.'''\n for k, v in d.items():\n if isinstance(v,dict):\n print('{}{} : <dict>'.format(' '*i,k))\n print_d(v, i=i+4)\n elif isinstance(v,(np.ndarray)):\n print('{}{} : Ar{}: {}'.format(' '*i,k,v.shape,v))\n elif isinstance(v,(list,tuple)):\n print('{}{} : L{}: {}'.format(' '*i,k,len(v),v))\n else:\n print('{}{} : {}'.format(' '*i,k,v))\n\ndef print_results(results):\n '''Simple helper to print out a list of dictionaries.'''\n for i, result in enumerate(results):\n print(i)\n print_d(result)\n\ndef print_n(d):\n '''Simple helper to print nested arrays/dicts'''\n if isinstance(d, (list,tuple,np.ndarray)):\n print_results(d)\n elif isinstance(d, dict):\n print_d(d)\n else:\n print(d)\n\ndef val_stats(values, name='z'):\n span = np.max(values)-np.min(values)\n print(\" {} = {:.2g} ± {:.2g} (span {:.2g}, from {:.3g} to {:.3g})\".format(name, np.average(values), np.std(values), span, np.min(values), np.max(values)))\n\n\n\nclass Plotter():\n '''A generic (shell) class meant to streamline plotting. The intent is to modify this\n class for a specific plot.\n \n The structure of the class follows the convetions used in SciAnalysis:\n https://github.com/CFN-softbio/SciAnalysis/\n '''\n \n def __init__(self, x=None, y=None, name=None, plot_args=None, **kwargs):\n \n self.x = x\n self.y = y\n self.name = name\n\n self.x_label = kwargs['x_label'] if 'x_label' in kwargs else 'x'\n self.y_label = kwargs['y_label'] if 'y_label' in kwargs else 'y'\n self.x_rlabel = kwargs['x_rlabel'] if 'x_rlabel' in kwargs else self.x_label\n self.y_rlabel = kwargs['y_rlabel'] if 'y_rlabel' in kwargs else self.y_label\n self.x_err = kwargs['x_err'] if 'x_err' in kwargs else None\n self.y_err = kwargs['y_err'] if 'y_err' in kwargs else None\n \n self.plot_valid_keys = ['color', 'linestyle', 'linewidth', 'marker', 'markerfacecolor', 'markersize', 'alpha', 'markeredgewidth', 'markeredgecolor', 'capsize', 'ecolor', 'elinewidth']\n self.plot_args = { 'color' : 'k',\n 'marker' : None,\n 'linewidth' : 3.0,\n 'rcParams': {'axes.labelsize': 35,\n 'xtick.labelsize': 30,\n 'ytick.labelsize': 30,\n },\n } \n if plot_args: self.plot_args.update(plot_args)\n self._kwargs = kwargs # Save incase later methods depend on these settings\n \n \n def plot(self, save=None, show=False, plot_range=[None,None,None,None], plot_buffers=[0.2,0.05,0.2,0.05], **kwargs):\n '''Plots the data.\n \n Parameters\n ----------\n save : str\n Set to 'None' to avoid saving to disk. Provide filename to save.\n show : bool\n Set to true to open an interactive window.\n plot_range : [float, float, float, float]\n Set the range of the plotting (None scales automatically instead).\n ''' \n \n self._plot(save=save, show=show, plot_range=plot_range, plot_buffers=plot_buffers, **kwargs)\n \n \n def _plot(self, save=None, show=False, plot_range=[None,None,None,None], plot_buffers=[0.2,0.05,0.2,0.05], error=False, error_band=False, xlog=False, ylog=False, xticks=None, yticks=None, dashes=None, transparent=False, **kwargs):\n \n # DataLine._plot()\n \n plot_args = self.plot_args.copy()\n plot_args.update(kwargs)\n self.process_plot_args(**plot_args)\n \n \n \n self.fig = plt.figure( figsize=(10,7), facecolor='white' )\n left_buf, right_buf, bottom_buf, top_buf = plot_buffers\n fig_width = 1.0-right_buf-left_buf\n fig_height = 1.0-top_buf-bottom_buf\n self.ax = self.fig.add_axes( [left_buf, bottom_buf, fig_width, fig_height] )\n \n \n p_args = dict([(i, plot_args[i]) for i in self.plot_valid_keys if i in plot_args])\n self._plot_main(error=error, error_band=error_band, dashes=dashes, **p_args)\n \n \n self.ax.set_xlabel(self.x_rlabel)\n self.ax.set_ylabel(self.y_rlabel)\n \n if xlog:\n plt.semilogx()\n if ylog:\n plt.semilogy()\n if xticks is not None:\n self.ax.set_xticks(xticks)\n if yticks is not None:\n self.ax.set_yticks(yticks)\n\n if 'gridlines' in plot_args and plot_args['gridlines']:\n plt.grid()\n \n if 'title' in plot_args and plot_args['title'] is not None:\n size = plot_args['rcParams']['axes.labelsize']*0.5\n #size = plot_args['rcParams']['xtick.labelsize']\n plt.figtext(0, 1, plot_args['title'], size=size, weight='bold', verticalalignment='top', horizontalalignment='left')\n \n \n # Axis scaling\n xi, xf, yi, yf = self.ax.axis()\n if plot_range[0] != None: xi = plot_range[0]\n if plot_range[1] != None: xf = plot_range[1]\n if plot_range[2] != None: yi = plot_range[2]\n if plot_range[3] != None: yf = plot_range[3]\n self.ax.axis( [xi, xf, yi, yf] )\n \n self._plot_extra(**plot_args)\n \n if save:\n if 'dpi' in plot_args:\n plt.savefig(save, dpi=plot_args['dpi'], transparent=transparent)\n else:\n plt.savefig(save, transparent=transparent)\n \n if show:\n self._plot_interact()\n plt.show()\n \n plt.close(self.fig.number)\n \n \n\n def _plot_main(self, error=False, error_band=False, dashes=None, **plot_args):\n \n #l, = plt.plot(self.x, self.y, **plot_args)\n l, = self.ax.plot(self.x, self.y, alpha=0.25, **plot_args)\n \n from scipy.ndimage import gaussian_filter1d\n \n y_smoothed = gaussian_filter1d(self.y, sigma=10, mode='nearest')\n \n l, = self.ax.plot(self.x, y_smoothed, **plot_args)\n if dashes is not None:\n l.set_dashes(dashes) \n\n\n N = int(len(self.y)*0.10)\n y_final = np.average(self.y[-N:])\n self.ax.axhline(y_final, color='b', alpha=0.5, linewidth=1.0)\n \n thresh = 0.8\n y_span = self.y[0]-y_final\n y_target = self.y[0] - y_span*thresh\n xt, yt = self.target_y(np.asarray(self.x), np.asarray(y_smoothed), y_target)\n self.ax.plot(xt, yt, 'o', color='b', markersize=10, alpha=0.75)\n s = '$\\epsilon$ decrease reaches {:.0f}% by $N = {:d}$'.format(100*thresh, xt)\n e = y_span*0.3\n self.ax.text(xt, yt+e, s, size=15, color='b', verticalalignment='bottom', horizontalalignment='left')\n self.ax.plot([xt, xt], [yt, yt+e], color='b', alpha=0.5, linewidth=0.5)\n \n \n def target_y(self, x, y, target):\n '''Find the datapoint closest to the given y.'''\n \n #x = np.asarray(self.x)\n #y = np.asarray(self.y)\n\n # Sort\n indices = np.argsort(y)\n x_sorted = x[indices]\n y_sorted = y[indices]\n\n # Search through y for the target\n idx = np.where( y_sorted>=target )[0][0]\n xcur = x_sorted[idx]\n ycur = y_sorted[idx]\n \n return xcur, ycur\n \n \n \n \n def _plot_extra(self, **plot_args):\n '''This internal function can be over-ridden in order to force additional\n plotting behavior.'''\n \n pass\n \n \n\n def process_plot_args(self, **plot_args):\n \n if 'rcParams' in plot_args:\n for param, value in plot_args['rcParams'].items():\n plt.rcParams[param] = value \n \n \n \nif __name__ == '__main__':\n \n \n #infile = 'Data_2021-02-09_10_33_48_model_1.npy' # 101\n #infile, sample_name = 'Data_2021-02-09_11_59_02_model_1.npy', 'sample2_anneal15_run1' # 1341\n #infile, sample_name = 'Data_2021-02-09_21_54_05_model_1.npy', 'sample3_anneal1200_run1' # 1502\n #infile, sample_name = 'Data_2021-02-10_08_57_09_model_1.npy', 'sample5_anneal300_run1' # 1312 \n infile, sample_name = 'Data_2021-02-10_18_29_11_model_1.npy', 'sample1_anneal5_run1' # 1244 \n #infile = 'Data_2021-02-11_03_39_16_model_1.npy' # 4\n #infile = 'Data_2021-02-11_03_43_42_model_1.npy' # 767\n \n data = np.load(infile, allow_pickle=True)\n print('Loaded {} records from {}'.format(data.shape[0], infile))\n print(' filename: {}'.format(data[-1]['filename']))\n \n vals = np.asarray([d['time stamp'] for d in data])\n idx = np.argsort(vals)\n data = data[idx]\n \n #vals = np.asarray([d['objective function evaluation'] for d in data])\n vals = []\n for d in data:\n if 'objective function evaluation' in d:\n vals.append(d['objective function evaluation'])\n Ns = range(len(vals))\n \n \n p = Plotter(x=Ns, y=vals, x_rlabel='$N$', y_rlabel='$ \\epsilon \\, (\\mathrm{a.u.})$')\n\n p.plot(save='error_history-{}.png'.format(sample_name), title=sample_name, plot_range=[0, None, None, None], plot_buffers=[0.14, 0.04, 0.15, 0.08])\n"
] |
[
[
"numpy.min",
"numpy.asarray",
"scipy.ndimage.gaussian_filter1d",
"numpy.max",
"numpy.std",
"numpy.argsort",
"numpy.load",
"numpy.average",
"numpy.where"
]
] |
ExpressAI/DataLab
|
[
"c3eddd4068f131d031c2486c60b650092bb0ae84"
] |
[
"datalabs/utils/streaming_download_manager.py"
] |
[
"from asyncio import TimeoutError\nimport glob\nfrom itertools import chain\nimport os\nfrom pathlib import Path, PurePosixPath\nimport posixpath\nimport re\nimport tarfile\nimport time\nfrom typing import List, Optional, Tuple, Union\n\nfrom aiohttp.client_exceptions import ClientError\nimport fsspec\n\nfrom datalabs import config\nfrom datalabs.filesystems import COMPRESSION_FILESYSTEMS\nfrom datalabs.utils.download_manager import DownloadConfig, map_nested\nfrom datalabs.utils.file_utils import (\n get_authentication_headers_for_url,\n http_head,\n is_local_path,\n is_relative_path,\n is_remote_url,\n url_or_path_join,\n)\nfrom datalabs.utils.logging import get_logger\n\nlogger = get_logger(__name__)\n\nBASE_KNOWN_EXTENSIONS = [\n \"txt\",\n \"csv\",\n \"json\",\n \"jsonl\",\n \"tsv\",\n \"conll\",\n \"conllu\",\n \"orig\",\n \"parquet\",\n \"pkl\",\n \"pickle\",\n \"rel\",\n \"xml\",\n]\nCOMPRESSION_EXTENSION_TO_PROTOCOL = {\n # single file compression\n **{\n fs_class.extension.lstrip(\".\"): fs_class.protocol\n for fs_class in COMPRESSION_FILESYSTEMS\n },\n # archive compression\n \"zip\": \"zip\",\n \"tar\": \"tar\",\n \"tgz\": \"tar\",\n}\nSINGLE_FILE_COMPRESSION_PROTOCOLS = {\n fs_class.protocol for fs_class in COMPRESSION_FILESYSTEMS\n}\nSINGLE_SLASH_AFTER_PROTOCOL_PATTERN = re.compile(r\"(?<!:):/\")\n\n\nMAGIC_NUMBER_TO_COMPRESSION_PROTOCOL = {\n bytes.fromhex(\"504B0304\"): \"zip\",\n bytes.fromhex(\"504B0506\"): \"zip\", # empty archive\n bytes.fromhex(\"504B0708\"): \"zip\", # spanned archive\n bytes.fromhex(\"425A68\"): \"bz2\",\n bytes.fromhex(\"1F8B\"): \"gzip\",\n bytes.fromhex(\"FD377A585A00\"): \"xz\",\n bytes.fromhex(\"04224D18\"): \"lz4\",\n bytes.fromhex(\"28B52FFD\"): \"zstd\",\n}\nMAGIC_NUMBER_TO_UNSUPPORTED_COMPRESSION_PROTOCOL = {\n b\"Rar!\": \"rar\",\n}\nMAGIC_NUMBER_MAX_LENGTH = max(\n len(magic_number)\n for magic_number in chain(\n MAGIC_NUMBER_TO_COMPRESSION_PROTOCOL,\n MAGIC_NUMBER_TO_UNSUPPORTED_COMPRESSION_PROTOCOL,\n )\n)\n\n\ndef xjoin(a, *p):\n \"\"\"\n This function extends os.path.join to support the \"::\" hop\n separator. It supports both paths and urls.\n\n A shorthand, particularly useful where you have multiple hops,\n is to “chain” the URLs with the special separator \"::\".\n This is used to access files inside a zip file over http for\n example.\n\n Let's say you have a zip file at https://host.com/archive.zip\n , and you want to access the file inside the zip file at /folder1/file.txt.\n Then you can just chain the url this way:\n\n zip://folder1/file.txt::https://host.com/archive.zip\n\n The xjoin function allows you to apply the join on the first path of the chain.\n\n Example::\n\n >>> xjoin(\"zip://folder1::https://host.com/archive.zip\", \"file.txt\")\n zip://folder1/file.txt::https://host.com/archive.zip\n \"\"\"\n a, *b = a.split(\"::\")\n if is_local_path(a):\n a = Path(a, *p).as_posix()\n else:\n a = posixpath.join(a, *p)\n return \"::\".join([a] + b)\n\n\ndef xdirname(a):\n \"\"\"\n This function extends os.path.dirname to support the \"::\" hop separator.\n It supports both paths and urls.\n\n A shorthand, particularly useful where you have multiple hops, is\n to “chain” the URLs with the special separator \"::\".\n This is used to access files inside a zip file over http for example.\n\n Let's say you have a zip file at https://host.com/archive.zip, and\n you want to access the file inside the zip file at /folder1/file.txt.\n Then you can just chain the url this way:\n\n zip://folder1/file.txt::https://host.com/archive.zip\n\n The xdirname function allows you to apply the dirname on the\n first path of the chain.\n\n Example::\n\n >>> xdirname(\"zip://folder1/file.txt::https://host.com/archive.zip\")\n zip://folder1::https://host.com/archive.zip\n \"\"\"\n a, *b = a.split(\"::\")\n if is_local_path(a):\n a = os.path.dirname(Path(a).as_posix())\n else:\n a = posixpath.dirname(a)\n # if we end up at the root of the protocol, we get for example a = 'http:'\n # so we have to fix it by adding the '//' that was removed:\n if a.endswith(\":\"):\n a += \"//\"\n return \"::\".join([a] + b)\n\n\ndef xbasename(a):\n \"\"\"\n This function extends os.path.basename to support the \"::\" hop separator.\n It supports both paths and urls.\n\n A shorthand, particularly useful where you have multiple hops, is to\n “chain” the URLs with the special separator \"::\".\n This is used to access files inside a zip file over http for example.\n\n Let's say you have a zip file at https://host.com/archive.zip,\n and you want to access the file inside the zip file at /folder1/file.txt.\n Then you can just chain the url this way:\n\n zip://folder1/file.txt::https://host.com/archive.zip\n\n The xbasename function allows you to apply the basename on the\n first path of the chain.\n\n Example::\n\n >>> xbasename(\"zip://folder1/file.txt::https://host.com/archive.zip\")\n file.txt\n \"\"\"\n a, *b = a.split(\"::\")\n if is_local_path(a):\n return os.path.basename(Path(a).as_posix())\n else:\n return posixpath.basename(a)\n\n\ndef _as_posix(path: Path):\n \"\"\"Extend :meth:`pathlib.PurePath.as_posix` to fix missing slashes after protocol.\n\n Args:\n path (:obj:`~pathlib.Path`): Calling Path instance.\n\n Returns:\n obj:`str`\n \"\"\"\n path_as_posix = path.as_posix()\n path_as_posix = SINGLE_SLASH_AFTER_PROTOCOL_PATTERN.sub(\"://\", path_as_posix)\n path_as_posix += (\n \"//\" if path_as_posix.endswith(\":\") else \"\"\n ) # Add slashes to root of the protocol\n return path_as_posix\n\n\ndef xpathjoin(a: Path, *p: Tuple[str, ...]):\n \"\"\"Extend :func:`xjoin` to support argument of type :obj:`~pathlib.Path`.\n\n Args:\n a (:obj:`~pathlib.Path`): Calling Path instance.\n *p (:obj:`tuple` of :obj:`str`): Other path components.\n\n Returns:\n obj:`str`\n \"\"\"\n return type(a)(xjoin(_as_posix(a), *p))\n\n\ndef _add_retries_to_file_obj_read_method(file_obj):\n read = file_obj.read\n max_retries = config.STREAMING_READ_MAX_RETRIES\n\n def read_with_retries(*args, **kwargs):\n for retry in range(1, max_retries + 1):\n try:\n out = read(*args, **kwargs)\n break\n except (ClientError, TimeoutError):\n logger.warning(\n f\"Got disconnected from remote data host. \"\n f\"Retrying in {config.STREAMING_READ_RETRY_INTERVAL}sec\"\n f\" [{retry}/{max_retries}]\"\n )\n time.sleep(config.STREAMING_READ_RETRY_INTERVAL)\n else:\n raise ConnectionError(\"Server Disconnected\")\n return out\n\n file_obj.read = read_with_retries\n\n\ndef _get_extraction_protocol_with_magic_number(f) -> Optional[str]:\n \"\"\"read the magic number from a file-like object and return\n the compression protocol\"\"\"\n prev_loc = f.loc\n magic_number = f.read(MAGIC_NUMBER_MAX_LENGTH)\n f.seek(prev_loc)\n for i in range(MAGIC_NUMBER_MAX_LENGTH):\n compression = MAGIC_NUMBER_TO_COMPRESSION_PROTOCOL.get(\n magic_number[: MAGIC_NUMBER_MAX_LENGTH - i]\n )\n if (\n compression is not None\n ): # TODO(QL): raise an error for .tar.gz files as in _get_extraction_protocol\n return compression\n compression = MAGIC_NUMBER_TO_UNSUPPORTED_COMPRESSION_PROTOCOL.get(\n magic_number[: MAGIC_NUMBER_MAX_LENGTH - i]\n )\n if compression is not None:\n raise NotImplementedError(\n f\"Compression protocol '{compression}' not implemented.\"\n )\n\n\ndef _get_extraction_protocol(\n urlpath: str, use_auth_token: Optional[Union[str, bool]] = None\n) -> Optional[str]:\n # get inner file: zip://train-00000.json.gz::https://foo.bar/data.zip\n # -> zip://train-00000.json.gz\n path = urlpath.split(\"::\")[0]\n # Get extension: https://foo.bar/train.json.gz -> gz\n extension = path.split(\".\")[-1]\n # Remove query params (\"dl=1\", \"raw=true\"): gz?dl=1 -> gz\n # Remove shards infos (\".txt_1\", \".txt-00000-of-00100\"): txt_1 -> txt\n for symb in \"?-_\":\n extension = extension.split(symb)[0]\n if extension in BASE_KNOWN_EXTENSIONS:\n return None\n elif path.endswith(\".tar.gz\") or path.endswith(\".tgz\"):\n raise NotImplementedError(\n f\"Extraction protocol for TAR archives like '{urlpath}' is \"\n f\"not implemented in streaming mode. Please use \"\n f\"`dl_manager.iter_archive` instead.\"\n )\n elif extension in COMPRESSION_EXTENSION_TO_PROTOCOL:\n return COMPRESSION_EXTENSION_TO_PROTOCOL[extension]\n\n if is_remote_url(urlpath):\n # get headers and cookies for authentication on the HF Hub and for Google Drive\n urlpath, kwargs = _prepare_http_url_kwargs(\n urlpath, use_auth_token=use_auth_token\n )\n else:\n urlpath, kwargs = urlpath, {}\n with fsspec.open(urlpath, **kwargs) as f:\n return _get_extraction_protocol_with_magic_number(f)\n\n\ndef _prepare_http_url_kwargs(\n url: str, use_auth_token: Optional[Union[str, bool]] = None\n) -> Tuple[str, dict]:\n \"\"\"\n Prepare the URL and the kwargs that must be passed to the\n HttpFileSystem or to requests.get/head\n\n In particular it resolves google drive URLs and it adds\n the authentication headers for the Hugging Face Hub.\n \"\"\"\n kwargs = {\n \"headers\": get_authentication_headers_for_url(\n url, use_auth_token=use_auth_token\n )\n }\n if \"drive.google.com\" in url:\n response = http_head(url)\n cookies = None\n for k, v in response.cookies.items():\n if k.startswith(\"download_warning\"):\n url += \"&confirm=\" + v\n cookies = response.cookies\n kwargs[\"cookies\"] = cookies\n if url.startswith(\"https://raw.githubusercontent.com/\"):\n # Workaround for served data with gzip content-encoding:\n # https://github.com/fsspec/filesystem_spec/issues/389\n kwargs[\"block_size\"] = 0\n return url, kwargs\n\n\ndef xopen(\n file: str,\n mode=\"r\",\n *args,\n use_auth_token: Optional[Union[str, bool]] = None,\n **kwargs,\n):\n \"\"\"\n This function extends the builtin `open` function to support remote\n files using fsspec.\n\n It also has a retry mechanism in case connection fails.\n The args and kwargs are passed to fsspec.open, except `use_auth_token`\n which is used for queries to private repos on huggingface.co\n \"\"\"\n main_hop, *rest_hops = file.split(\"::\")\n # add headers and cookies for authentication on the HF Hub and for Google Drive\n if not rest_hops and (\n main_hop.startswith(\"http://\") or main_hop.startswith(\"https://\")\n ):\n file, new_kwargs = _prepare_http_url_kwargs(file, use_auth_token=use_auth_token)\n elif rest_hops and (\n rest_hops[0].startswith(\"http://\") or rest_hops[0].startswith(\"https://\")\n ):\n url = rest_hops[0]\n url, http_kwargs = _prepare_http_url_kwargs(url, use_auth_token=use_auth_token)\n new_kwargs = {\"https\": http_kwargs}\n file = \"::\".join([main_hop, url, *rest_hops[1:]])\n else:\n new_kwargs = {}\n kwargs = {**kwargs, **new_kwargs}\n file_obj = fsspec.open(file, mode=mode, *args, **kwargs).open()\n _add_retries_to_file_obj_read_method(file_obj)\n return file_obj\n\n\ndef xlistdir(path: str, use_auth_token: Optional[Union[str, bool]] = None) -> List[str]:\n \"\"\"Extend `os.listdir` function to support remote files.\n\n Args:\n path (:obj:`str`): URL path.\n\n Returns:\n :obj:`list` of :obj:`str`\n \"\"\"\n main_hop, *rest_hops = path.split(\"::\")\n if is_local_path(main_hop):\n return os.listdir(path)\n else:\n # globbing inside a zip in a private repo requires authentication\n if rest_hops and fsspec.get_fs_token_paths(rest_hops[0])[0].protocol == \"https\":\n storage_options = {\n \"https\": {\n \"headers\": get_authentication_headers_for_url(\n rest_hops[0], use_auth_token=use_auth_token\n )\n }\n }\n else:\n storage_options = None\n fs, *_ = fsspec.get_fs_token_paths(path, storage_options=storage_options)\n objects = fs.listdir(main_hop.split(\"://\")[1])\n return [os.path.basename(obj[\"name\"]) for obj in objects]\n\n\ndef xpathopen(path: Path, *args, **kwargs):\n \"\"\"Extend :func:`xopen` to support argument of type :obj:`~pathlib.Path`.\n\n Args:\n path (:obj:`~pathlib.Path`): Calling Path instance.\n **kwargs: Keyword arguments passed to :func:`fsspec.open`.\n\n Returns:\n :obj:`io.FileIO`: File-like object.\n \"\"\"\n return xopen(_as_posix(path), *args, **kwargs)\n\n\ndef xglob(\n urlpath, *, recursive=False, use_auth_token: Optional[Union[str, bool]] = None\n):\n \"\"\"Extend `glob.glob` function to support remote files.\n\n Args:\n urlpath (:obj:`str`): URL path with shell-style wildcard patterns.\n recursive (:obj:`bool`, default `False`):\n Whether to match the \"**\" pattern recursively to zero or more\n directories or subdirectories.\n\n Returns:\n :obj:`list` of :obj:`str`\n \"\"\"\n main_hop, *rest_hops = urlpath.split(\"::\")\n if is_local_path(main_hop):\n return glob.glob(main_hop, recursive=recursive)\n else:\n # globbing inside a zip in a private repo requires authentication\n if rest_hops and (\n rest_hops[0].startswith(\"http://\") or rest_hops[0].startswith(\"https://\")\n ):\n url = rest_hops[0]\n url, kwargs = _prepare_http_url_kwargs(url, use_auth_token=use_auth_token)\n storage_options = {\"https\": kwargs}\n urlpath = \"::\".join([main_hop, url, *rest_hops[1:]])\n else:\n storage_options = None\n fs, *_ = fsspec.get_fs_token_paths(urlpath, storage_options=storage_options)\n # - If there's no \"*\" in the pattern, get_fs_token_paths()\n # doesn't do any pattern matching\n # so to be able to glob patterns like \"[0-9]\", we have to call `fs.glob`.\n # - Also \"*\" in get_fs_token_paths() only matches files:\n # we have to call `fs.glob` to match directories.\n # - If there is \"**\" in the pattern, `fs.glob` must be called anyway.\n globbed_paths = fs.glob(main_hop)\n return [\n \"::\".join([f\"{fs.protocol}://{globbed_path}\"] + rest_hops)\n for globbed_path in globbed_paths\n ]\n\n\ndef xpathglob(path, pattern, use_auth_token: Optional[Union[str, bool]] = None):\n \"\"\"Glob function for argument of type :obj:`~pathlib.Path` that\n supports both local paths end remote URLs.\n\n Args:\n path (:obj:`~pathlib.Path`): Calling Path instance.\n pattern (:obj:`str`): Pattern that resulting paths must match.\n\n Yields:\n :obj:`~pathlib.Path`\n \"\"\"\n posix_path = _as_posix(path)\n main_hop, *rest_hops = posix_path.split(\"::\")\n if is_local_path(main_hop):\n yield from Path(main_hop).glob(pattern)\n else:\n # globbing inside a zip in a private repo requires authentication\n if rest_hops and (\n rest_hops[0].startswith(\"http://\") or rest_hops[0].startswith(\"https://\")\n ):\n url = rest_hops[0]\n url, kwargs = _prepare_http_url_kwargs(url, use_auth_token=use_auth_token)\n storage_options = {\"https\": kwargs}\n posix_path = \"::\".join([main_hop, url, *rest_hops[1:]])\n else:\n storage_options = None\n fs, *_ = fsspec.get_fs_token_paths(\n xjoin(posix_path, pattern), storage_options=storage_options\n )\n # - If there's no \"*\" in the pattern, get_fs_token_paths() doesn't\n # do any pattern matching\n # so to be able to glob patterns like \"[0-9]\", we have to call `fs.glob`.\n # - Also \"*\" in get_fs_token_paths() only matches files: we have\n # to call `fs.glob` to match directories.\n # - If there is \"**\" in the pattern, `fs.glob` must be called anyway.\n globbed_paths = fs.glob(xjoin(main_hop, pattern))\n for globbed_path in globbed_paths:\n yield type(path)(\"::\".join([f\"{fs.protocol}://{globbed_path}\"] + rest_hops))\n\n\ndef xpathrglob(path, pattern, **kwargs):\n \"\"\"Rglob function for argument of type :obj:`~pathlib.Path` that supports\n both local paths end remote URLs.\n\n Args:\n path (:obj:`~pathlib.Path`): Calling Path instance.\n pattern (:obj:`str`): Pattern that resulting paths must match.\n\n Yields:\n :obj:`~pathlib.Path`\n \"\"\"\n return xpathglob(path, \"**/\" + pattern, **kwargs)\n\n\ndef xpathstem(path: Path):\n \"\"\"Stem function for argument of type :obj:`~pathlib.Path` that supports\n both local paths end remote URLs.\n\n Args:\n path (:obj:`~pathlib.Path`): Calling Path instance.\n\n Returns:\n :obj:`str`\n \"\"\"\n return PurePosixPath(_as_posix(path).split(\"::\")[0]).stem\n\n\ndef xpathsuffix(path: Path):\n \"\"\"Suffix function for argument of type :obj:`~pathlib.Path` that\n supports both local paths end remote URLs.\n\n Args:\n path (:obj:`~pathlib.Path`): Calling Path instance.\n\n Returns:\n :obj:`str`\n \"\"\"\n return PurePosixPath(_as_posix(path).split(\"::\")[0]).suffix\n\n\ndef xpandas_read_csv(\n filepath_or_buffer, use_auth_token: Optional[Union[str, bool]] = None, **kwargs\n):\n import pandas as pd\n\n if hasattr(filepath_or_buffer, \"read\"):\n return pd.read_csv(filepath_or_buffer, **kwargs)\n else:\n return pd.read_csv(\n xopen(filepath_or_buffer, use_auth_token=use_auth_token), **kwargs\n )\n\n\nclass StreamingDownloadManager(object):\n \"\"\"\n Download manager that uses the \"::\" separator to navigate through\n (possibly remote) compressed archives.\n Contrary to the regular DownloadManager, the `download` and\n `extract` methods don't actually download nor extract\n data, but they rather return the path or url that could be opened\n using the `xopen` function which extends the\n builtin `open` function to stream data from remote files.\n \"\"\"\n\n def __init__(\n self,\n dataset_name: Optional[str] = None,\n data_dir: Optional[str] = None,\n download_config: Optional[DownloadConfig] = None,\n base_path: Optional[str] = None,\n ):\n self._dataset_name = dataset_name\n self._data_dir = data_dir\n self._base_path = base_path or os.path.abspath(\".\")\n self.download_config = download_config or DownloadConfig()\n\n @property\n def manual_dir(self):\n return self._data_dir\n\n def download(self, url_or_urls):\n url_or_urls = map_nested(self._download, url_or_urls, map_tuple=True)\n return url_or_urls\n\n def _download(self, urlpath: str) -> str:\n urlpath = str(urlpath)\n if is_relative_path(urlpath):\n # append the relative path to the base_path\n urlpath = url_or_path_join(self._base_path, urlpath)\n return urlpath\n\n def extract(self, path_or_paths):\n urlpaths = map_nested(self._extract, path_or_paths, map_tuple=True)\n return urlpaths\n\n def _extract(self, urlpath: str) -> str:\n urlpath = str(urlpath)\n protocol = _get_extraction_protocol(\n urlpath, use_auth_token=self.download_config.use_auth_token\n )\n if protocol is None:\n # no extraction\n return urlpath\n elif protocol in SINGLE_FILE_COMPRESSION_PROTOCOLS:\n # there is one single file which is the uncompressed file\n inner_file = os.path.basename(urlpath.split(\"::\")[0])\n inner_file = (\n inner_file[: inner_file.rindex(\".\")]\n if \".\" in inner_file\n else inner_file\n )\n # check for tar.gz, tar.bz2 etc.\n if inner_file.endswith(\".tar\"):\n return f\"tar://::{protocol}://{inner_file}::{urlpath}\"\n else:\n return f\"{protocol}://{inner_file}::{urlpath}\"\n else:\n return f\"{protocol}://::{urlpath}\"\n\n def download_and_extract(self, url_or_urls):\n return self.extract(self.download(url_or_urls))\n\n def iter_archive(self, urlpath: str):\n \"\"\"Returns iterator over files within archive.\n\n Args:\n path: path to archive.\n\n Returns:\n Generator yielding tuple (path_within_archive, file_obj).\n File-Obj are opened in byte mode (io.BufferedReader)\n \"\"\"\n with xopen(\n urlpath, \"rb\", use_auth_token=self.download_config.use_auth_token\n ) as f:\n stream = tarfile.open(fileobj=f, mode=\"r|*\")\n for tarinfo in stream:\n file_path = tarinfo.name\n if not tarinfo.isreg():\n continue\n if file_path is None:\n continue\n if os.path.basename(file_path).startswith(\".\") or os.path.basename(\n file_path\n ).startswith(\"__\"):\n # skipping hidden files\n continue\n file_obj = stream.extractfile(tarinfo)\n yield (file_path, file_obj)\n stream.members = []\n del stream\n"
] |
[
[
"pandas.read_csv"
]
] |
htet96/Integration-of-THOR-and-SiamRPN-wip-
|
[
"74d4baded10acfe6b35c6d7b2c66a3da6c36f4a1"
] |
[
"trackers/SiamRPNpp/tracker/siammask_tracker.py"
] |
[
"# Copyright (c) SenseTime. All Rights Reserved.\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nfrom __future__ import unicode_literals\n\nimport cv2\nimport numpy as np\n\nfrom siamrpnpp.core.config import cfg\nfrom siamrpnpp.utils.bbox import cxy_wh_2_rect\nfrom siamrpnpp.tracker.siamrpn_tracker import SiamRPNTracker\n\n\nclass SiamMaskTracker(SiamRPNTracker):\n def __init__(self, model):\n super(SiamMaskTracker, self).__init__(model)\n assert hasattr(self.model, 'mask_head'), \\\n \"SiamMaskTracker must have mask_head\"\n assert hasattr(self.model, 'refine_head'), \\\n \"SiamMaskTracker must have refine_head\"\n\n def _crop_back(self, image, bbox, out_sz, padding=0):\n a = (out_sz[0] - 1) / bbox[2]\n b = (out_sz[1] - 1) / bbox[3]\n c = -a * bbox[0]\n d = -b * bbox[1]\n mapping = np.array([[a, 0, c],\n [0, b, d]]).astype(np.float)\n crop = cv2.warpAffine(image, mapping, (out_sz[0], out_sz[1]),\n flags=cv2.INTER_LINEAR,\n borderMode=cv2.BORDER_CONSTANT,\n borderValue=padding)\n return crop\n\n def _mask_post_processing(self, mask):\n target_mask = (mask > cfg.TRACK.MASK_THERSHOLD)\n target_mask = target_mask.astype(np.uint8)\n if cv2.__version__[-5] == '4':\n contours, _ = cv2.findContours(target_mask,\n cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_NONE)\n else:\n _, contours, _ = cv2.findContours(target_mask,\n cv2.RETR_EXTERNAL,\n cv2.CHAIN_APPROX_NONE)\n cnt_area = [cv2.contourArea(cnt) for cnt in contours]\n if len(contours) != 0 and np.max(cnt_area) > 100:\n contour = contours[np.argmax(cnt_area)]\n polygon = contour.reshape(-1, 2)\n prbox = cv2.boxPoints(cv2.minAreaRect(polygon))\n rbox_in_img = prbox\n else: # empty mask\n location = cxy_wh_2_rect(self.center_pos, self.size)\n rbox_in_img = np.array([[location[0], location[1]],\n [location[0] + location[2], location[1]],\n [location[0] + location[2], location[1] + location[3]],\n [location[0], location[1] + location[3]]])\n return rbox_in_img\n\n def track(self, img):\n \"\"\"\n args:\n img(np.ndarray): BGR image\n return:\n bbox(list):[x, y, width, height]\n \"\"\"\n w_z = self.size[0] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n h_z = self.size[1] + cfg.TRACK.CONTEXT_AMOUNT * np.sum(self.size)\n s_z = np.sqrt(w_z * h_z)\n scale_z = cfg.TRACK.EXEMPLAR_SIZE / s_z\n s_x = s_z * (cfg.TRACK.INSTANCE_SIZE / cfg.TRACK.EXEMPLAR_SIZE)\n s_x = round(s_x)\n\n x_crop = self.get_subwindow(img,\n self.center_pos,\n cfg.TRACK.INSTANCE_SIZE,\n s_x,\n self.channel_average)\n crop_box = [self.center_pos[0] - s_x / 2,\n self.center_pos[1] - s_x / 2,\n s_x,\n s_x]\n\n outputs = self.model.track(x_crop)\n score = self._convert_score(outputs['cls'])\n pred_bbox = self._convert_bbox(outputs['loc'], self.anchors)\n\n def change(r):\n return np.maximum(r, 1. / r)\n\n def sz(w, h):\n pad = (w + h) * 0.5\n return np.sqrt((w + pad) * (h + pad))\n\n # scale penalty\n s_c = change(sz(pred_bbox[2, :], pred_bbox[3, :]) /\n (sz(self.size[0]*scale_z, self.size[1]*scale_z)))\n # aspect ratio penalty\n r_c = change((self.size[0] / self.size[1]) /\n (pred_bbox[2, :] / pred_bbox[3, :]))\n penalty = np.exp(-(r_c * s_c - 1) * cfg.TRACK.PENALTY_K)\n pscore = penalty * score\n\n # window penalty\n pscore = pscore * (1 - cfg.TRACK.WINDOW_INFLUENCE) + \\\n self.window * cfg.TRACK.WINDOW_INFLUENCE\n best_idx = np.argmax(pscore)\n\n bbox = pred_bbox[:, best_idx] / scale_z\n lr = penalty[best_idx] * score[best_idx] * cfg.TRACK.LR\n\n cx = bbox[0] + self.center_pos[0]\n cy = bbox[1] + self.center_pos[1]\n\n # smooth bbox\n width = self.size[0] * (1 - lr) + bbox[2] * lr\n height = self.size[1] * (1 - lr) + bbox[3] * lr\n\n # clip boundary\n cx, cy, width, height = self._bbox_clip(cx, cy,\n width, height, img.shape[:2])\n\n # udpate state\n self.center_pos = np.array([cx, cy])\n self.size = np.array([width, height])\n\n bbox = [cx - width / 2,\n cy - height / 2,\n width,\n height]\n best_score = score[best_idx]\n\n # processing mask\n pos = np.unravel_index(best_idx, (5, self.score_size, self.score_size))\n delta_x, delta_y = pos[2], pos[1]\n\n mask = self.model.mask_refine((delta_y, delta_x)).sigmoid().squeeze()\n out_size = cfg.TRACK.MASK_OUTPUT_SIZE\n mask = mask.view(out_size, out_size).cpu().data.numpy()\n\n s = crop_box[2] / cfg.TRACK.INSTANCE_SIZE\n base_size = cfg.TRACK.BASE_SIZE\n stride = cfg.ANCHOR.STRIDE\n sub_box = [crop_box[0] + (delta_x - base_size/2) * stride * s,\n crop_box[1] + (delta_y - base_size/2) * stride * s,\n s * cfg.TRACK.EXEMPLAR_SIZE,\n s * cfg.TRACK.EXEMPLAR_SIZE]\n s = out_size / sub_box[2]\n\n im_h, im_w = img.shape[:2]\n back_box = [-sub_box[0] * s, -sub_box[1] * s, im_w*s, im_h*s]\n mask_in_img = self._crop_back(mask, back_box, (im_w, im_h))\n polygon = self._mask_post_processing(mask_in_img)\n polygon = polygon.flatten().tolist()\n return {\n 'bbox': bbox,\n 'best_score': best_score,\n 'mask': mask_in_img,\n 'polygon': polygon,\n }\n"
] |
[
[
"numpy.maximum",
"numpy.sqrt",
"numpy.max",
"numpy.argmax",
"numpy.exp",
"numpy.array",
"numpy.unravel_index",
"numpy.sum"
]
] |
sharnesun/cgrowth_utils
|
[
"24552f02461ab7d9e903a6990c853dd907864053"
] |
[
"cgrowth_utils/mle.py"
] |
[
"import numpy as np\nimport scipy.stats as st\nimport scipy.optimize\nimport warnings\nimport pandas as pd\n\n\ndef log_like_iid_gamma(params, n):\n \"\"\"Log likelihood for i.i.d. Gamma measurements, parametrized\n by alpha, b=1/beta.\"\"\"\n alpha, b = params\n\n if alpha <= 0 or b <= 0:\n return -np.inf\n\n return np.sum(st.gamma.logpdf(n, alpha, scale=1/b))\n\ndef log_like_iid_succ_mi_poisson(params, n):\n \"\"\"Log likelihood for i.i.d. successive microtubule poisson measurements,\n parametrized by beta1, beta2.\"\"\"\n b1, b2 = params\n\n # Handling troubling edge cases for beta1 and beta2\n if b1 <= 0 or b2 <= 0:\n return -np.inf\n\n if b2 <= b1:\n return -np.inf\n\n if abs(b1 - b2) < 1e-5:\n return np.sum(log_like_iid_gamma([2, 1/b1], n))\n\n # Using the properties of log, we have split off beta1 * beta2/(beta2 - beta1)\n log_like = (np.log(b1 * b2) - np.log(b2 - b1)) * len(n)\n\n # We pulled out an e^ (-beta1 * t) and this is the sum we have for the rest of our PDF\n logs = [-b1 * t + np.log(1 - np.exp((b1 - b2) * t)) for t in n]\n log_like += sum(logs)\n return log_like\n\ndef mle_iid_succ_mi_poisson(n, init_params=[1,2]):\n return mle_iid(n, log_like_iid_succ_mi_poisson, init_params)\n\ndef mle_iid(n, log_like_fun=log_like_iid_gamma, init_params=[3, 3]):\n \"\"\"Perform maximum likelihood estimates for parameters for i.i.d.\n with specified log likelihood function and initial parameters\"\"\"\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n\n res = scipy.optimize.minimize(\n fun=lambda params, n: -log_like_fun(params, n),\n x0=np.array(init_params),\n args=(n,),\n method='Powell'\n )\n\n if res.success:\n return res.x\n else:\n raise RuntimeError('Convergence failed with message', res.message)\n"
] |
[
[
"numpy.exp",
"numpy.log",
"numpy.array",
"scipy.stats.gamma.logpdf"
]
] |
RoboCupULaval/StrategyAI
|
[
"ccddde144f2c0a67113d2e5ffe7c75ed9d4a3d19"
] |
[
"ai/Algorithm/evaluation_module.py"
] |
[
"# Under MIT License, see LICENSE.txt\nimport logging\nfrom typing import List\n\nimport numpy as np\n\nfrom Util.geometry import Line, angle_between_three_points, perpendicular, wrap_to_pi, closest_point_on_line, \\\n normalize, intersection_between_lines\nfrom Util.position import Position\nfrom Util.role import Role\nfrom Util.constant import ROBOT_RADIUS, BALL_RADIUS\nfrom ai.Algorithm.path_partitionner import Obstacle\nfrom ai.GameDomainObjects import Player\nfrom ai.states.game_state import GameState\n\n\nclass PlayerPosition(object):\n def __init__(self, player, distance):\n self.player = player\n self.distance = distance\n\n\ndef player_with_ball(min_dist_from_ball=1.2 * ROBOT_RADIUS, our_team=None):\n # Retourne le joueur qui possède la balle, NONE si balle libre\n closest_player = closest_player_to_point(GameState().ball_position, our_team)\n if closest_player.distance < min_dist_from_ball:\n return closest_player.player\n else:\n return None\n\n\ndef player_pointing_toward_point(player: Player, point: Position, angle_tolerance=90 * np.pi / 180):\n return abs((player.pose.orientation - (point - player.position).angle)) < angle_tolerance / 2\n\n\ndef object_pointing_toward_point(object_position, object_orientation, point, angle_tolerance=90 * np.pi / 180):\n return abs((object_orientation - (point - object_position).angle)) < angle_tolerance / 2\n\n\ndef player_pointing_toward_segment(player: Player, segment: Line):\n angle_bisection = angle_between_three_points(segment.p1, player.position, segment.p2) / 2\n angle_reference = angle_bisection + (segment.p2 - player.position).angle\n return abs(player.pose.orientation - angle_reference) < angle_bisection\n\n\ndef player_covered_from_goal(player: Player):\n ball_position = GameState().ball.position\n their_goal_line = GameState().field.their_goal_line.copy()\n # In Sydney, we found that our kick hit the wall around the goal quite often\n if their_goal_line.p1.y > their_goal_line.p2.y:\n their_goal_line.p1.y -= BALL_RADIUS\n their_goal_line.p2.y += BALL_RADIUS\n else:\n their_goal_line.p2.y -= BALL_RADIUS\n their_goal_line.p1.y += BALL_RADIUS\n\n shooting_angle = angle_between_three_points(their_goal_line.p1, ball_position, their_goal_line.p2)\n vec_ball_to_goal = GameState().field.their_goal - ball_position\n\n our_team = [other_player for other_player in GameState().our_team.available_players.values() if\n other_player is not player]\n enemy_team = [other_player for other_player in GameState().enemy_team.available_players.values()]\n pertinent_collisions = []\n for other_player in our_team + enemy_team:\n if object_pointing_toward_point(ball_position,\n vec_ball_to_goal.angle,\n other_player.position,\n wrap_to_pi(shooting_angle + 5 * np.pi / 180)):\n pertinent_collisions.append(Obstacle(other_player.position.array, avoid_distance=90))\n\n if not any(pertinent_collisions):\n return GameState().field.their_goal\n pertinent_collisions_positions = np.array([obs.position for obs in pertinent_collisions])\n pertinent_collisions_avoid_radius = np.array([obs.avoid_distance for obs in pertinent_collisions])\n results = []\n nb_beam = 45\n for i in range(0, nb_beam + 1): # discretisation de la ligne de but\n goal_point = their_goal_line.p1 + their_goal_line.direction * (their_goal_line.length * i / nb_beam)\n is_colliding = is_path_colliding(pertinent_collisions, pertinent_collisions_positions,\n pertinent_collisions_avoid_radius, ball_position.array, goal_point.array)\n results.append((is_colliding, goal_point))\n max_len_seg, index_end = find_max_consecutive_bool(results)\n\n if max_len_seg == 0 and index_end == 0:\n return None\n middle_idx = int(index_end - 1 - max_len_seg // 2)\n return results[middle_idx][1]\n\n\ndef find_max_consecutive_bool(results):\n count = 0\n max_len_seg = 0 # longueur du segment\n index_end = 0\n\n for i, (is_colliding, _) in enumerate(results):\n if not is_colliding:\n count += 1\n else:\n if count > max_len_seg:\n max_len_seg = count\n index_end = i\n count = 0\n if count > max_len_seg:\n max_len_seg = count\n index_end = i\n return max_len_seg, index_end\n\n\ndef is_path_colliding(obstacles, obstacles_position, obstacles_avoid_radius, start, target) -> bool:\n collisions, _ = find_collisions(obstacles, obstacles_position, obstacles_avoid_radius, start, target)\n return any(collisions)\n\n\ndef find_collisions(obstacles: List[Obstacle], obstacles_position: np.ndarray, obstacles_avoid_radius: np.ndarray,\n start: np.ndarray, target: np.ndarray):\n # fonction prend en argument des positions converties en array!\n # Position().array par exemple.\n robot_to_obstacles = obstacles_position - start\n robot_to_obstacle_norm = np.linalg.norm(robot_to_obstacles, axis=1)\n obstacles_avoid_distance = obstacles_avoid_radius\n segment_direction = (target - start) / np.linalg.norm(target - start)\n dists_from_path = np.abs(np.cross(segment_direction, robot_to_obstacles))\n is_collision = dists_from_path < obstacles_avoid_distance\n obstacles = np.array(obstacles)\n\n return obstacles[is_collision].tolist(), robot_to_obstacle_norm[is_collision]\n\n\n# noinspection PyUnusedLocal\n# TODO: Change 'our_team' to 'is_our_team'\ndef closest_players_to_point(point: Position, our_team=None):\n # Retourne une liste de tuples (player, distance) en ordre croissant de distance,\n # our_team pour obtenir une liste contenant une équipe en particulier\n list_player = []\n if our_team or our_team is None:\n for i in GameState().our_team.available_players.values():\n # les players friends\n player_distance = (i.pose.position - point).norm\n list_player.append(PlayerPosition(i, player_distance))\n if not our_team:\n for i in GameState().enemy_team.available_players.values():\n # les players ennemis\n player_distance = (i.pose.position - point).norm\n list_player.append(PlayerPosition(i, player_distance))\n list_player = sorted(list_player, key=lambda x: x.distance)\n return list_player\n\n\ndef closest_player_to_point(point: Position, our_team=None):\n # Retourne le player le plus proche,\n # our_team pour obtenir une liste contenant une équipe en particulier\n return closest_players_to_point(point, our_team)[0]\n\n\ndef closest_players_to_point_except(point: Position, except_roles=[], except_players=[]):\n closests = closest_players_to_point(point, our_team=True)\n ban_players = except_players.copy()\n ban_players += [GameState().get_player_by_role(r) for r in except_roles]\n return [player_dist for player_dist in closests if player_dist.player not in ban_players]\n\n\n# noinspection PyUnresolvedReferences\ndef is_ball_our_side():\n # Retourne TRUE si la balle est dans notre demi-terrain\n return GameState().ball_position.x > 0\n\n\n# noinspection PyUnresolvedReferences\ndef best_passing_option(passing_player, passer_can_kick_in_goal=True):\n # Retourne l'ID du player ou le but le mieux placé pour une passe, NONE si but est la meilleure possibilité\n\n score_min = float(\"inf\")\n goal = GameState().field.their_goal\n\n receiver = None\n for r, p in GameState().assigned_roles.items():\n if p != passing_player and r != Role.GOALKEEPER:\n # Calcul du score pour passeur vers receveur\n score = line_of_sight_clearance(passing_player, p.pose.position)\n\n # Calcul du score pour receveur vers but\n score += line_of_sight_clearance(p, goal)\n if score_min > score:\n score_min = score\n receiver = p\n\n if passer_can_kick_in_goal and not is_ball_our_side():\n score = (line_of_sight_clearance(passing_player, goal))\n if score_min > score:\n receiver = None\n\n # DO NOT PASS TOWARD OUR GOAL... TOO DANGEROUS\n if receiver is not None:\n ball_position = GameState().ball.position\n pass_direction = normalize(receiver.position - ball_position)\n if pass_direction.x * GameState().field.our_goal.x > 0: # Ball is going toward our side\n inter = intersection_between_lines(ball_position,\n ball_position + pass_direction,\n GameState().field.our_goal_line.p1,\n GameState().field.our_goal_line.p2)\n if abs(inter.y) < (GameState().field.goal_width / 2) * 1.5:\n receiver = None\n return receiver\n\n\ndef line_of_sight_clearance(player, target):\n # Retourne un score en fonction du dégagement de la trajectoire (plus c'est dégagé plus le score est petit)\n score = (player.pose.position - target).norm\n for p in GameState().our_team.available_players.values():\n # Obstacle : les players friends\n if not (p.id == player.id):\n if target is not p.pose.position:\n score *= trajectory_score(player.pose.position, target, p.pose.position)\n for p in GameState().enemy_team.available_players.values():\n # Obstacle : les players ennemis\n score *= trajectory_score(player.pose.position, target, p.pose.position)\n return score\n\n\n# noinspection PyUnusedLocal\ndef line_of_sight_clearance_ball(player, targets, distances=None):\n # Retourne un score en fonction du dégagement de la trajectoire de la target vers la ball excluant le robot actuel\n # (plus c'est dégagé plus le score est petit)\n ball_position = GameState().ball_position\n if distances is None:\n # la maniere full cool de calculer la norme d'un matrice verticale de vecteur horizontaux:\n scores = np.sqrt(((targets - np.array(ball_position)) *\n (targets - np.array(ball_position))).sum(axis=1))\n else:\n scores = distances\n # for j in GameState().my_team.available_players.values():\n # # Obstacle : les players friends\n # if not (j.id == player.id or j.pose.position == target):\n # score *= trajectory_score(GameState().get_ball_position(), target, j.pose.position)\n for j in GameState().enemy_team.available_players.values():\n # Obstacle : les players ennemis\n scores *= trajectory_score(GameState().ball_position, targets, j.pose.position)\n # print(scores)\n # print(scores_temp)\n return scores\n\n\ndef object_going_toward_other_object(object_1, object_2, max_angle_of_approach=25):\n if object_1.is_mobile(50): # to avoid division by zero and unstable ball_directions\n object_1_approach_angle = np.arccos(np.dot(normalize(object_2.position - object_1.position).array,\n normalize(object_1.velocity).array)) * 180 / np.pi\n return object_1_approach_angle < max_angle_of_approach\n return False\n\n\ndef ball_going_toward_player(game_state, player, max_angle_of_approach=25):\n return object_going_toward_other_object(game_state.ball, player, max_angle_of_approach=max_angle_of_approach)\n\n\ndef ball_not_going_toward_player(game_state, player):\n return not ball_going_toward_player(game_state, player)\n\n\n# noinspection PyPep8Naming\ndef trajectory_score(pointA, pointsB, obstacle):\n # Retourne un score en fonction de la distance de l'obstacle par rapport à la trajectoire AB\n proportion_max = 15 # Proportion du triangle rectancle derrière les robots obstacles\n\n # FIXME: HACK SALE, je ne comprends pas le fonctionnement de cette partie du code, analyser plus tard!\n if isinstance(pointA, Position):\n pointA = pointA.array\n if isinstance(obstacle, Position):\n obstacle = obstacle.array\n\n if isinstance(pointsB, Position):\n pointsB = pointsB.array\n\n if len(pointsB.shape) == 1:\n scores = np.array([0])\n else:\n scores = np.zeros(pointsB.shape[0])\n AB = pointsB - pointA\n AO = obstacle - pointA\n # la maniere full cool de calculer la norme d'un matrice verticale de vecteur horizontaux:\n normsAB = np.sqrt(np.transpose((AB * AB)).sum(axis=0))\n normsAC = np.divide(np.dot(AB, AO), normsAB)\n normsOC = np.sqrt(np.abs(np.linalg.norm(AO) ** 2 - normsAC ** 2))\n if scores.size == 1:\n if normsAC < 0 or normsAC > 1.1 * normsAB:\n scores = 1\n else:\n min_proportion = proportion_max if normsOC == 0 else min(normsAC / normsOC, proportion_max)\n scores = max(1, min_proportion)\n else:\n scores[normsAC < 0] = 1\n scores[normsAC > 1.1 * normsAB] = 1\n temp = np.divide(normsAC[scores == 0], normsOC[scores == 0])\n temp[temp > proportion_max] = proportion_max\n temp[temp < 1] = 1\n scores[scores == 0] = temp\n return scores\n\n\n# noinspection PyPep8Naming,PyUnresolvedReferences\ndef best_position_in_region(player, A, B):\n # Retourne la position (dans un rectangle aux points A et B) la mieux placée pour une passe\n ncounts = 5\n bottom_left = Position(min(A.x, B.x), min(A.y, B.y))\n top_right = Position(max(A.x, B.x), max(A.y, B.y))\n ball_position = GameState().ball_position\n\n positions = []\n for i in range(ncounts):\n x_point = bottom_left.x + i * (top_right.x - bottom_left.x) / (ncounts - 1)\n for j in range(ncounts):\n y_point = bottom_left.y + j * (top_right.y - bottom_left.y) / (ncounts - 1)\n positions += [Position(x_point, y_point).array]\n positions = np.stack(positions)\n # la maniere full cool de calculer la norme d'un matrice verticale de vecteur horizontaux:\n dists_from_ball_raw = np.sqrt(((positions - ball_position.array) *\n (positions - ball_position.array)).sum(axis=1))\n positions = positions[dists_from_ball_raw > 1000, :]\n dists_from_ball = dists_from_ball_raw[dists_from_ball_raw > 1000]\n scores = line_of_sight_clearance_ball(player, positions, dists_from_ball)\n our_side = GameState().field.our_goal_x\n if abs(A.x - our_side) < abs(B.x - our_side):\n x_closest_to_our_side = A.x\n else:\n x_closest_to_our_side = B.x\n\n width = abs(A.x - B.x)\n\n saturation_modifier = np.clip((positions[:, 0] - x_closest_to_our_side) / width, 0.05, 1)\n scores /= saturation_modifier\n try:\n best_score_index = np.argmin(scores)\n best_position = positions[best_score_index, :]\n except IndexError:\n best_position = Position()\n\n return best_position\n\n\ndef get_away_from_trajectory(position, start, end, min_distance):\n try:\n point = closest_point_on_line(position, start, end)\n dist = position - point\n except ZeroDivisionError:\n point = position\n dist = perpendicular(end - start) * min_distance / 2\n if dist.norm < min_distance:\n return point - dist.norm * min_distance\n else:\n return position\n"
] |
[
[
"numpy.dot",
"numpy.clip",
"numpy.linalg.norm",
"numpy.stack",
"numpy.transpose",
"numpy.argmin",
"numpy.cross",
"numpy.array",
"numpy.zeros",
"numpy.divide"
]
] |
suyashbire1/pym6
|
[
"8fe9930eb340898b242e1254309751b230d1bdd5"
] |
[
"pym6/Variable.py"
] |
[
"import numpy as np\nfrom netCDF4 import Dataset as dset, MFDataset as mfdset\nfrom functools import partial\nimport copy\nfrom .Plotter import plotter, rhotoz\n\nclass GridNdarray(np.ndarray):\n \"\"\"A class to hold a grid-located variable.\"\"\"\n def __new__(cls,input_array,loc):\n obj = input_array.view(cls)\n obj.loc = loc\n return obj\n\n def __array_finalize__(self, obj):\n if obj is None: return\n self.loc = getattr(obj, 'loc', None)\n\n def __array_wrap__(self, out_arr, context=None):\n return np.ndarray.__array_wrap__(self, out_arr, context)\n\nclass GridVariable():\n\n \"\"\"A class to hold a variable.\"\"\"\n def __init__(self,var,domain,loc,*fhl,**kwargs):\n for fh in fhl:\n try:\n self._v = fh.variables[var]\n except KeyError:\n pass\n else:\n self._name = kwargs.get('name',var)\n self._units = kwargs.get('units',None)\n self._math = kwargs.get('math',None)\n self.var = var\n self.dom = domain\n self.loc = loc\n self.plot_loc = kwargs.get('plot_loc',self.loc)[0]\n self._plot_slice = self.dom.slices[self.plot_loc].copy()\n self.implement_syntactic_sugar_for_plot_slice()\n self.Time = fh.variables['Time'][:]\n self.dom.dt = np.diff(self.Time[:2])*3600\n if 'average_DT' in fh.variables.keys():\n average_DT = fh.variables['average_DT'][:]\n average_DT = average_DT[:,np.newaxis,np.newaxis,np.newaxis]\n self.average_DT = average_DT\n self._htol = kwargs.get('htol',1e-3)\n if 'zi' in fh.variables.keys():\n self.dom.Interface = fh.variables['zi'][:]\n break\n\n self._divisor = kwargs.get('divisor',None)\n if self._divisor:\n for fh in fhl:\n try:\n self._div = fh.variables[self._divisor]\n except KeyError:\n pass\n else:\n break\n\n @property\n def shape(self):\n return self.values.shape if hasattr(self,'values') else None\n\n def __add__(self,other):\n if hasattr(other,'values') and self.values.loc == other.values.loc:\n new_variable = copy.copy(self)\n new_variable.values = self.values + other.values\n return new_variable\n elif hasattr(other,'loc') and self.values.loc == other.loc:\n new_variable = copy.copy(self)\n new_variable.values = self.values + other\n return new_variable\n else:\n new_variable = copy.copy(self)\n new_variable.values = self.values + other\n return new_variable\n\n def __sub__(self,other):\n if hasattr(other,'values') and self.values.loc == other.values.loc:\n new_variable = copy.copy(self)\n new_variable.values = self.values - other.values\n return new_variable\n elif hasattr(other,'loc') and self.values.loc == other.loc:\n new_variable = copy.copy(self)\n new_variable.values = self.values - other\n return new_variable\n else:\n new_variable = copy.copy(self)\n new_variable.values = self.values - other\n return new_variable\n\n def __mul__(self,other):\n if hasattr(other,'values') and self.values.loc == other.values.loc:\n new_variable = copy.copy(self)\n new_variable.values = self.values * other.values\n return new_variable\n elif hasattr(other,'loc') and self.values.loc == other.loc:\n new_variable = copy.copy(self)\n new_variable.values = self.values * other\n return new_variable\n else:\n new_variable = copy.copy(self)\n new_variable.values = self.values * other\n return new_variable\n\n def __div__(self,other):\n if hasattr(other,'values') and self.values.loc == other.values.loc:\n new_variable = copy.copy(self)\n new_variable.values = self.values / other.values\n return new_variable\n elif hasattr(other,'loc') and self.values.loc == other.loc:\n new_variable = copy.copy(self)\n new_variable.values = self.values / other\n return new_variable\n else:\n new_variable = copy.copy(self)\n new_variable.values = self.values / other\n return new_variable\n\n def __neg__(self):\n new_variable = copy.copy(self)\n new_variable.values = self.values*-1\n return new_variable\n\n @property\n def name(self):\n return self._name\n\n @name.setter\n def name(self,name):\n assert isinstance(name,str)\n self._name = name\n\n @property\n def math(self):\n return self._math\n\n @math.setter\n def math(self,math):\n assert isinstance(math,str)\n self._math = math\n\n @property\n def units(self):\n return self._units\n\n @units.setter\n def units(self,units):\n assert isinstance(units,str)\n self._units = units\n\n @property\n def plot_slice(self):\n return self._plot_slice\n\n @plot_slice.setter\n def plot_slice(self,operation_string):\n axis,limit,operation = list(operation_string)\n\n axes = ['t','l','y','x']\n limits = ['s','e']\n operations = { 'm': -1,\n 'p': +1 }\n self._plot_slice[axes.index(axis)][limits.index(limit)] += operations[operation]\n\n def plot_slice_modifier(self,string):\n self.plot_slice = string\n return self\n\n def implement_syntactic_sugar_for_plot_slice(self):\n axes = ['t','l','y','x']\n limits = ['s','e']\n operations = ['m','p']\n for axis in axes:\n for limit in limits:\n for op in operations:\n string = axis+limit+op\n setattr(self,string,partial(self.plot_slice_modifier,string))\n\n def extend_halos(self,array,axis,boundary_index,**kwargs):\n method = kwargs.get('method')\n if method == 'vorticity':\n slip = kwargs.get('slip',False)\n slip_multiplyer = 1 if slip else -1\n array_extendor = slip_multiplyer*array.take([boundary_index],axis=axis)\n elif method == 'mirror':\n array_extendor = array.take([boundary_index],axis=axis)\n elif method == 'zeros':\n array_extendor = np.zeros(array.take([boundary_index],axis=axis).shape)\n elif method == 'symmetric':\n select_index = 1 if boundary_index == 0 else -2\n array_extendor = array.take([select_index],axis=axis)\n\n if boundary_index == 0:\n array1 = array_extendor\n array2 = array\n else:\n array1 = array\n array2 = array_extendor\n array = np.append(array1,array2,axis=axis)\n return array\n\n def read_array(self,extend_kwargs={},**kwargs):\n if np.any(self._plot_slice[:,0]<0):\n plot_slice_temp = self._plot_slice.copy()\n for slice_index in np.nditer(plot_slice_temp[:,0],\n op_flags=['readwrite']):\n if slice_index < 0:\n slice_index[...] = 0\n self._slice = self._slice_array_to_slice(plot_slice_temp)\n else:\n self._slice = self._slice_array_to_slice(self._plot_slice)\n out_array = self._v[self._slice]\n\n filled = kwargs.get('filled',np.nan)\n if np.ma.isMaskedArray(out_array):\n out_array = out_array.filled(filled)\n\n set_min_value = kwargs.get('set_min_value',False)\n if set_min_value:\n out_array[out_array<self._htol] = filled\n\n tmean = kwargs.get('tmean',True)\n if tmean:\n dt = self.average_DT\n out_array = np.apply_over_axes(np.sum,out_array*dt,0)/np.sum(dt)\n self._plot_slice[0,1] = 1\n\n if self._divisor:\n divisor = self._div[self._slice]\n if np.ma.isMaskedArray(divisor):\n divisor = divisor.filled(filled)\n if tmean:\n dt = self.average_DT\n divisor = np.apply_over_axes(np.sum,divisor*dt,0)/np.sum(dt)\n divisor[divisor<self._htol] = np.nan\n out_array /= divisor\n\n divide_by_dx = kwargs.get('divide_by_dx',False)\n if divide_by_dx:\n out_array /= self.dom.dxCv[self._slice[2:]]\n\n divide_by_dy = kwargs.get('divide_by_dy',False)\n if divide_by_dy:\n out_array /= self.dom.dyCu[self._slice[2:]]\n\n divide_by_db = kwargs.get('divide_by_db',False)\n if divide_by_db:\n out_array /= self.dom.db\n\n if self._plot_slice[2,0] < 0:\n out_array = self.extend_halos(out_array,axis=2,\n boundary_index=0,**extend_kwargs)\n if self._plot_slice[2,1] > self.dom.total_ylen:\n out_array = self.extend_halos(out_array,axis=2,\n boundary_index=-1,**extend_kwargs)\n if self._plot_slice[3,0] < 0:\n out_array = self.extend_halos(out_array,axis=3,\n boundary_index=0,**extend_kwargs)\n if self._plot_slice[3,1] > self.dom.total_xlen:\n out_array = self.extend_halos(out_array,axis=3,\n boundary_index=-1,**extend_kwargs)\n out_array = GridNdarray(out_array,self.loc)\n self.values = out_array\n return self\n\n def _modify_slice(self,axis,ns=0,ne=0):\n out_slice = self._plot_slice.copy()\n out_slice[axis,0] += ns\n out_slice[axis,1] += ne\n return out_slice\n\n @staticmethod\n def _slice_array_to_slice(slice_array):\n \"\"\"Creates a slice object from a slice array\"\"\"\n Slice = np.s_[ slice_array[0,0]:slice_array[0,1]:slice_array[0,2],\n slice_array[1,0]:slice_array[1,1]:slice_array[1,2],\n slice_array[2,0]:slice_array[2,1]:slice_array[2,2],\n slice_array[3,0]:slice_array[3,1]:slice_array[3,2] ]\n return Slice\n\n def o1diff(self,axis):\n possible_hlocs = dict(u = ['u','u','q','h'],\n v = ['v','v','h','q'],\n h = ['h','h','v','u'],\n q = ['q','q','u','v'])\n possible_vlocs = dict(l = ['l','i','l','l'],\n i = ['i','l','i','i'])\n\n out_array = np.diff(self.values,n=1,axis=axis)\n out_array.loc = ( possible_hlocs[self.values.loc[0]][axis]\n + possible_vlocs[self.values.loc[1]][axis] )\n self.values = out_array\n return self\n\n\n def ddx(self,axis):\n possible_divisors = dict(u = [self.dom.dt, self.dom.db,\n self.dom.dyBu, self.dom.dxT],\n v = [self.dom.dt, self.dom.db,\n self.dom.dyT, self.dom.dxBu],\n h = [self.dom.dt, self.dom.db,\n self.dom.dyCv, self.dom.dxCu],\n q = [self.dom.dt, self.dom.db,\n self.dom.dyCu, self.dom.dxCv])\n possible_ns = dict(u = [0,0,0,1],\n v = [0,0,1,0],\n h = [0,0,0,0],\n q = [0,0,-1,-1])\n possible_ne = dict(u = [0,0,-1,0],\n v = [0,0,0,-1],\n h = [0,0,-1,-1],\n q = [0,0,0,0])\n if axis == 1:\n divisor = possible_divisors[self.values.loc[0]][axis]\n if hasattr(self,'atz') and self.atz:\n divisor = self.dz\n else:\n ns = possible_ns[self.values.loc[0]][axis]\n ne = possible_ne[self.values.loc[0]][axis]\n slice_array = self._modify_slice(axis,ns,ne)\n self._plot_slice = slice_array\n self._slice = self._slice_array_to_slice(slice_array)\n divisor = possible_divisors[self.values.loc[0]][axis][self._slice[2:]]\n extend_kwargs = {'method':'mirror'}\n if self._plot_slice[2,0] < 0:\n divisor = self.extend_halos(divisor,axis=0,\n boundary_index=0,**extend_kwargs)\n if self._plot_slice[2,1] > self.dom.total_ylen:\n divisor = self.extend_halos(divisor,axis=0,\n boundary_index=-1,**extend_kwargs)\n if self._plot_slice[3,0] < 0:\n divisor = self.extend_halos(divisor,axis=1,\n boundary_index=0,**extend_kwargs)\n if self._plot_slice[3,1] > self.dom.total_xlen:\n divisor = self.extend_halos(divisor,axis=1,\n boundary_index=-1,**extend_kwargs)\n\n ddx = self.o1diff(axis).values/divisor\n self.values = ddx\n return self\n\n def move_to(self,new_loc):\n possible_hlocs = dict(u = ['q','h'],\n v = ['h','q'],\n h = ['v','u'],\n q = ['u','v'])\n possible_ns = dict(u = [0,0,0,1],\n v = [0,0,1,0],\n h = [0,0,0,0],\n q = [0,0,-1,-1])\n possible_ne = dict(u = [0,-1,-1,0],\n v = [0,-1,0,-1],\n h = [0,-1,-1,-1],\n q = [0,-1,0,0])\n loc = self.values.loc\n if new_loc[0] in possible_hlocs[loc[0]]:\n axis = possible_hlocs[loc[0]].index(new_loc[0])+2\n elif new_loc[1] is not loc[1]:\n axis = 1\n ns = possible_ns[loc[0]][axis]\n ne = possible_ne[loc[0]][axis]\n slice_array = self._modify_slice(axis,ns,ne)\n self._plot_slice = slice_array\n self._slice = self._slice_array_to_slice(slice_array)\n out_array = 0.5*( np.take(self.values,range(self.values.shape[axis]-1),axis=axis)\n + np.take(self.values,range(1,self.values.shape[axis]),axis=axis) )\n out_array.loc = new_loc\n self.values = out_array\n return self\n\n plot = plotter\n\n def toz(self,z,**kwargs):\n self.z = np.array(z)\n if self.z.size > 1:\n self.dz = np.diff(z)[0]\n values = self.values\n rho = kwargs.get('rho',False)\n if rho:\n valuesz = rhotoz(self.dom.Layer,z,self.values,**kwargs)\n valuesz = GridNdarray(valuesz,self.values.loc[0]+'l')\n else:\n e = kwargs.get('e')\n kwargs.pop('e')\n e = e.values\n valuesz = rhotoz(values,z,e,**kwargs)\n valuesz = GridNdarray(valuesz,self.values.loc)\n self.values = valuesz\n self.atz = True\n return self\n"
] |
[
[
"numpy.ma.isMaskedArray",
"numpy.nditer",
"numpy.ndarray.__array_wrap__",
"numpy.append",
"numpy.apply_over_axes",
"numpy.diff",
"numpy.any",
"numpy.array",
"numpy.sum"
]
] |
mnucci32/heat
|
[
"dc5cfb9c96cbec9738bc0fae34572a8c75859130"
] |
[
"fem.py"
] |
[
"#!/usr/bin/python3\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib as mpl\nimport time\n\nmpl.rcParams[\"font.size\"] = 20\n\nclass node:\n def __init__(self, id, coords):\n self.id_ = id\n self.coords_ = coords\n\n def Id(self):\n return self.id_\n\n def Coordinates(self):\n return self.coords_\n\n def X(self):\n return self.coords_[0]\n\n def Y(self):\n return self.coords_[1]\n\n def Z(self):\n return self.coords_[2]\n\n def Distance(self, a):\n return np.linalg.norm(self.coords_, a.coords_)\n\n def Print(self):\n print(\"id:\", self.id_, \"coordinates:\", self.coords_)\n\nclass triangle:\n def __init__(self, id, n0, n1, n2):\n self.id_ = id\n self.connectivity_ = np.array([n0.Id(), n1.Id(), n2.Id()])\n self.r01_ = n1.Coordinates() - n0.Coordinates()\n self.r12_ = n2.Coordinates() - n1.Coordinates()\n self.r20_ = n0.Coordinates() - n2.Coordinates()\n area = 0.5 * np.cross(-self.r20_, self.r01_)\n self.area_ = np.linalg.norm(area)\n self.normal_ = area / self.area_\n self.centroid_ = (n0.Coordinates() + n1.Coordinates() + n2.Coordinates()) / 3\n self.shape_ = np.zeros((3, 3))\n self.shapeDeriv_ = np.zeros((3, 2))\n self.CalculateShapeFunctions(n0, n1, n2)\n self.weight_ = np.zeros((3, 3))\n self.weightDeriv_ = np.zeros((3, 2))\n self.CalculateWeightFunctions()\n self.massMatrix_ = np.zeros((3, 3))\n self.CalculateMassMatrix()\n self.boundaryEdge_ = [False, False, False]\n\n # calculate shape/trial functions\n def CalculateShapeFunctions(self, n0, n1, n2):\n self.shape_[0, 0] = n1.X() * n2.Y() - n2.X() * n1.Y()\n self.shape_[1, 0] = n2.X() * n0.Y() - n0.X() * n2.Y()\n self.shape_[2, 0] = n0.X() * n1.Y() - n1.X() * n0.Y()\n self.shape_[0, 1] = n1.Y() - n2.Y()\n self.shape_[1, 1] = n2.Y() - n0.Y()\n self.shape_[2, 1] = n0.Y() - n1.Y()\n self.shape_[0, 2] = n2.X() - n1.X()\n self.shape_[1, 2] = n0.X() - n2.X()\n self.shape_[2, 2] = n1.X() - n0.X()\n self.shape_ *= 0.5 / self.area_\n self.shapeDeriv_ = np.zeros_like(self.shape_)\n self.shapeDeriv_[:, 1:] = self.shape_[:, 1:]\n \n # calculate weight/test functions\n # same as shape/trial functions for Galerkin method\n def CalculateWeightFunctions(self):\n self.weight_ = self.shape_.copy()\n self.weightDeriv_ = self.shapeDeriv_.copy()\n\n # Shape vector times its transpose integrated over the element area\n def CalculateMassMatrix(self):\n self.massMatrix_ = np.ones((3, 3))\n self.massMatrix_[0, 0] = 2\n self.massMatrix_[1, 1] = 2\n self.massMatrix_[2, 2] = 2\n self.massMatrix_ *= self.area_ / 12\n\n def SetEdgeAsBoundary(self, ind):\n self.boundaryEdge_[ind] = True\n\n def Id(self):\n return self.id_\n\n def EdgeConnectivity(self):\n ec = np.zeros((3, 2))\n ec[0,:] = [self.connectivity_[1], self.connectivity_[0]]\n ec[1,:] = [self.connectivity_[2], self.connectivity_[1]]\n ec[2,:] = [self.connectivity_[0], self.connectivity_[2]]\n return ec\n\n def Connectivity(self):\n return self.connectivity_\n\n def MatrixIndices(self):\n indices = []\n for r in self.connectivity_:\n for c in self.connectivity_:\n indices.append((r, c))\n return indices\n\n def VectorIndicesEdge(self, ind):\n edgeInds = []\n if ind == 0:\n edgeInds.append(self.connectivity_[0])\n edgeInds.append(self.connectivity_[1])\n elif ind == 1:\n edgeInds.append(self.connectivity_[1])\n edgeInds.append(self.connectivity_[2])\n elif ind == 2:\n edgeInds.append(self.connectivity_[0])\n edgeInds.append(self.connectivity_[2])\n return edgeInds\n\n def MassMatrix(self):\n return self.massMatrix_\n\n def Area(self):\n return self.area_\n\n def Normal(self):\n return self.normal_\n\n def ShapeInterp(self, nd):\n vec = np.ones((3, 1))\n vec[1] = nd.X()\n vec[2] = nd.Y()\n return np.sum(self.shape_ @ vec)\n\n def ShapeDerivative(self):\n return self.shapeDeriv_\n\n def WeightDerivative(self):\n return self.weightDeriv_\n\n def Print(self):\n print(\"id:\", self.id_, \"connectivity:\", self.connectivity_)\n\ndef AssembleMatrices(numNodes, elems):\n K = np.zeros((numNodes, numNodes))\n M = np.zeros((numNodes, numNodes))\n for elem in elems:\n elemK = elem.WeightDerivative() @ np.transpose(elem.ShapeDerivative())\n elemK *= elem.Area()\n elemK = elemK.flatten(\"C\")\n elemM = elem.MassMatrix()\n elemM = elemM.flatten(\"C\")\n indices = elem.MatrixIndices()\n for ii in range(len(indices)):\n K[indices[ii]] += elemK[ii]\n M[indices[ii]] += elemM[ii]\n return K, M\n\ndef AssignNeumannBCs(rhs, elems, qdot, inds):\n edgeFactor = 0.5 # 2 nodes per edge\n for elem in elems:\n if elem.boundaryEdge_[0]:\n length = np.linalg.norm(elem.r01_)\n edgeIndices = elem.VectorIndicesEdge(0)\n # if all edge indices are neumann indices, apply BC\n if all(index in inds for index in edgeIndices):\n for ii in edgeIndices:\n rhs[ii] += edgeFactor * qdot * length\n if elem.boundaryEdge_[1]:\n length = np.linalg.norm(elem.r12_)\n edgeIndices = elem.VectorIndicesEdge(1)\n # if all edge indices are neumann indices, apply BC\n if all(index in inds for index in edgeIndices):\n for ii in edgeIndices:\n rhs[ii] += edgeFactor * qdot * length\n if elem.boundaryEdge_[2]:\n length = np.linalg.norm(elem.r20_)\n edgeIndices = elem.VectorIndicesEdge(2)\n # if all edge indices are neumann indices, apply BC\n if all(index in inds for index in edgeIndices):\n for ii in edgeIndices:\n rhs[ii] += edgeFactor * qdot * length\n return rhs\n\ndef AssignDirichletBCs(Morig, rhs, inds):\n M = Morig.copy()\n # assigned dT for all Dirichlet BCs\n dT = 0.0\n for jj in inds:\n for ii in range(M.shape[0]):\n rhs[ii] -= M[ii, jj] * dT\n M[:, jj] = 0.0\n M[jj, :] = 0.0\n M[jj, jj] = 1.0\n rhs[jj] = dT\n return M, rhs"
] |
[
[
"numpy.linalg.norm",
"numpy.ones",
"numpy.zeros_like",
"numpy.cross",
"numpy.zeros",
"numpy.sum"
]
] |
abhishekgaikwad2006/data-av
|
[
"23cbe8ecc76d7e65327b68b981dc8d32c8f6f179"
] |
[
"code.py"
] |
[
"import pandas as pd\r\nimport csv\r\nimport plotly.graph_objects as go\r\nimport plotly.express as px\r\n\r\ndf = pd.read_csv(\"data.csv\")\r\n\r\nmean = df.groupby([\"student_id\", \"level\"], as_index=False)[\"attempt\"].mean()\r\nfig = px.scatter(mean, x=\"student_id\", y=\"level\", size=\"attempt\", color=\"attempt\")\r\nfig.show()\r\n"
] |
[
[
"pandas.read_csv"
]
] |
tonyzoooo/my-portfolio
|
[
"3a87dd8685aae8a15b0751d30dac1589e46a51ef"
] |
[
"data_generator.py"
] |
[
"import pandas as pd\nimport datetime as dt\nimport numpy as np\nfrom dateutil.relativedelta import relativedelta\n\nfilepath = \"./data_sample.csv\"\n\ndef generate_dates():\n dates = []\n today = dt.date.today()\n for i in range(100):\n random_day = today - relativedelta(months=np.random.randint(0, 20))\n dates.append(random_day)\n return sorted(dates)\n\ndef generate_companies():\n company_names = [\"Yes\", \"No\", \"Maybe\"]\n companies = [company_names[np.random.randint(0, len(company_names))] for i in range(100)]\n return companies\n\ndef generate_products():\n product_names = [\"Plan A\", \"Plan B\", \"Plan C\", \"Plan X\"]\n products = [product_names[np.random.randint(0, len(product_names))] for i in range(100)]\n return products\n\ndef generate_types():\n type_names = [\"Type A\", \"Type B\", \"Type C\", \"Type X\", \"Type Y\", \"Type Z\"]\n types = [type_names[np.random.randint(0, len(type_names))] for i in range(100)]\n return types\n\ndef generate_values():\n values = [np.random.randint(0, 20000) for i in range(100)]\n return values\n\ndef generate_comments():\n comments = [\"\" for i in range(100)]\n return comments\n\ndef main():\n columns = [\"date\", \"company\", \"product\", \"type\", \"value\", \"comment\"]\n dates = generate_dates()\n companies = generate_companies()\n products = generate_products()\n types = generate_types()\n values = generate_values()\n comments = generate_comments()\n data = pd.DataFrame(list(zip(dates, companies, products, types, values, comments)), columns=columns)\n data.to_csv(filepath, index=False)\n\nif __name__ == \"__main__\":\n main()"
] |
[
[
"numpy.random.randint"
]
] |
Milad84/Regression-Analysis
|
[
"3806c63a2ce86e74dc4c562f38cc299a0a5172c4"
] |
[
"04_Simple Linear Regression with scikit-learn on Boston Housing sample data.py"
] |
[
"#-------------------------------------------------------------------------------\n# Name: module1\n# Purpose:\n#\n# Author: milad\n#\n# Created: 01/01/2021\n# Copyright: (c) milad 2021\n# Licence: <your licence>\n#-------------------------------------------------------------------------------\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn import datasets\nboston = datasets.load_boston()\nX_train = boston['data']\ny_train = boston['target']\n\nfrom sklearn.linear_model import LinearRegression\nsklearn_model = LinearRegression()\nsklearn_model.fit(X_train, y_train);\n\nsklearn_predictions = sklearn_model.predict(X_train)\nfig, ax = plt.subplots()\nsns.scatterplot(y_train, sklearn_predictions)\nax.set_xlabel(r'$y$', size = 16)\nax.set_ylabel(r'$\\hat{y}$', rotation = 0, size = 16, labelpad = 15)\nax.set_title(r'$y$ vs. $\\hat{y}$', size = 20, pad = 10)\nsns.despine()\n\npredictors = boston.feature_names\nbeta_hats = sklearn_model.coef_\nprint('\\n'.join([f'{predictors[i]}: {round(beta_hats[i], 3)}' for i in range(3)]))\n\n"
] |
[
[
"matplotlib.pyplot.subplots",
"sklearn.linear_model.LinearRegression",
"sklearn.datasets.load_boston"
]
] |
RobEn-AAST/image-quality-assessment
|
[
"4b5a0079c783faaa5b186a636f1214fe1651f496"
] |
[
"src/handlers/data_generator.py"
] |
[
"\nimport os\nimport numpy as np\nimport tensorflow as tf\nfrom utils import utils\n\n\nclass TrainDataGenerator(tf.keras.utils.Sequence):\n '''inherits from Keras Sequence base object, allows to use multiprocessing in .fit_generator'''\n def __init__(self, samples, img_dir, batch_size, n_classes, basenet_preprocess, img_format,\n img_load_dims=(256, 256), img_crop_dims=(224, 224), shuffle=True):\n self.samples = samples\n self.img_dir = img_dir\n self.batch_size = batch_size\n self.n_classes = n_classes\n self.basenet_preprocess = basenet_preprocess # Keras basenet specific preprocessing function\n self.img_load_dims = img_load_dims # dimensions that images get resized into when loaded\n self.img_crop_dims = img_crop_dims # dimensions that images get randomly cropped to\n self.shuffle = shuffle\n self.img_format = img_format\n self.on_epoch_end() # call ensures that samples are shuffled in first epoch if shuffle is set to True\n\n def __len__(self):\n return int(np.ceil(len(self.samples) / self.batch_size)) # number of batches per epoch\n\n def __getitem__(self, index):\n batch_indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # get batch indexes\n batch_samples = [self.samples[i] for i in batch_indexes] # get batch samples\n X, y = self.__data_generator(batch_samples)\n return X, y\n\n def on_epoch_end(self):\n self.indexes = np.arange(len(self.samples))\n if self.shuffle is True:\n np.random.shuffle(self.indexes)\n\n def __data_generator(self, batch_samples):\n # initialize images and labels tensors for faster processing\n X = np.empty((len(batch_samples), *self.img_crop_dims, 3))\n y = np.empty((len(batch_samples), self.n_classes))\n\n for i, sample in enumerate(batch_samples):\n # load and randomly augment image\n img_file = os.path.join(self.img_dir, '{}.{}'.format(sample['image_id'], self.img_format))\n img = utils.load_image(img_file, self.img_load_dims)\n if img is not None:\n img = utils.random_crop(img, self.img_crop_dims)\n img = utils.random_horizontal_flip(img)\n X[i, ] = img\n\n # normalize labels\n y[i, ] = utils.normalize_labels(sample['label'])\n\n # apply basenet specific preprocessing\n # input is 4D numpy array of RGB values within [0, 255]\n X = self.basenet_preprocess(X)\n\n return X, y\n\n\nclass TestDataGenerator(tf.keras.utils.Sequence):\n '''inherits from Keras Sequence base object, allows to use multiprocessing in .fit_generator'''\n def __init__(self, samples, img_dir, batch_size, n_classes, basenet_preprocess, img_format,\n img_load_dims=(224, 224)):\n self.samples = samples\n self.img_dir = img_dir\n self.batch_size = batch_size\n self.n_classes = n_classes\n self.basenet_preprocess = basenet_preprocess # Keras basenet specific preprocessing function\n self.img_load_dims = img_load_dims # dimensions that images get resized into when loaded\n self.img_format = img_format\n self.on_epoch_end() # call ensures that samples are shuffled in first epoch if shuffle is set to True\n\n def __len__(self):\n return int(np.ceil(len(self.samples) / self.batch_size)) # number of batches per epoch\n\n def __getitem__(self, index):\n batch_indexes = self.indexes[index*self.batch_size:(index+1)*self.batch_size] # get batch indexes\n batch_samples = [self.samples[i] for i in batch_indexes] # get batch samples\n X, y = self.__data_generator(batch_samples)\n return X, y\n\n def on_epoch_end(self):\n self.indexes = np.arange(len(self.samples))\n\n def __data_generator(self, batch_samples):\n # initialize images and labels tensors for faster processing\n X = np.empty((len(batch_samples), *self.img_load_dims, 3))\n y = np.empty((len(batch_samples), self.n_classes))\n\n for i, sample in enumerate(batch_samples):\n # load and randomly augment image\n img_file = os.path.join(self.img_dir, '{}.{}'.format(sample['image_id'], self.img_format))\n img = utils.load_image(img_file, self.img_load_dims)\n if img is not None:\n X[i, ] = img\n\n # normalize labels\n if sample.get('label') is not None:\n y[i, ] = utils.normalize_labels(sample['label'])\n\n # apply basenet specific preprocessing\n # input is 4D numpy array of RGB values within [0, 255]\n X = self.basenet_preprocess(X)\n\n return X, y\n"
] |
[
[
"numpy.random.shuffle"
]
] |
houtanb/dash-docs
|
[
"daf5f555117ff5ba53d7d5161c5f08e8c270cad9"
] |
[
"dash_docs/chapters/getting_started/examples/getting_started_table.py"
] |
[
"# Run this app with `python app.py` and\n# visit http://127.0.0.1:8050/ in your web browser.\n\nimport dash\nimport dash_html_components as html\nimport pandas as pd\n\ndf = pd.read_csv('https://gist.githubusercontent.com/chriddyp/c78bf172206ce24f77d6363a2d754b59/raw/c353e8ef842413cae56ae3920b8fd78468aa4cb2/usa-agricultural-exports-2011.csv')\n\n\ndef generate_table(dataframe, max_rows=10):\n return html.Table([\n html.Thead(\n html.Tr([html.Th(col) for col in dataframe.columns])\n ),\n html.Tbody([\n html.Tr([\n html.Td(dataframe.iloc[i][col]) for col in dataframe.columns\n ]) for i in range(min(len(dataframe), max_rows))\n ])\n ])\n\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\napp.layout = html.Div(children=[\n html.H4(children='US Agriculture Exports (2011)'),\n generate_table(df)\n])\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n"
] |
[
[
"pandas.read_csv"
]
] |
pmalhaire/dqn-from-scratch-with-tf2
|
[
"e11a4cc11c637b8a83bffcaddbbe5c76223f749f"
] |
[
"whale/utils.py"
] |
[
"import os\nfrom pathlib import Path\nimport json\nimport numpy as np\nfrom collections import OrderedDict\n\nfrom whale.card import WhaleCard as Card\n\n# Read required docs\nROOT_PATH = Path(__file__).parent\n\n# a map of trait to its index\nCARD_MAP = {'water': 0, 'wave': 1, 'double_wave': 2}\n\n# a map of abstract action to its index and a list of abstract action\nwith open(os.path.join(ROOT_PATH, 'jsondata/action_space.json'), 'r') as file:\n ACTION_SPACE = json.load(file, object_pairs_hook=OrderedDict)\n ACTION_LIST = list(ACTION_SPACE.keys())\n\n\ndef init_deck():\n ''' Generate whale deck of 108 cards\n '''\n deck = []\n\n # init wave cards\n for _ in range(1, 32):\n deck.append(Card('wave'))\n\n # init double_wave cards\n for _ in range(1, 8):\n deck.append(Card('double_wave'))\n\n # init water cards\n for _ in range(1, 40):\n deck.append(Card('water'))\n\n return deck\n\n\ndef cards2list(cards):\n ''' Get the corresponding string representation of cards\n\n Args:\n cards (list): list of WhaleCards objects\n\n Returns:\n (string): string representation of cards\n '''\n cards_list = []\n for card in cards:\n cards_list.append(card.get_str())\n return cards_list\n\n\ndef hand2dict(hand):\n ''' Get the corresponding dict representation of hand\n\n Args:\n hand (list): list of string of hand's card\n\n Returns:\n (dict): dict of hand\n '''\n hand_dict = {}\n for card in hand:\n if card not in hand_dict:\n hand_dict[card] = 1\n else:\n hand_dict[card] += 1\n return hand_dict\n\n\ndef encode_hand(hand):\n ''' Encode hand and represerve it into plane\n\n Args:\n hand (list): list of string of hand's card\n\n Returns:\n (array): 3 numpy array\n '''\n plane = [0, 0, 0]\n hand = hand2dict(hand)\n # populate each card\n for card in CARD_MAP.items():\n # print(f'card{card}')\n if hand.get(card[0]):\n plane[card[1]] = hand[card[0]]\n return plane\n\n\ndef encode_level(water_levels):\n ''' Encode level and represerve it into plane\n\n Args:\n water_levels (list) : list of water levels\n first is current player\n\n Returns:\n (array): numpy array\n '''\n return water_levels\n\n\ndef reorganize(trajectories, payoffs):\n ''' Reorganize the trajectory to make it RL friendly\n\n Args:\n trajectory (list): A list of trajectories\n payoffs (list): A list of payoffs for the players.\n Each entry corresponds to one player\n\n Returns:\n (list): A new trajectories that can be fed into RL algorithms.\n\n '''\n player_num = len(trajectories)\n new_trajectories = [[] for _ in range(player_num)]\n\n for player in range(player_num):\n for i in range(0, len(trajectories[player])-2, 2):\n if i == len(trajectories[player])-3:\n reward = payoffs[player]\n done = True\n else:\n reward, done = 0, False\n transition = trajectories[player][i:i+3].copy()\n transition.insert(2, reward)\n transition.append(done)\n\n new_trajectories[player].append(transition)\n return new_trajectories\n\n\ndef set_global_seed(seed):\n ''' Set the global see for reproducing results\n\n Args:\n seed (int): The seed\n\n Note: If using other modules with randomness, they also need to be seeded\n '''\n if seed is not None:\n import subprocess\n import sys\n\n reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])\n installed_packages = [r.decode().split('==')[0] for r in reqs.split()]\n if 'tensorflow' in installed_packages:\n import tensorflow as tf\n tf.random.set_seed(seed)\n np.random.seed(seed)\n import random\n random.seed(seed)\n"
] |
[
[
"numpy.random.seed",
"tensorflow.random.set_seed"
]
] |
openforcefield/openff-interchange
|
[
"275bd4146dd2724c5eeb2b52d3177b53371edb7c"
] |
[
"openff/interchange/interoperability_tests/internal/test_amber.py"
] |
[
"import mdtraj as md\nimport numpy as np\nimport parmed as pmd\nimport pytest\nfrom openff.toolkit.topology import Molecule\nfrom openff.toolkit.typing.engines.smirnoff import ForceField\nfrom openff.units import unit\n\nfrom openff.interchange.components.interchange import Interchange\nfrom openff.interchange.drivers import get_amber_energies, get_openmm_energies\nfrom openff.interchange.testing import _BaseTest\n\nkj_mol = unit.kilojoule / unit.mol\n\n\nclass TestAmber(_BaseTest):\n def test_inpcrd(self, parsley):\n mol = Molecule.from_smiles(10 * \"C\")\n mol.name = \"HPER\"\n mol.generate_conformers(n_conformers=1)\n\n out = Interchange.from_smirnoff(force_field=parsley, topology=mol.to_topology())\n out.box = [4, 4, 4]\n out.positions = mol.conformers[0]\n out.positions = unit.nanometer * np.round(out.positions.m_as(unit.nanometer), 5)\n\n out.to_inpcrd(\"internal.inpcrd\")\n out._to_parmed().save(\"parmed.inpcrd\")\n\n coords1 = pmd.load_file(\"internal.inpcrd\").coordinates\n coords2 = pmd.load_file(\"parmed.inpcrd\").coordinates\n\n np.testing.assert_equal(coords1, coords2)\n\n @pytest.mark.slow()\n @pytest.mark.parametrize(\n \"smiles\",\n [\n \"C\",\n \"CC\", # Adds a proper torsion term(s)\n \"C=O\", # Simplest molecule with any improper torsion\n \"OC=O\", # Simplest molecule with a multi-term torsion\n \"CCOC\", # This hits t86, which has a non-1.0 idivf\n \"C1COC(=O)O1\", # This adds an improper, i2\n ],\n )\n @pytest.mark.parametrize(\"constrained\", [True, False])\n def test_amber_energy(self, smiles, constrained):\n \"\"\"Basic test to see if the amber energy driver is functional\"\"\"\n mol = Molecule.from_smiles(smiles)\n mol.generate_conformers(n_conformers=1)\n top = mol.to_topology()\n top.mdtop = md.Topology.from_openmm(top.to_openmm())\n\n if constrained:\n sage = ForceField(\"openff-2.0.0.offxml\")\n else:\n sage = ForceField(\"openff_unconstrained-2.0.0.offxml\")\n\n off_sys = Interchange.from_smirnoff(sage, top)\n\n off_sys.box = [4, 4, 4]\n off_sys.positions = mol.conformers[0]\n\n omm_energies = get_openmm_energies(off_sys)\n amb_energies = get_amber_energies(off_sys)\n\n # MT: I _think_ some of these errors are the result of Amber reporting energies\n # to 0.001 kcal/mol, which introduces error on the order of ~0.002 kJ/mol\n # TODO: Figure out why bond and angle energies are reported differently\n # in constrained systems\n # https://github.com/openforcefield/openff-interchange/issues/323\n omm_energies.compare(\n amb_energies,\n custom_tolerances={\n \"Bond\": (0.1 if constrained else 0.001) * kj_mol,\n \"Angle\": (0.05 if constrained else 0.001) * kj_mol,\n \"Torsion\": (0.005 if constrained else 0.001) * kj_mol,\n \"vdW\": 0.02 * kj_mol,\n \"Electrostatics\": (0.5 if constrained else 0.05) * kj_mol,\n },\n )\n"
] |
[
[
"numpy.testing.assert_equal"
]
] |
billybishop21/Algo_Signals_2.0
|
[
"07541de6cdc0de0c050f7c38173ee0ded33a6d19"
] |
[
"remy_workflow/helpful_methods.py"
] |
[
"from datetime import datetime\n# from logging import info\n# from multiprocessing import Value\n# from os import symlink\nimport questionary\nimport shelve\nimport pandas as pd\nimport sqlalchemy\n# from pathlib import Path\nimport remy_workflow.finnhubIO as fh\n# from time import sleep\nimport yfinance as yf\nimport concurrent.futures\n\n\n# Create a temporary SQLite database and populate the database with content from the etf.db seed file\ndatabase_connection_string = 'sqlite:///../Resources/portfolio.db'\nshelf_path = './Resources/shelf'\nmarket_list = ['stock', 'crypto']\n\n\ndef gen_df(\n table_name,\n engine,\n):\n df = pd.read_sql_table(\n table_name,\n con=engine,\n index_col='Time',\n parse_dates=True,\n )\n return df\n\n\ndef get_username(username=None):\n if username is None:\n username = questionary.text(\n \"What is your name?\",\n qmark='',\n ).ask()\n with shelve.open(shelf_path) as sh:\n # Check to see if username exists in shelf\n if username in sh:\n message = f\"Hello, {username}!\"\n # If username does not exist, create empty dictionary\n else:\n sh[username] = {}\n message = f\"It's nice to meet you, {username}!\"\n sh.sync()\n print(message)\n\n return username\n\n\ndef choose_market():\n default_market = 'stock'\n if default_market in market_list:\n market = questionary.select(\n \"What market are you looking at?\",\n choices=market_list,\n qmark='',\n default=default_market,\n ).ask()\n else:\n market = questionary.select(\n \"What market are you looking at?\",\n choices=market_list,\n qmark='',\n ).ask()\n\n return market\n\n\ndef choose_exchange(market=None):\n default_exchange = 'COINBASE'\n if market is None:\n market = choose_market()\n if market == 'stock':\n exchange = 'US'\n if market == 'crypto':\n crypto_list = fh.crypto_exchange_list\n if default_exchange in crypto_list:\n exchange = questionary.select(\n \"What crypto exchange do you want to use?\",\n choices = sorted(fh.crypto_exchange_list),\n qmark='',\n default=default_exchange,\n ).ask()\n else:\n exchange = questionary.select(\n \"What crypto exchange do you want to use?\",\n choices = sorted(fh.crypto_exchange_list),\n qmark='',\n ).ask()\n return exchange\n\n\ndef choose_product_type(market=None, exchange=None):\n if market == None:\n market = choose_market()\n if exchange == None:\n exchange = choose_exchange(market)\n\n if market == 'crypto':\n default_base = 'USD'\n ticker_df = gen_crypto_df(exchange)\n\n base_list = sorted(ticker_df['baseCurrency'].unique())\n print(type(base_list))\n if default_base in base_list:\n print(f'found {default_base}')\n\n product_type = questionary.select(\n \"What currency do you use?\",\n choices=base_list,\n qmark='',\n default='USD',\n ).ask()\n\n else:\n product_type = questionary.select(\n \"What currency do you use?\",\n choices=base_list,\n qmark='',\n ).ask()\n\n\n if market == 'stock':\n default_type = 'Common Stock'\n stock_types = sorted(fh.stocks_df['type'].unique())\n if default_type in stock_types:\n product_type = questionary.select(\n \"What type of stock?\",\n choices=stock_types,\n qmark='',\n default=default_type,\n ).ask()\n else:\n product_type = questionary.select(\n \"What type of stock?\",\n choices=stock_types,\n qmark='',\n ).ask()\n\n return product_type\n\ndef gen_product_df(market=None, exchange=None, product_type=None):\n if market == None:\n market = choose_market()\n if exchange == None:\n exchange = choose_exchange(market)\n if product_type == None:\n product_type = choose_product_type(market, exchange)\n\n if market == 'stock':\n product_df=fh.stocks_df.loc[lambda df: df['type'] == product_type]['symbol'].reset_index(drop=True)\n\n if market == 'crypto':\n crypto_df = gen_crypto_df(exchange)\n product_df=crypto_df.loc[lambda df: df['baseCurrency'] == product_type]['displaySymbol'].reset_index(drop=True)\n\n return product_df\n\ndef gen_crypto_df(exchange=None):\n if exchange == None:\n exchange = choose_exchange()\n crypto_list = fh.get_crypto_tickers(exchange=exchange)\n df = pd.DataFrame(crypto_list)\n df['baseCurrency'] = df['displaySymbol'].apply(lambda x: x[x.find('/')+1:])\n df['quoteCurrency'] = df['displaySymbol'].apply(lambda x: x[:x.find('/')])\n \n return df\n\n\ndef get_market_info(df, market, exchange, product_type, engine):\n inspector = sqlalchemy.inspect(engine)\n table_names = inspector.get_table_names()\n if table_names:\n df = pd.read_sql_table(table_names[0], con=engine)\n print(f\"Loaded db {len(df)} items\")\n # else:\n # df = pd.DataFrame(df)\n # sleep_time = 1.0/10.0\n # print(market, type(market))\n if market == 'stock':\n time_start = datetime.now()\n # df.set_index('symbol', inplace=True)\n print(f'Found {len(df)}')\n symbol_list = list(df['symbol'])\n\n search_limit = 10\n sliced_symbol_list = symbol_list[:search_limit]\n df = get_threaded_info(sliced_symbol_list, df).copy()\n\n run_time = datetime.now() - time_start\n estimated_total_run_time = len(symbol_list) * (run_time.total_seconds()/search_limit) / 60\n print(f\"Time to run: {run_time}\\nEstimated time to run entire market: {estimated_total_run_time} minutes.\")\n return df\n\n\ndef get_product_info(symbol, market, exchange, product_type):\n print(f\"Getting info for {symbol} {market} {exchange} {product_type}\")\n if market=='stock':\n ticker = yf.Ticker(symbol)\n print(ticker.info)\n # return fh.finnhub_client.aggregate_indicator(symbol, 'D')\n return {}\n\ndef get_threaded_info(stocks, df):\n exception_count = 0\n cap_count = 0\n exception_list = []\n key_error_list = []\n with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:\n # with concurrent.futures.ThreadPoolExecutor() as executor:\n future_to_dict = {executor.submit(get_stock_info, stock): stock for stock in stocks}\n for future in concurrent.futures.as_completed(future_to_dict):\n stock = future_to_dict[future]\n try:\n info = future.result()\n\n for k, v in info.items():\n if k not in df.columns:\n df[k] = pd.NA\n try:\n df[k].loc[df['symbol'] == stock] = v\n except ValueError:\n df[k].loc[df['symbol'] == stock] = pd.NA\n except Exception as e:\n print(stock, k, v, type(e), e)\n exception_count += 1\n\n cap_count += 1\n except KeyError:\n key_error_list.append(stock)\n except Exception as exc:\n exception_count += 1\n exception_list.append(stock)\n print(f'\\n{stock} generated a {type(exc)} exception: {exc}', end='\\n')\n else:\n pass\n print(f\"\\r{stock:<6s}\", end=\"\")\n print(f'\\rDone! {cap_count} stocks, {len(key_error_list)} key errors, {exception_count} unhandled exceptions.')\n print(f'Tickers with no market cap data:\\n{key_error_list}')\n # return info_dict\n return df\n\n\ndef get_stock_info(stock):\n try:\n ticker = yf.Ticker(stock)\n except Exception as e:\n print(f\"{e}\")\n return e\n return ticker.info\n\n\ndef get_stock_market_cap(stock):\n# print(f'\\rGetting {stock} ticker...', end='')\n ticker = yf.Ticker(stock)\n return ticker.info['marketCap']\n\ndef process_ticker_info(ticker):\n print(ticker)\n stock_info = get_stock_info(ticker)\n stock_info_list = list(stock_info.items())\n product_df = pd.DataFrame(stock_info_list, columns=['Info', ticker])\n product_df = product_df.set_index(\"Info\")\n # product_df = product_df.T\n drop_rows = ['zip', 'sector', 'fullTimeEmployees', 'longBusinessSummary', 'city', 'phone', 'state', 'country', 'companyOfficers', 'website', 'maxAge', 'address1', 'address2', 'industry', 'logo_url', 'tradeable', 'fromCurrency', ] \n # print(product_df.index)\n for row in drop_rows:\n if row in product_df.index:\n product_df = product_df.drop(index=row)\n # print(product_df.head(20))\n # print(product_df.tail(20))\n\n return product_df\n\n\ndef process_ticker_hist(ticker):\n candle_df = yf.download(ticker, period=\"max\")\n print(candle_df.head())\n candle_df.rename_axis('Datetime', inplace=True)\n candle_df = candle_df[['Open', 'High', 'Low', 'Close', 'Volume']]\n return candle_df\n \ndef get_minute_candles(ticker):\n current_time = int(round(datetime.now().timestamp(),0))\n print(datetime.fromtimestamp(current_time))\n max_offset = 86400 * 10 * 365\n dt_end = current_time\n dt_start = dt_end - max_offset\n candles = fh.get_stock_candles(\n ticker, \n dt_start=dt_start, \n dt_end=dt_end, \n resolution='1'\n )\n # This is causing an error\n try:\n candle_df = pd.DataFrame(candles)\n except Exception as e:\n print(f'Error: {e} {type(e)}')\n raise e\n candle_df.rename(\n columns={\n 't': 'Datetime', \n 'c': 'Close', \n 'h': 'High', \n 'l': 'Low', \n 'o': 'Open', \n 's': 'Status', \n 'v': 'Volume',\n },\n inplace=True,\n )\n candle_df['Datetime'] = candle_df['Datetime'].apply(lambda df: datetime.fromtimestamp(df))\n candle_df.set_index('Datetime', inplace=True, drop=True)\n # print(candle_df)\n candle_df = candle_df[['Open', 'High', 'Low', 'Close', 'Volume']]\n return candle_df\n"
] |
[
[
"pandas.read_sql_table",
"pandas.DataFrame"
]
] |
spinoza-centre/prf-seeg
|
[
"ed725f0284bede5d6947a7a22cfa77f9d921368c"
] |
[
"experiment/trial.py"
] |
[
"#!/usr/bin/env python\n#-*- coding: utf-8 -*-\n\nimport math, time\nimport numpy as np\nimport pandas as pd\n\nfrom exptools2.core import Trial\nfrom psychopy.core import getTime\nfrom psychopy.visual import TextStim\nfrom psychopy import logging\n\nfrom stimuli import FixationLines\n\n# #### Windows triggering\n# try:\n# from ctypes import windll\n# win_triggering = True\n# except ImportError as error:\n# logging.warn(f'Attempted import of windll failed, {error.__class__.__name__}: {error}')\n# win_triggering = False\n\nclass BarPassTrial(Trial):\n \n def __init__(self, session, trial_nr, phase_durations, phase_names,\n parameters, timing, aperture_sequence, bg_img_sequence,\n verbose=True, draw_each_frame=False):\n \"\"\" Initializes a BarPassTrial object. \n \n Parameters\n ----------\n session : exptools Session object\n A Session object (needed for metadata)\n trial_nr: int\n Trial nr of trial\n phase_durations : array-like\n List/tuple/array with phase durations\n phase_names : array-like\n List/tuple/array with names for phases (only for logging),\n optional (if None, all are named 'stim')\n parameters : dict\n Dict of parameters that needs to be added to the log of this trial\n timing : str\n The \"units\" of the phase durations. Default is 'seconds', where we\n assume the phase-durations are in seconds. The other option is\n 'frames', where the phase-\"duration\" refers to the number of frames.\n verbose : bool\n Whether to print extra output (mostly timing info)\n \"\"\"\n super().__init__(session, trial_nr, phase_durations, phase_names,\n parameters, timing, load_next_during_phase=None, verbose=verbose, draw_each_frame=draw_each_frame)\n # print(self.parameters)\n # internalize these sequences and their expected times in the trials\n\n expected_aperture_times = self.parameters['start_time'] + np.arange(len(aperture_sequence)+1) * self.parameters['bar_refresh_time']\n expected_bg_img_times = self.parameters['start_time'] + np.arange(len(bg_img_sequence)+1) * self.parameters['bg_stim_refresh_time']\n\n self.aperture_sequence_df = pd.DataFrame(np.array([np.r_[aperture_sequence, 0], \n expected_aperture_times, \n np.zeros_like(expected_aperture_times)]).T, \n columns=['seq_index', 'expected_time', 'empirical_time'])\n self.bg_img_sequence_df = pd.DataFrame(np.array([np.r_[bg_img_sequence, 0], \n expected_bg_img_times, \n np.zeros_like(expected_bg_img_times)]).T, \n columns=['seq_index', 'expected_time', 'empirical_time'])\n\n self.aperture_masks = self.session.aperture_dict[self.parameters['bar_width']][self.parameters['bar_refresh_time']][self.parameters['bar_direction']]\n\n self.bg_display_frame = -1\n self.bar_display_frame = -1\n \n def run(self):\n\n #####################################################\n ## TRIGGER HERE\n #####################################################\n self.session.parallel_trigger(self.session.settings['design'].get('ttl_trigger_bar'))\n\n super().run() # run parent class!\n\n def draw(self):\n\n draw = False\n\n total_display_time = (getTime() - self.session.experiment_start_time)\n trial_display_time = total_display_time - self.parameters['start_time']\n bg_display_frame = math.floor(trial_display_time / self.session.settings['stimuli'].get('bg_stim_refresh_time'))\n if bg_display_frame != self.bg_display_frame:\n self.bg_display_frame = bg_display_frame\n self.bg_img_sequence_df['empirical_time'].loc[bg_display_frame] = total_display_time\n draw = True\n\n # find and fill in the binary mask\n bar_display_frame = np.min([int(trial_display_time / self.parameters['bar_refresh_time']), self.aperture_masks.shape[0]])\n if bar_display_frame != self.bar_display_frame:\n self.bar_display_frame = bar_display_frame\n self.aperture_sequence_df['empirical_time'].loc[bar_display_frame] = total_display_time\n draw = True\n\n if draw:\n if total_display_time > self.session.fix_event_times[self.session.last_fix_event]:\n self.session.last_fix_event = self.session.last_fix_event + 1\n self.session.report_fixation.setColor(-1 * self.session.report_fixation.color)\n\n # identify stimulus object, and decide whether to draw\n if math.fmod(trial_display_time, self.parameters['bar_blank_interval']) > self.parameters['bar_blank_duration']:\n which_bg_stim = self.session.image_bg_stims[int(self.bg_img_sequence_df['seq_index'].loc[bg_display_frame])]\n\n which_mask = np.min([self.aperture_sequence_df['seq_index'].loc[bar_display_frame], \n self.aperture_masks.shape[0]])\n\n mask = self.aperture_masks[int(which_mask)]\n which_bg_stim.mask = (mask * 2) - 1\n which_bg_stim.draw()\n \n self.session.fixation.draw()\n self.session.report_fixation.draw()\n self.session.win.flip()\n\n\n def get_events(self):\n events = super().get_events()\n if len(events) > 0:\n t = getTime() - self.session.experiment_start_time\n # discard early events\n if self.session.fix_event_times[0] > t:\n pass\n else:\n which_last_fix_event = np.arange(self.session.fix_event_times.shape[0])[self.session.fix_event_times < t][-1]\n self.session.fix_event_responses[which_last_fix_event][0] = t\n self.session.fix_event_responses[which_last_fix_event][2] = t - self.session.fix_event_times[which_last_fix_event]\n\nclass EmptyBarPassTrial(Trial):\n \"\"\" Simple trial with text (trial x) and fixation. \"\"\"\n\n def __init__(self, session, trial_nr, phase_durations=None, draw_each_frame=False, **kwargs):\n\n super().__init__(session, trial_nr, phase_durations, draw_each_frame=draw_each_frame, **kwargs)\n \n def draw(self):\n total_display_time = (getTime() - self.session.experiment_start_time)\n trial_display_time = total_display_time - self.parameters['start_time']\n\n if total_display_time > self.session.fix_event_times[self.session.last_fix_event]:\n self.session.last_fix_event = self.session.last_fix_event + 1\n self.session.report_fixation.setColor(-1 * self.session.report_fixation.color)\n\n self.session.fixation.draw()\n self.session.report_fixation.draw()\n self.session.win.flip()\n\n def run(self):\n\n #####################################################\n ## TRIGGER HERE\n #####################################################\n self.session.parallel_trigger(self.session.settings['design'].get('ttl_trigger_blank'))\n\n super().run() # run parent class!\n\n def get_events(self):\n events = super().get_events()\n if len(events) > 0:\n t = getTime() - self.session.experiment_start_time\n # discard early events\n if self.session.fix_event_times[0] > t:\n pass\n else:\n which_last_fix_event = np.arange(self.session.fix_event_times.shape[0])[self.session.fix_event_times < t][-1]\n self.session.fix_event_responses[which_last_fix_event][0] = t\n self.session.fix_event_responses[which_last_fix_event][2] = t - self.session.fix_event_times[which_last_fix_event]\n\nclass InstructionTrial(Trial):\n \"\"\" Simple trial with instruction text. \"\"\"\n\n def __init__(self, session, trial_nr, phase_durations=[np.inf],\n txt=None, keys=None, draw_each_frame=False, **kwargs):\n\n super().__init__(session, trial_nr, phase_durations, draw_each_frame=draw_each_frame, **kwargs)\n\n txt_height = self.session.settings['various'].get('text_height')\n txt_width = self.session.settings['various'].get('text_width')\n text_position_x = self.session.settings['various'].get('text_position_x')\n text_position_y = self.session.settings['various'].get('text_position_y')\n\n if txt is None:\n txt = '''Press any button to continue.'''\n\n self.text = TextStim(self.session.win, txt,\n height=txt_height, \n wrapWidth=txt_width, \n pos=[text_position_x, text_position_y],\n font='Songti SC',\n alignText = 'center',\n anchorHoriz = 'center',\n anchorVert = 'center')\n self.text.setSize(txt_height)\n\n self.keys = keys\n\n def draw(self):\n self.session.fixation.draw()\n self.session.report_fixation.draw()\n\n self.text.draw()\n self.session.win.flip()\n\n def get_events(self):\n events = super().get_events()\n\n if self.keys is None:\n if events:\n self.stop_phase()\n else:\n for key, t in events:\n if key in self.keys:\n self.stop_phase()\n\n\nclass DummyWaiterTrial(InstructionTrial):\n \"\"\" Simple trial with text (trial x) and fixation. \"\"\"\n\n def __init__(self, session, trial_nr, phase_durations=None,\n txt=\"Waiting for scanner triggers.\", draw_each_frame=False, **kwargs):\n\n super().__init__(session, trial_nr, phase_durations, txt, draw_each_frame=draw_each_frame, **kwargs)\n \n def draw(self):\n self.session.fixation.draw()\n if self.phase == 0:\n self.text.draw()\n else:\n self.session.report_fixation.draw()\n self.session.win.flip()\n\n def get_events(self):\n events = Trial.get_events(self)\n\n if events:\n for key, t in events:\n if key == self.session.mri_trigger:\n if self.phase == 0:\n self.stop_phase()\n self.session.win.flip()\n #####################################################\n ## TRIGGER HERE\n #####################################################\n self.session.experiment_start_time = getTime()\n self.session.parallel_trigger(self.session.settings['design'].get('ttl_trigger_start'))\n\n\nclass OutroTrial(InstructionTrial):\n \"\"\" Simple trial with only fixation cross. \"\"\"\n\n def __init__(self, session, trial_nr, phase_durations, txt='', draw_each_frame=False, **kwargs):\n\n txt = ''''''\n super().__init__(session, trial_nr, phase_durations, txt=txt, draw_each_frame=draw_each_frame, **kwargs)\n\n def get_events(self):\n events = Trial.get_events(self)\n\n if events:\n for key, t in events:\n if key == 'space':\n self.stop_phase() "
] |
[
[
"numpy.arange",
"numpy.zeros_like",
"numpy.min"
]
] |
loostrum/psrdada_filterbankdb
|
[
"efd2b9aa4e77c66758f4e41dfbecac5adac8130d"
] |
[
"test/test_dada_fildb.py"
] |
[
"import os\nimport unittest\nimport time\nimport multiprocessing as mp\n\nimport numpy as np\nfrom psrdada import Reader, Writer\n\nfrom dada_fildb import dada_fildb\nfrom dada_fildb.sigproc import SigprocFile\n\n\nclass TestDadaFildb(unittest.TestCase):\n\n def setUp(self):\n \"\"\"\n Set configuration, create filterbank files\n \"\"\"\n\n self.nbeam = 2\n self.nfreq = 384\n self.pagesize = 1024\n self.npage = 3\n\n self.dada_key = 'dada'\n self.buffer = None\n\n self.files = []\n for beam in range(self.nbeam):\n self.files.append(self.create_filterbank(beam))\n\n def create_filterbank(self, beam):\n \"\"\"\n Create a test filterbank file\n :return: path to file, pointer to file\n \"\"\"\n fname = f'test_beam{beam:02d}.fil'\n header = {'rawdatafile': fname,\n 'source_name': 'FAKE',\n 'machine_id': 15,\n 'barycentric': 0,\n 'telescope_id': 10,\n 'src_raj': 0.,\n 'src_dej': 0.,\n 'az_start': 0.,\n 'za_start': 0.,\n 'data_type': 1,\n 'fch1': 1520.,\n 'foff': -1.,\n 'nchans': 384,\n 'nbeams': self.nbeam,\n 'ibeam': beam,\n 'nbits': 8,\n 'tstart': 55000.0,\n 'tsamp': 1e-3,\n 'nifs': 1}\n\n filterbank = SigprocFile.new_file(fname, header)\n\n # add some data\n for page in range(self.npage):\n # data is increasing values in time and freq in each page, multiplied by page and beam index (1-based)\n data = (np.arange(self.pagesize)[:, None] * np.arange(self.nfreq)[None, :]\n * (beam + 1) * (page + 1)).astype(np.uint8)\n filterbank.append_spectra(data, fname)\n\n return fname, filterbank\n\n def create_ringbuffer(self):\n \"\"\"\n Create a PSRDADA ringbuffer\n :return:\n \"\"\"\n\n hdr_size = 40960\n buffer_size = self.nbeam * self.nfreq * self.pagesize\n nbuffer = 5\n nreader = 1\n\n cmd = f'dada_db -w -a {hdr_size} -b {buffer_size} -k {self.dada_key} -n {nbuffer} -r {nreader}'\n self.buffer = mp.Process(target=os.system, args=(cmd,))\n self.buffer.start()\n time.sleep(.1)\n\n def tearDown(self):\n \"\"\"\n Remove any remaining buffers and files\n \"\"\"\n try:\n self.buffer.terminate()\n except AttributeError:\n pass\n for fname, filterbank in self.files:\n try:\n filterbank.fp.close()\n os.remove(fname)\n except FileNotFoundError:\n pass\n\n def test_dada_fildb(self):\n \"\"\"\n Write filterbank to buffer and read back the header and data\n \"\"\"\n # create a buffer\n self.create_ringbuffer()\n # start dada_fildb\n dada_fildb(np.transpose(self.files)[0], self.dada_key, order='FT', pagesize=self.pagesize)\n # init reader\n reader = Reader(int(self.dada_key, 16))\n # read header\n header = reader.getHeader()\n # remove raw header\n del header['__RAW_HEADER__']\n # read data\n ind = 0\n for page in reader:\n data = np.asarray(page)\n # calculate expected sum: each point is product of time, freq, page, beam index, mod 255 (i.e. 2**nbit-1)\n expected_total = (np.arange(self.pagesize)[:, None, None] * np.arange(self.nfreq)[None, :, None]\n * np.arange(1, self.nbeam + 1)[None, None, :] * (ind + 1)).astype(np.uint8).sum()\n self.assertEqual(data.sum(), expected_total)\n ind += 1\n\n # disconnect\n reader.disconnect()\n\n\nif __name__ == '__main__':\n unittest.main()\n"
] |
[
[
"numpy.asarray",
"numpy.arange",
"numpy.transpose"
]
] |
insomnia1996/mrc_c3
|
[
"081297faa8e5909e60cd222e2ebbf2a3338a02b3"
] |
[
"test_multichoice_mrc.py"
] |
[
"from __future__ import print_function\n\nimport argparse\nimport os\nfrom glob import glob\n\nimport torch\nfrom google_albert_pytorch_modeling import AlbertConfig, AlbertForMultipleChoice\nfrom preprocess.CHID_preprocess import RawResult, get_final_predictions, write_predictions, \\\n generate_input\nfrom pytorch_modeling import ALBertConfig, ALBertForMultipleChoice\nfrom pytorch_modeling import BertConfig, BertForMultipleChoice\nfrom tools.official_tokenization import BertTokenizer\nfrom torch.utils.data import TensorDataset, DataLoader, SequentialSampler\nfrom tqdm import tqdm\n\n\ndef torch_init_model(model, init_restore_dir):\n state_dict = torch.load(init_restore_dir, map_location='cpu')\n missing_keys = []\n unexpected_keys = []\n error_msgs = []\n # copy state_dict so _load_from_state_dict can modify it\n metadata = getattr(state_dict, '_metadata', None)\n state_dict = state_dict.copy()\n if metadata is not None:\n state_dict._metadata = metadata\n\n def load(module, prefix=''):\n local_metadata = {} if metadata is None else metadata.get(prefix[:-1], {})\n\n module._load_from_state_dict(\n state_dict, prefix, local_metadata, True, missing_keys, unexpected_keys, error_msgs)\n for name, child in module._modules.items():\n if child is not None:\n load(child, prefix + name + '.')\n\n load(model, prefix='' if hasattr(model, 'bert') else 'bert.')\n\n print(\"missing keys:{}\".format(missing_keys))\n print('unexpected keys:{}'.format(unexpected_keys))\n print('error msgs:{}'.format(error_msgs))\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--gpu_ids\", default='0,1,2,3,4,5,6,7', type=str)\n parser.add_argument(\"--bert_config_file\",\n default='check_points/prev_trained_model/roberta_wwm_ext_large/bert_config.json',\n type=str,\n help=\"The config json file corresponding to the pre-trained BERT model. \"\n \"This specifies the model architecture.\")\n parser.add_argument(\"--vocab_file\", default='check_points/prev_trained_model/roberta_wwm_ext_large/vocab.txt',\n type=str,\n help=\"The vocabulary file that the BERT model was trained on.\")\n parser.add_argument(\"--init_restore_dir\",\n required=True,\n type=str,\n help=\"Initial checkpoint (usually from a pre-trained BERT model).\")\n parser.add_argument(\"--input_dir\", type=str, default='mrc_data/c3')\n parser.add_argument(\"--output_dir\", required=True, type=str,\n help=\"The output directory where the model checkpoints and predictions will be written.\")\n parser.add_argument(\"--predict_file\", type=str, default='d-test.json')\n parser.add_argument('--output_file', type=str, default='test_predictions.json')\n\n ## Other parameters\n parser.add_argument(\"--max_seq_length\", default=256, type=int,\n help=\"The maximum total input sequence length after WordPiece tokenization. Sequences \"\n \"longer than this will be truncated, and sequences shorter than this will be padded.\")\n parser.add_argument(\"--max_num_choices\", default=4, type=int,\n help=\"The maximum number of cadicate answer, shorter than this will be padded.\")\n parser.add_argument(\"--predict_batch_size\", default=16, type=int, help=\"Total batch size for predictions.\")\n parser.add_argument(\"--do_lower_case\",\n default=True,\n help=\"Whether to lower case the input text. True for uncased models, False for cased models.\")\n parser.add_argument('--fp16',\n default=False,\n action='store_true',\n help=\"Whether to use 16-bit float precision instead of 32-bit\")\n\n args = parser.parse_args()\n print(args)\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = args.gpu_ids\n\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n print(\"device: {}, 16-bits training: {}\".format(device, args.fp16))\n\n tokenizer = BertTokenizer(vocab_file=args.vocab_file, do_lower_case=args.do_lower_case)\n\n test_example_file = os.path.join(args.input_dir, 'test_examples_{}.pkl'.format(str(args.max_seq_length)))\n test_feature_file = os.path.join(args.input_dir, 'test_features_{}.pkl'.format(str(args.max_seq_length)))\n\n eval_features = generate_input(args.predict_file, None, test_example_file, test_feature_file, tokenizer,\n max_seq_length=args.max_seq_length, max_num_choices=args.max_num_choices,\n is_training=False)\n\n # Prepare model\n if 'albert' in args.bert_config_file:\n if 'google' in args.bert_config_file:\n bert_config = AlbertConfig.from_json_file(args.bert_config_file)\n model = AlbertForMultipleChoice(bert_config, num_choices=args.max_num_choices)\n else:\n bert_config = ALBertConfig.from_json_file(args.bert_config_file)\n model = ALBertForMultipleChoice(bert_config, num_choices=args.max_num_choices)\n else:\n bert_config = BertConfig.from_json_file(args.bert_config_file)\n model = BertForMultipleChoice(bert_config, num_choices=args.max_num_choices)\n model = model.to(device)\n if args.init_restore_dir.endswith('.pth') or \\\n args.init_restore_dir.endswith('.pt') or \\\n args.init_restore_dir.endswith('.bin'):\n pass\n else:\n args.init_restore_dir = glob(args.init_restore_dir + '*.pth') + \\\n glob(args.init_restore_dir + '*.pt') + \\\n glob(args.init_restore_dir + '*.bin')\n assert len(args.init_restore_dir) == 1\n args.init_restore_dir = args.init_restore_dir[0]\n torch_init_model(model, args.init_restore_dir)\n if args.fp16:\n model = model.half()\n\n print(\"***** Running predictions *****\")\n print(\"Num split examples = %d\", len(eval_features))\n print(\"Batch size = %d\", args.predict_batch_size)\n\n all_example_ids = [f.example_id for f in eval_features]\n all_tags = [f.tag for f in eval_features]\n all_input_ids = torch.tensor([f.input_ids for f in eval_features], dtype=torch.long)\n all_input_masks = torch.tensor([f.input_masks for f in eval_features], dtype=torch.long)\n all_segment_ids = torch.tensor([f.segment_ids for f in eval_features], dtype=torch.long)\n all_choice_masks = torch.tensor([f.choice_masks for f in eval_features], dtype=torch.long)\n all_example_index = torch.arange(all_input_ids.size(0), dtype=torch.long)\n eval_data = TensorDataset(all_input_ids, all_input_masks, all_segment_ids, all_choice_masks,\n all_example_index)\n # Run prediction for full data\n eval_sampler = SequentialSampler(eval_data)\n eval_dataloader = DataLoader(eval_data, sampler=eval_sampler, batch_size=args.predict_batch_size)\n\n model.eval()\n all_results = []\n print(\"Start evaluating\")\n for input_ids, input_masks, segment_ids, choice_masks, example_indices in tqdm(eval_dataloader,\n desc=\"Evaluating\",\n disable=None):\n if len(all_results) == 0:\n print('shape of input_ids: {}'.format(input_ids.shape))\n input_ids = input_ids.to(device)\n input_masks = input_masks.to(device)\n segment_ids = segment_ids.to(device)\n with torch.no_grad():\n batch_logits = model(input_ids=input_ids,\n token_type_ids=segment_ids,\n attention_mask=input_masks,\n labels=None)\n for i, example_index in enumerate(example_indices):\n logits = batch_logits[i].detach().cpu().tolist()\n eval_feature = eval_features[example_index.item()]\n unique_id = int(eval_feature.unique_id)\n all_results.append(RawResult(unique_id=unique_id,\n example_id=all_example_ids[unique_id],\n tag=all_tags[unique_id],\n logit=logits))\n else:\n print(\"prediction is over\")\n\n print('decoder raw results')\n tmp_predict_file = os.path.join(args.output_dir, \"test_raw_predictions.pkl\")\n output_prediction_file = os.path.join(args.output_dir, args.output_file)\n results = get_final_predictions(all_results, tmp_predict_file, g=True)\n write_predictions(results, output_prediction_file)\n print('predictions saved to {}'.format(output_prediction_file))\n\n\nif __name__ == \"__main__\":\n main()\n"
] |
[
[
"torch.load",
"torch.utils.data.TensorDataset",
"torch.utils.data.SequentialSampler",
"torch.utils.data.DataLoader",
"torch.tensor",
"torch.no_grad",
"torch.cuda.is_available"
]
] |
PriyankaDatar/NLP_project_BIDAF
|
[
"0e9790d6c4d7bfa2a29c0b0a30a5acc9959cd6f7"
] |
[
"test.py"
] |
[
"import json\nimport torch\nfrom sqlnet.utils import *\nfrom sqlnet.model.seq2sql import Seq2SQL\nfrom sqlnet.model.sqlnet import SQLNet\nimport numpy as np\nimport datetime\n\nimport argparse\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--toy', action='store_true', \n help='If set, use small data; used for fast debugging.')\n parser.add_argument('--ca', action='store_true',\n help='Use conditional attention.')\n parser.add_argument('--dataset', type=int, default=0,\n help='0: original dataset, 1: re-split dataset')\n parser.add_argument('--rl', action='store_true',\n help='Use RL for Seq2SQL.')\n parser.add_argument('--baseline', action='store_true', \n help='If set, then test Seq2SQL model; default is SQLNet model.')\n parser.add_argument('--train_emb', action='store_true',\n help='Use trained word embedding for SQLNet.')\n args = parser.parse_args()\n\n N_word=50\n B_word=6\n if args.toy:\n USE_SMALL=True\n GPU=True\n BATCH_SIZE=15\n else:\n USE_SMALL=False\n GPU=True\n BATCH_SIZE=64\n TEST_ENTRY=(True, True, True) # (AGG, SEL, COND)\n\n sql_data, table_data, val_sql_data, val_table_data, \\\n test_sql_data, test_table_data, \\\n TRAIN_DB, DEV_DB, TEST_DB = load_dataset(\n args.dataset, use_small=USE_SMALL)\n\n word_emb = load_word_emb('glove/glove.%dB.%dd.txt'%(B_word,N_word), \\\n load_used=True, use_small=USE_SMALL) # load_used can speed up loading\n\n if args.baseline:\n model = Seq2SQL(word_emb, N_word=N_word, gpu=GPU, trainable_emb = True)\n else:\n model = SQLNet(word_emb, N_word=N_word, use_ca=args.ca, gpu=GPU,\n trainable_emb = True)\n\n if args.train_emb:\n agg_m, sel_m, cond_m, agg_e, sel_e, cond_e = best_model_name(args)\n print(\"Loading from %s\"%agg_m)\n model.agg_pred.load_state_dict(torch.load(agg_m))\n print(\"Loading from %s\"%sel_m)\n model.sel_pred.load_state_dict(torch.load(sel_m))\n print(\"Loading from %s\"%cond_m)\n model.cond_pred.load_state_dict(torch.load(cond_m))\n print(\"Loading from %s\"%agg_e)\n model.agg_embed_layer.load_state_dict(torch.load(agg_e))\n print(\"Loading from %s\"%sel_e)\n model.sel_embed_layer.load_state_dict(torch.load(sel_e))\n print(\"Loading from %s\"%cond_e)\n model.cond_embed_layer.load_state_dict(torch.load(cond_e))\n else:\n agg_m, sel_m, cond_m = best_model_name(args)\n print(\"Loading from %s\"%agg_m)\n model.agg_pred.load_state_dict(torch.load(agg_m))\n print(\"Loading from %s\"%sel_m)\n model.sel_pred.load_state_dict(torch.load(sel_m))\n print(\"Loading from %s\"%cond_m)\n model.cond_pred.load_state_dict(torch.load(cond_m))\n\n print(\"Dev acc_qm: %s;\\n breakdown on (agg, sel, where): %s\"%epoch_acc(\n model, BATCH_SIZE, val_sql_data, val_table_data, TEST_ENTRY))\n print(\"Dev execution acc: %s\"%epoch_exec_acc(\n model, BATCH_SIZE, val_sql_data, val_table_data, DEV_DB))\n print(\"Test acc_qm: %s;\\n breakdown on (agg, sel, where): %s\"%epoch_acc(\n model, BATCH_SIZE, test_sql_data, test_table_data, TEST_ENTRY))\n print(\"Test execution acc: %s\"%epoch_exec_acc(\n model, BATCH_SIZE, test_sql_data, test_table_data, TEST_DB))\n"
] |
[
[
"torch.load"
]
] |
jmanson377/PySMSIM
|
[
"1f6187679810ea647d074ab65c80827b67a27d53"
] |
[
"PySMSIM/examples/matyas.py"
] |
[
"import numpy as np\n\ndef matyas(X):\n return (0.26 * (X[:,0] ** 2 + X[:,1] ** 2) - 0.48 * X[:,0] * X[:,1]).reshape(-1)\n\nif __name__ == \"__main__\":\n print(matyas(np.array([1,1]).reshape(1,-1)))\n print(matyas(np.array([0,0]).reshape(1,-1)))\n print(matyas(np.array([[0,0],[1,1]]).reshape(-1,2)))\n print(matyas(np.array([0,0]).reshape(1,-1)).shape)\n print(matyas(np.array([[0,0],[1,1]]).reshape(-1,2)).shape)"
] |
[
[
"numpy.array"
]
] |
st3107/pdfstream
|
[
"6e1829d889e5f5400386513efe993ad0596da8a5"
] |
[
"tests/visualization/test_main.py"
] |
[
"import matplotlib.pyplot as plt\nimport pytest\n\nimport pdfstream.visualization.main as vis\n\n\[email protected](\n 'keys,kwargs', [\n (['Ni_gr', 'Ni_gr'], {'mode': 'line', 'legends': ['Ni0', 'Ni1'], 'label': 'gr'}),\n (['Ni_gr', 'Ni_gr'], {'mode': 'line', 'stack': False}),\n (['Ni_gr', 'Ni_gr'], {'mode': 'line', 'xy_kwargs': {'color': 'black'}, 'texts': ['Ni0', 'Ni1']}),\n (['Ni_gr', 'Ni_gr'], {'mode': 'line', 'colors': ['r', 'g']}),\n (['Ni_fgr', 'Ni_fgr'], {'mode': 'fit', 'texts': ['Ni0', 'Ni1'], 'label': 'gr'}),\n (['Ni_fgr', 'Ni_fgr'], {'mode': 'fit', 'stack': False}),\n (['Ni_fgr', 'Ni_fgr'], {'mode': 'fit', 'xy_kwargs': {'color': 'black'}}),\n (['Ni_fgr', 'Ni_fgr'], {'mode': 'fit', 'colors': ['r', 'g']})\n ]\n)\ndef test_waterfall(test_data, keys, kwargs):\n plt.figure()\n vis.waterfall((test_data[k] for k in keys), **kwargs)\n plt.show(block=False)\n plt.close()\n\n\ndef test_waterfall_error(test_data):\n plt.figure()\n with pytest.raises(ValueError):\n vis.waterfall(test_data['Ni_gr'], mode=\"unknown\")\n\n\[email protected](\n 'key,kwargs', [\n ('Ni_gr', {'mode': 'line', 'text': 'Ni', 'xy_kwargs': {'color': 'black'}}),\n ('Ni_gr', {'mode': 'line', 'legends': ['Ni'], 'xy_kwargs': {'color': 'black'}}),\n ('Ni_fgr', {'mode': 'fit', 'text': 'Ni', 'xy_kwargs': {'color': 'black'}})\n ]\n)\ndef test_visualize(test_data, key, kwargs):\n fig = plt.figure()\n ax = fig.add_subplot(111)\n vis.visualize(test_data[key], ax=ax, **kwargs)\n plt.show(block=False)\n plt.close()\n"
] |
[
[
"matplotlib.pyplot.show",
"matplotlib.pyplot.close",
"matplotlib.pyplot.figure"
]
] |
DJdongbudong/Bearing-Detection
|
[
"b1cddb4c699f3180e2ef128933020b083eadfef0"
] |
[
"experience/no3_train.py"
] |
[
"import numpy as np\nimport pandas as pd\nimport math\n\n# step 1/3 数据生成器\n#把标签转成oneHot\ndef convert2oneHot(index,Lens):\n hot = np.zeros((Lens,))\n hot[int(index)] = 1\n return(hot)\nMANIFEST_DIR = \"../data/train.csv\"\nBatch_size = 20\nLens = 640 # 取640为训练和验证截点。\n# 训练样本生成器——然后使用 keras 的 fit_generator 就可以不断调用 yield 的返回值\ndef xs_gen(path=MANIFEST_DIR, batch_size=Batch_size, train=True, Lens=Lens):\n data_list = pd.read_csv(path)\n if train:\n data_list = np.array(data_list)[:Lens] # 取前Lens行的训练数据\n print(\"Found %s train items.\"%len(data_list))\n print(\"list 1 is\",data_list[0,-1])\n steps = math.ceil(len(data_list) / batch_size) # 确定每轮有多少个batch\n else:\n data_list = np.array(data_list)[Lens:] # 取Lens行后的验证数据\n print(\"Found %s test items.\"%len(data_list))\n print(\"list 1 is\",data_list[0,-1])\n steps = math.ceil(len(data_list) / batch_size) # 确定每轮有多少个batch\n while True:\n for i in range(steps):\n batch_list = data_list[i * batch_size : i * batch_size + batch_size]\n np.random.shuffle(batch_list)\n batch_x = np.array([file for file in batch_list[:,1:-1]])\n batch_y = np.array([convert2oneHot(label,10) for label in batch_list[:,-1]])\n yield batch_x, batch_y\n# step 2/3 模型制造\nimport keras\nfrom keras.layers import *\nfrom keras.models import *\nfrom keras.optimizers import *\nTIME_PERIODS = 6000 # 数据长度为6000个点\ndef build_model(input_shape=(TIME_PERIODS,),num_classes=10):\n model = Sequential()\n model.add(Reshape((TIME_PERIODS, 1), input_shape=input_shape))\n # keras.layers.Conv1D(filters, kernel_size)\n # 当使用该层作为模型第一层时,需要提供 input_shape 参数\n \n # input_shape:第一层卷积层——输入数据\n # 6000 -> 3000\n model.add(Conv1D(16, 8, strides=2, activation='relu', input_shape=(TIME_PERIODS,1)))\n \n # 3000 -> 1500\n model.add(Conv1D(16, 8, strides=2, activation='relu', padding=\"same\"))\n # 1500 -> 750\n model.add(MaxPooling1D(2))\n \n # 750 -> 375\n model.add(Conv1D(64, 4, strides=2, activation='relu',padding=\"same\"))\n # 375 -> 188\n model.add(Conv1D(64, 4, strides=2, activation='relu',padding=\"same\"))\n # 188 -> 94\n model.add(MaxPooling1D(2))\n\n # 94 -> 47\n model.add(Conv1D(256, 4,strides=2, activation='relu',padding=\"same\"))\n # 47 -> 24\n model.add(Conv1D(256, 4,strides=2, activation='relu',padding=\"same\"))\n # 24 -> 12\n model.add(MaxPooling1D(2))\n\n # 12 -> 12 (strides=1,则输入=输出)\n model.add(Conv1D(512, 2, strides=1, activation='relu', padding=\"same\"))\n # 12 -> 12\n model.add(Conv1D(512, 2, strides=1, activation='relu', padding=\"same\"))\n # 12 -> 6\n model.add(MaxPooling1D(2))\n\n \"\"\"model.add(Flatten())\n model.add(Dropout(0.3))\n model.add(Dense(256, activation='relu'))\"\"\"\n # GlobalAveragePooling1D:对于时序数据的全局平均池化。\n model.add(GlobalAveragePooling1D())\n model.add(Dropout(0.3))\n \n # Dense():全连接层——返回计算类别\n model.add(Dense(num_classes, activation='softmax'))\n return model\n\n# step 3/3 模型优化器和训练\nif __name__ == \"__main__\":\n # 1 数据初始化\n train_iter = xs_gen()\n val_iter = xs_gen(train=False)\n\n # 2.模型保存点\n ckpt = keras.callbacks.ModelCheckpoint(\n filepath='best_model.{epoch:02d}-{val_loss:.4f}.h5',\n monitor='val_loss', save_best_only=True,verbose=1)\n\n # 3.模型构建\n model = build_model()\n\n # 4.损失函数与优化器\n model.compile(loss='categorical_crossentropy', optimizer=Adam(0.0002), metrics=['accuracy'])\n # 模型打印:# print(model.summary())\n \n Long = 792\n # 5.模型训练,配合使用数据生成器\n model.fit_generator(\n generator = train_iter,\n steps_per_epoch = Lens//Batch_size,\n epochs = 50,\n initial_epoch = 0,\n validation_data = val_iter,\n nb_val_samples = (Long - Lens)//Batch_size,\n callbacks = [ckpt],\n )\n # 6.训练后的模型保存\n model.save(\"finishModel.h5\")\n pass\n"
] |
[
[
"numpy.array",
"pandas.read_csv",
"numpy.zeros",
"numpy.random.shuffle"
]
] |
ooooverflow/DigestPath2019
|
[
"db7b6a0a86bffbe8f44b5d6aa72b4c76e982c0b8"
] |
[
"model.py"
] |
[
"import torch.nn as nn\nimport torch\nimport math\nimport time\nimport torch.utils.model_zoo as model_zoo\nfrom utils import BasicBlock, Bottleneck, BBoxTransform, ClipBoxes\nfrom anchors import Anchors\nimport losses\nfrom lib.nms.pth_nms import pth_nms\n\ndef nms(dets, thresh):\n \"Dispatch to either CPU or GPU NMS implementations.\\\n Accept dets as tensor\"\"\"\n return pth_nms(dets, thresh)\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\nclass PyramidFeatures(nn.Module):\n def __init__(self, C3_size, C4_size, C5_size, feature_size=256):\n super(PyramidFeatures, self).__init__()\n \n # upsample C5 to get P5 from the FPN paper\n self.P5_1 = nn.Conv2d(C5_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P5_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n self.P5_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1)\n\n # add P5 elementwise to C4\n self.P4_1 = nn.Conv2d(C4_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P4_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n self.P4_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1)\n\n # add P4 elementwise to C3\n self.P3_1 = nn.Conv2d(C3_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P3_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=1)\n\n # \"P6 is obtained via a 3x3 stride-2 conv on C5\"\n self.P6 = nn.Conv2d(C5_size, feature_size, kernel_size=3, stride=2, padding=1)\n\n # \"P7 is computed by applying ReLU followed by a 3x3 stride-2 conv on P6\"\n self.P7_1 = nn.ReLU()\n self.P7_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=2, padding=1)\n\n def forward(self, inputs):\n\n C3, C4, C5 = inputs\n\n P5_x = self.P5_1(C5)\n P5_upsampled_x = self.P5_upsampled(P5_x)\n P5_x = self.P5_2(P5_x)\n \n P4_x = self.P4_1(C4)\n P4_x = P5_upsampled_x + P4_x\n P4_upsampled_x = self.P4_upsampled(P4_x)\n P4_x = self.P4_2(P4_x)\n\n P3_x = self.P3_1(C3)\n P3_x = P3_x + P4_upsampled_x\n P3_x = self.P3_2(P3_x)\n\n P6_x = self.P6(C5)\n\n P7_x = self.P7_1(P6_x)\n P7_x = self.P7_2(P7_x)\n\n return [P3_x, P4_x, P5_x, P6_x, P7_x]\n\n\nclass RegressionModel(nn.Module):\n def __init__(self, num_features_in, num_anchors=9, feature_size=256):\n super(RegressionModel, self).__init__()\n \n self.conv1 = nn.Conv2d(num_features_in, feature_size, kernel_size=3, padding=1)\n self.act1 = nn.ReLU()\n\n self.conv2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)\n self.act2 = nn.ReLU()\n\n self.conv3 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)\n self.act3 = nn.ReLU()\n\n self.conv4 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)\n self.act4 = nn.ReLU()\n\n self.output = nn.Conv2d(feature_size, num_anchors*4, kernel_size=3, padding=1)\n\n def forward(self, x):\n\n out = self.conv1(x)\n out = self.act1(out)\n\n out = self.conv2(out)\n out = self.act2(out)\n\n out = self.conv3(out)\n out = self.act3(out)\n\n out = self.conv4(out)\n out = self.act4(out)\n\n out = self.output(out)\n\n # out is B x C x W x H, with C = 4*num_anchors\n out = out.permute(0, 2, 3, 1)\n\n return out.contiguous().view(out.shape[0], -1, 4)\n\nclass ClassificationModel(nn.Module):\n def __init__(self, num_features_in, num_anchors=9, num_classes=80, prior=0.01, feature_size=256):\n super(ClassificationModel, self).__init__()\n\n self.num_classes = num_classes\n self.num_anchors = num_anchors\n \n self.conv1 = nn.Conv2d(num_features_in, feature_size, kernel_size=3, padding=1)\n self.act1 = nn.ReLU()\n\n self.conv2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)\n self.act2 = nn.ReLU()\n\n self.conv3 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)\n self.act3 = nn.ReLU()\n\n self.conv4 = nn.Conv2d(feature_size, feature_size, kernel_size=3, padding=1)\n self.act4 = nn.ReLU()\n\n self.output = nn.Conv2d(feature_size, num_anchors*num_classes, kernel_size=3, padding=1)\n self.output_act = nn.Sigmoid()\n\n def forward(self, x):\n\n out = self.conv1(x)\n out = self.act1(out)\n\n out = self.conv2(out)\n out = self.act2(out)\n\n out = self.conv3(out)\n out = self.act3(out)\n\n out = self.conv4(out)\n out = self.act4(out)\n\n out = self.output(out)\n out = self.output_act(out)\n\n # out is B x C x W x H, with C = n_classes + n_anchors\n out1 = out.permute(0, 2, 3, 1)\n\n batch_size, width, height, channels = out1.shape\n\n out2 = out1.view(batch_size, width, height, self.num_anchors, self.num_classes)\n\n return out2.contiguous().view(x.shape[0], -1, self.num_classes)\n\nclass ResNet(nn.Module):\n\n def __init__(self, num_classes, block, layers):\n self.inplanes = 64\n super(ResNet, self).__init__()\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False)\n self.bn1 = nn.BatchNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 256, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 512, layers[3], stride=2)\n\n if block == BasicBlock:\n fpn_sizes = [self.layer2[layers[1]-1].conv2.out_channels, self.layer3[layers[2]-1].conv2.out_channels, self.layer4[layers[3]-1].conv2.out_channels]\n elif block == Bottleneck:\n fpn_sizes = [self.layer2[layers[1]-1].conv3.out_channels, self.layer3[layers[2]-1].conv3.out_channels, self.layer4[layers[3]-1].conv3.out_channels]\n\n self.fpn = PyramidFeatures(fpn_sizes[0], fpn_sizes[1], fpn_sizes[2])\n\n self.regressionModel = RegressionModel(256)\n self.classificationModel = ClassificationModel(256, num_classes=num_classes)\n\n self.anchors = Anchors()\n\n self.regressBoxes = BBoxTransform()\n\n self.clipBoxes = ClipBoxes()\n \n self.focalLoss = losses.FocalLoss()\n \n for m in self.modules():\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n prior = 0.01\n \n self.classificationModel.output.weight.data.fill_(0)\n self.classificationModel.output.bias.data.fill_(-math.log((1.0-prior)/prior))\n\n self.regressionModel.output.weight.data.fill_(0)\n self.regressionModel.output.bias.data.fill_(0)\n\n self.freeze_bn()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def freeze_bn(self):\n '''Freeze BatchNorm layers.'''\n for layer in self.modules():\n if isinstance(layer, nn.BatchNorm2d):\n layer.eval()\n\n def forward(self, inputs, test=False):\n\n if self.training or test:\n img_batch, annotations = inputs\n else:\n img_batch = inputs\n \n x = self.conv1(img_batch)\n x = self.bn1(x)\n x = self.relu(x)\n x = self.maxpool(x)\n\n x1 = self.layer1(x)\n x2 = self.layer2(x1)\n x3 = self.layer3(x2)\n x4 = self.layer4(x3)\n\n features = self.fpn([x2, x3, x4])\n regression = torch.cat([self.regressionModel(feature) for feature in features], dim=1)\n\n classification = torch.cat([self.classificationModel(feature) for feature in features], dim=1)\n\n anchors = self.anchors(img_batch)\n\n if self.training or test:\n return self.focalLoss(classification, regression, anchors, annotations)\n else:\n transformed_anchors = self.regressBoxes(anchors, regression)\n transformed_anchors = self.clipBoxes(transformed_anchors, img_batch)\n\n scores = torch.max(classification, dim=2, keepdim=True)[0]\n\n scores_over_thresh = (scores>0.05)[0, :, 0]\n\n if scores_over_thresh.sum() == 0:\n # no boxes to NMS, just return\n return [torch.zeros(0), torch.zeros(0), torch.zeros(0, 4)]\n\n classification = classification[:, scores_over_thresh, :]\n transformed_anchors = transformed_anchors[:, scores_over_thresh, :]\n scores = scores[:, scores_over_thresh, :]\n\n anchors_nms_idx = nms(torch.cat([transformed_anchors, scores], dim=2)[0, :, :], 0.3)\n\n nms_scores, nms_class = classification[0, anchors_nms_idx, :].max(dim=1)\n\n return [nms_scores, nms_class, transformed_anchors[0, anchors_nms_idx, :]]\n\n\n\ndef resnet18(num_classes, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(num_classes, BasicBlock, [2, 2, 2, 2], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18'], model_dir='.'), strict=False)\n return model\n\n\ndef resnet34(num_classes, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(num_classes, BasicBlock, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34'], model_dir='.'), strict=False)\n return model\n\n\ndef resnet50(num_classes, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-50 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(num_classes, Bottleneck, [3, 4, 6, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet50'], model_dir='.'), strict=False)\n return model\n\ndef resnet101(num_classes, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-101 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(num_classes, Bottleneck, [3, 4, 23, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet101'], model_dir='.'), strict=False)\n return model\n\n\ndef resnet152(num_classes, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-152 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(num_classes, Bottleneck, [3, 8, 36, 3], **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet152'], model_dir='.'), strict=False)\n return model\n\nif __name__ == '__main__':\n import os\n os.environ['CUDA_VISIBLE_DEVICES'] = '5'\n model = resnet18(num_classes=2, pretrained=False).cuda()\n x = torch.rand(1, 3, 512, 512).cuda()\n label = [[10, 20, 30, 40, 50, 60, 0]]\n label = torch.Tensor(label).unsqueeze(0).cuda()\n model.eval()\n y = model(x)\n print(y)\n"
] |
[
[
"torch.nn.Sequential",
"torch.max",
"torch.Tensor",
"torch.zeros",
"torch.cat",
"torch.nn.Conv2d",
"torch.nn.Sigmoid",
"torch.nn.MaxPool2d",
"torch.nn.Upsample",
"torch.rand",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU",
"torch.utils.model_zoo.load_url"
]
] |
camus1337/pytorch_geometric
|
[
"38514197a327541eb47abb69d4ab224910852605"
] |
[
"torch_geometric/nn/models/node2vec.py"
] |
[
"import torch\nfrom torch.nn import Embedding\nfrom torch.utils.data import DataLoader\nfrom torch_sparse import SparseTensor\n\nfrom torch_geometric.utils.num_nodes import maybe_num_nodes\n\ntry:\n import torch_cluster # noqa\n random_walk = torch.ops.torch_cluster.random_walk\nexcept ImportError:\n random_walk = None\n\nEPS = 1e-15\n\n\nclass Node2Vec(torch.nn.Module):\n r\"\"\"The Node2Vec model from the\n `\"node2vec: Scalable Feature Learning for Networks\"\n <https://arxiv.org/abs/1607.00653>`_ paper where random walks of\n length :obj:`walk_length` are sampled in a given graph, and node embeddings\n are learned via negative sampling optimization.\n\n .. note::\n\n For an example of using Node2Vec, see `examples/node2vec.py\n <https://github.com/rusty1s/pytorch_geometric/blob/master/examples/\n node2vec.py>`_.\n\n Args:\n edge_index (LongTensor): The edge indices.\n embedding_dim (int): The size of each embedding vector.\n walk_length (int): The walk length.\n context_size (int): The actual context size which is considered for\n positive samples. This parameter increases the effective sampling\n rate by reusing samples across different source nodes.\n walks_per_node (int, optional): The number of walks to sample for each\n node. (default: :obj:`1`)\n p (float, optional): Likelihood of immediately revisiting a node in the\n walk. (default: :obj:`1`)\n q (float, optional): Control parameter to interpolate between\n breadth-first strategy and depth-first strategy (default: :obj:`1`)\n num_negative_samples (int, optional): The number of negative samples to\n use for each positive sample. (default: :obj:`1`)\n num_nodes (int, optional): The number of nodes. (default: :obj:`None`)\n sparse (bool, optional): If set to :obj:`True`, gradients w.r.t. to the\n weight matrix will be sparse. (default: :obj:`False`)\n \"\"\"\n def __init__(self, edge_index, embedding_dim, walk_length, context_size,\n walks_per_node=1, p=1, q=1, num_negative_samples=1,\n num_nodes=None, sparse=False):\n super(Node2Vec, self).__init__()\n\n if random_walk is None:\n raise ImportError('`Node2Vec` requires `torch-cluster`.')\n\n N = maybe_num_nodes(edge_index, num_nodes)\n row, col = edge_index\n self.adj = SparseTensor(row=row, col=col, sparse_sizes=(N, N))\n self.adj = self.adj.to('cpu')\n\n assert walk_length >= context_size\n\n self.embedding_dim = embedding_dim\n self.walk_length = walk_length - 1\n self.context_size = context_size\n self.walks_per_node = walks_per_node\n self.p = p\n self.q = q\n self.num_negative_samples = num_negative_samples\n\n self.embedding = Embedding(N, embedding_dim, sparse=sparse)\n\n self.reset_parameters()\n\n def reset_parameters(self):\n self.embedding.reset_parameters()\n\n def forward(self, batch=None):\n \"\"\"Returns the embeddings for the nodes in :obj:`batch`.\"\"\"\n emb = self.embedding.weight\n return emb if batch is None else emb[batch]\n\n def loader(self, **kwargs):\n return DataLoader(range(self.adj.sparse_size(0)),\n collate_fn=self.sample, **kwargs)\n\n def pos_sample(self, batch):\n batch = batch.repeat(self.walks_per_node)\n rowptr, col, _ = self.adj.csr()\n rw = random_walk(rowptr, col, batch, self.walk_length, self.p, self.q)\n if not isinstance(rw, torch.Tensor):\n rw = rw[0]\n\n walks = []\n num_walks_per_rw = 1 + self.walk_length + 1 - self.context_size\n for j in range(num_walks_per_rw):\n walks.append(rw[:, j:j + self.context_size])\n return torch.cat(walks, dim=0)\n\n def neg_sample(self, batch):\n batch = batch.repeat(self.walks_per_node * self.num_negative_samples)\n\n rw = torch.randint(self.adj.sparse_size(0),\n (batch.size(0), self.walk_length))\n rw = torch.cat([batch.view(-1, 1), rw], dim=-1)\n\n walks = []\n num_walks_per_rw = 1 + self.walk_length + 1 - self.context_size\n for j in range(num_walks_per_rw):\n walks.append(rw[:, j:j + self.context_size])\n return torch.cat(walks, dim=0)\n\n def sample(self, batch):\n if not isinstance(batch, torch.Tensor):\n batch = torch.tensor(batch)\n return self.pos_sample(batch), self.neg_sample(batch)\n\n def loss(self, pos_rw, neg_rw):\n r\"\"\"Computes the loss given positive and negative random walks.\"\"\"\n\n # Positive loss.\n start, rest = pos_rw[:, 0], pos_rw[:, 1:].contiguous()\n\n h_start = self.embedding(start).view(pos_rw.size(0), 1,\n self.embedding_dim)\n h_rest = self.embedding(rest.view(-1)).view(pos_rw.size(0), -1,\n self.embedding_dim)\n\n out = (h_start * h_rest).sum(dim=-1).view(-1)\n pos_loss = -torch.log(torch.sigmoid(out) + EPS).mean()\n\n # Negative loss.\n start, rest = neg_rw[:, 0], neg_rw[:, 1:].contiguous()\n\n h_start = self.embedding(start).view(neg_rw.size(0), 1,\n self.embedding_dim)\n h_rest = self.embedding(rest.view(-1)).view(neg_rw.size(0), -1,\n self.embedding_dim)\n\n out = (h_start * h_rest).sum(dim=-1).view(-1)\n neg_loss = -torch.log(1 - torch.sigmoid(out) + EPS).mean()\n\n return pos_loss + neg_loss\n\n def test(self, train_z, train_y, test_z, test_y, solver='lbfgs',\n multi_class='auto', *args, **kwargs):\n r\"\"\"Evaluates latent space quality via a logistic regression downstream\n task.\"\"\"\n from sklearn.linear_model import LogisticRegression\n\n clf = LogisticRegression(solver=solver, multi_class=multi_class, *args,\n **kwargs).fit(train_z.detach().cpu().numpy(),\n train_y.detach().cpu().numpy())\n return clf.score(test_z.detach().cpu().numpy(),\n test_y.detach().cpu().numpy())\n\n def __repr__(self):\n return '{}({}, {})'.format(self.__class__.__name__,\n self.embedding.weight.size(0),\n self.embedding.weight.size(1))\n"
] |
[
[
"torch.sigmoid",
"sklearn.linear_model.LogisticRegression",
"torch.cat",
"torch.nn.Embedding",
"torch.tensor"
]
] |
tianjuchen/pyoptmat
|
[
"6f34205f450fd884679f37522ccd0d0b65ecdb71",
"6f34205f450fd884679f37522ccd0d0b65ecdb71",
"6f34205f450fd884679f37522ccd0d0b65ecdb71"
] |
[
"examples/structural-inference/tension/deterministic/optimize.py",
"pyoptmat/experiments.py",
"pyoptmat/flowrules.py"
] |
[
"#!/usr/bin/env python3\n\n\"\"\"\n Example using the tutorial data to train a deterministic model, rather than\n a statistical model.\n\"\"\"\n\nimport sys\n\nsys.path.append(\"../../../..\")\nsys.path.append(\"..\")\n\nimport os.path\n\nimport numpy.random as ra\n\nimport xarray as xr\nimport torch\n\nfrom maker import make_model, downsample\n\nfrom pyoptmat import optimize, experiments\nfrom tqdm import tqdm\n\nimport matplotlib.pyplot as plt\n\n# Don't care if integration fails\nimport warnings\n\nwarnings.filterwarnings(\"ignore\")\n\n# Use doubles\ntorch.set_default_tensor_type(torch.DoubleTensor)\n\n# Select device to run on\nif torch.cuda.is_available():\n dev = \"cuda:0\"\nelse:\n dev = \"cpu\"\ndevice = torch.device(dev)\n\n# Maker function returns the ODE model given the parameters\n# Don't try to optimize for the Young's modulus\ndef make(n, eta, s0, R, d, **kwargs):\n \"\"\"\n Maker with the Young's modulus fixed\n \"\"\"\n return make_model(torch.tensor(0.5), n, eta, s0, R, d, device=device, **kwargs).to(\n device\n )\n\n\nif __name__ == \"__main__\":\n # 1) Load the data for the variance of interest,\n # cut down to some number of samples, and flatten\n scale = 0.01\n nsamples = 10 # at each strain rate\n input_data = xr.open_dataset(os.path.join(\"..\", \"scale-%3.2f.nc\" % scale))\n data, results, cycles, types, control = downsample(\n experiments.load_results(input_data, device=device),\n nsamples,\n input_data.nrates,\n input_data.nsamples,\n )\n\n # 2) Setup names for each parameter and the initial conditions\n names = [\"n\", \"eta\", \"s0\", \"R\", \"d\"]\n ics = torch.tensor([ra.uniform(0, 1) for i in range(len(names))], device=device)\n\n print(\"Initial parameter values:\")\n for n, ic in zip(names, ics):\n print(\"%s:\\t%3.2f\" % (n, ic))\n print(\"\")\n\n # 3) Create the actual model\n model = optimize.DeterministicModel(make, names, ics)\n\n # 4) Setup the optimizer\n niter = 10\n optim = torch.optim.LBFGS(model.parameters())\n\n # 5) Setup the objective function\n loss = torch.nn.MSELoss(reduction=\"sum\")\n\n # 6) Actually do the optimization!\n def closure():\n optim.zero_grad()\n pred = model(data, cycles, types, control)\n lossv = loss(pred, results)\n lossv.backward()\n return lossv\n\n t = tqdm(range(niter), total=niter, desc=\"Loss: \")\n loss_history = []\n for i in t:\n closs = optim.step(closure)\n loss_history.append(closs.detach().cpu().numpy())\n t.set_description(\"Loss: %3.2e\" % loss_history[-1])\n\n # 7) Check accuracy of the optimized parameters\n print(\"\")\n print(\"Optimized parameter accuracy:\")\n for n in names:\n print(\"%s:\\t%3.2f/0.50\" % (n, getattr(model, n).data))\n\n # 8) Plot the convergence history\n plt.figure()\n plt.plot(loss_history)\n plt.xlabel(\"Iteration\")\n plt.ylabel(\"Loss\")\n plt.tight_layout()\n plt.show()\n",
"# pylint: disable=dangerous-default-value\n\n\"\"\"\n Various routines for dealing with generating input and processing output\n for abstracted records of experimental tests.\n\n These routines do things like:\n * Convert simplified descriptions of tests into strain/strain time\n histories that the models can use\n * Generate random experiments and the corresponding inputs\n\n The actual deterministic and statistical fitting routines expect data\n in a common format. There are a few conditions on the input test data:\n\n 1. You have to sample all tests with the same number of time points (ntime).\n 2. You have to provide the full, correct history of the input conditions.\n For strain controlled experiments this is the full history of test\n time, strain, and temperature. For stress control it is the full\n history of time, stress, and temperature.\n 3. You do not have to provide the full *results* history. That is,\n the fit routines can accommodate some types of abstracted test data,\n like maximum stress as a function of cycles for strain-controlled cyclic\n tests. The convert_results function can then convert a full (simulated)\n results history to the right abstracted format for comparison to the\n test data.\n\n The fitting routines rely on five tensors with the following format:\n\n * data :code:`(3, ntime, nexp)`: the input experimental conditions.\n The first\n index contains the experimental time, temperature, and strain history\n for strain controlled tests and the experimental time, temperature\n and stress history for stress controlled tests\n * results :code:`(ntime, nexp)`: the (potentially abstracted) experimental\n results.\n For example, this could be the stress history for a tensile test or\n the strain history for a creep test. The specific requirements for\n certain tests types are described below.\n * cycles :code:`(ntime, nexp)`: the cycle counts for cyclic tests or an\n integer\n used to indicate features of the experiment for other test types.\n Specific requirements are given below.\n * types :code:`(nexp,)`: an integer giving the test type (see list below)\n * control :code:`(nexp,)`: 0 for strain control, 1 for stress control\n\n The current test types are:\n\n 0. \"tension\" -- uniaxial, monotonic tension or compression test\n 1. \"relaxation\" -- stress relaxation test\n 2. \"strain_cyclic\" -- strain controlled cyclic (i.e. creep or creep-fatigue)\n 3. \"creep\" -- a creep test\n 4. \"stress_cyclic\" -- a stress controlled cyclic test\n 5. \"abstract_tensile\" -- tension tests where only the yield strength\n and ultimate tensile strength are known\n 6. \"direct_data\" -- the full results history is known and provided\n\n The :func:`pyoptmat.experiments.load_results`\n function provides a way to load data for this type\n from an xarray format. The same tensors are stored in the xarray\n structure, however the descriptive string names for the tests are used\n and \"strain\" or \"stress\" is used instead of 0 and 1 to indicate the\n control type. Additional metadata can be stored in the xarray format with\n source information, heat ID, etc.\n\"\"\"\n\nimport numpy as np\nimport numpy.random as ra\n\nimport torch\n\n\ndef load_results(xdata, device=torch.device(\"cpu\")):\n \"\"\"\n Load experimental data from xarray into torch tensors\n\n Args:\n xdata (xarray.DataArray): xarray data structure\n\n Keyword Args:\n device (torch.device): the device to dump the resulting arrays on\n\n Returns:\n tuple: see below\n\n This function returns a tuple of five tensors\n\n data :code:`(3, ntime, nexperiment)`\n\n The initial index are the experimental (times, temperatures, idata)\n For strain controlled tests idata is strain\n For stress controlled tests idata is stress\n\n results :code:`(ntime, nexperiment)`\n\n For strain controlled tests this is stress\n For stress controlled tests this is strain\n\n cycles :code:`(ntime, nexperiment)`\n\n Cycle count for all tests\n\n types :code:`(nexperiment,)`\n\n Experiment types, converted to integers per the dicts above\n\n control :code:`(nexperiment,)`\n\n Maps the string control type (\"strain\" or \"stress\") to an integer\n using the dict above\n \"\"\"\n time = torch.tensor(xdata[\"time\"].values, device=device)\n temp = torch.tensor(xdata[\"temperature\"].values, device=device)\n strain = torch.tensor(xdata[\"strain\"].values, device=device)\n stress = torch.tensor(xdata[\"stress\"].values, device=device)\n\n cycle = torch.tensor(xdata[\"cycle\"].values, device=device)\n types = torch.tensor([exp_map[t] for t in xdata[\"type\"].values], device=device)\n control = torch.tensor(\n [control_map[t] for t in xdata[\"control\"].values], device=device\n )\n\n data = torch.empty((4,) + time.shape, device=device)\n\n data[0] = time\n data[1] = temp\n data[2, :, control == 0] = strain[:, control == 0]\n data[2, :, control == 1] = stress[:, control == 1]\n\n results = torch.empty_like(time)\n results[:, control == 0] = stress[:, control == 0]\n results[:, control == 1] = strain[:, control == 1]\n\n return data, results, cycle, types, control\n\n\ndef convert_results(results, cycles, types):\n \"\"\"\n Process a raw results vector to our common format based on test type\n\n Args:\n results (torch.tensor): raw results data :code:`(ntime, nexperiment)`\n cycles (torch.tensor): cycle counts :code:`(ntime, nexperiment)`\n types (torch.tensor): test types :code:`(nexperiment,)`\n\n Returns:\n torch.tensor: tensor of processed results\n \"\"\"\n processed = torch.empty_like(results)\n\n for i, func in exp_fns_num.items():\n current = types == i\n if torch.sum(current) > 0:\n processed[:, current] = func(cycles[:, current], results[:, current])\n\n return processed\n\n\ndef format_direct_data(cycles, predictions):\n \"\"\"\n Format direct stress/strain results\n\n For this test type cycles just equals 0 for all time steps\n\n This function does nothing, it just returns :code:`predictions`\n\n Args:\n cycles (torch.tensor): cycle count\n predictions (torch.tensor): input to format\n\n Returns:\n torch.tensor: tensor of processed results\n\n \"\"\"\n return predictions\n\n\ndef format_abstract_tensile(cycles, predictions):\n \"\"\"\n Format abstracted tensile test data, where only the yield strength\n and ultimate tensile strength are available.\n\n This method relies on the input cycles being:\n * 0: in the elastic regime\n * 1: for the first 1/2 of the remaining time points outside of the elastic regime\n * 2: for the second 1/2 of the remaining time points.\n\n The inputs are the full stress history. This function:\n\n * Cycle 0: overwrite with zeros\n * Cycle 1: overwrite with the first value in cycle 1\n * Cycle 2: overwrite with the maximum stress\n\n Args:\n cycles (torch.tensor): cycle count\n predictions (torch.tensor): input to format\n\n Returns:\n torch.tensor: tensor of processed results\n \"\"\"\n result = torch.zeros_like(predictions)\n\n # cycles == 0 -> 0\n result += torch.where(cycles == 0, 0.0, 0.0)\n\n # cycles == 1 -> first value in that region\n _, index = torch.max(cycles == 1, 0)\n result += torch.where(cycles == 1, predictions.gather(0, index.view(1, -1))[0], 0.0)\n\n # cycles == 2 -> max value overall\n mvalues, _ = torch.max(predictions, 0)\n result += torch.where(cycles == 2, mvalues, 0.0)\n\n return result\n\n\ndef format_tensile(cycles, predictions):\n \"\"\"\n Format tension test data to our \"post-processed\" form for comparison\n\n Input data are stresses for this test type\n\n Cycles are all 0\n\n This function doesn't do anything, just returns :code:`predictions`\n\n Args:\n cycles (torch.tensor): cycle count/listing\n predictions (torch.tensor): input data\n\n Returns:\n torch.tensor: processed results\n \"\"\"\n return predictions\n\n\ndef format_relaxation(cycles, predictions):\n \"\"\"\n Format stress relaxation test data to our \"post-processed\" form for\n comparison. This works for both creep and stress relaxation tests.\n\n Input data are stresses for stress relaxation and strains for creep\n\n Cycle 0 indicates the loading part of the test, cycle 1 is the hold\n\n Zero out the loading results, replace the relaxation results with the\n normalized (subtract t=0) curve\n\n Args:\n cycles (torch.tensor): cycle count/listing\n predictions (torch.tensor): input data\n\n Returns:\n torch.tensor: processed results\n \"\"\"\n result = torch.zeros_like(predictions)\n rcurve = cycles[:, 0] == 1 # This is right, but dangerous in the future\n\n curve = predictions[rcurve]\n curve = curve - curve[0]\n\n result[rcurve] = curve\n\n return result\n\n\ndef format_cyclic(cycles, predictions):\n \"\"\"\n Format a generic cyclic test -- works for both stress and strain control\n\n Input data are stresses for strain control and strains for stress control.\n\n We format this as a \"block\" -- the values for each cycle are replaced\n by the maximum value within the cycle\n\n Args:\n cycles (torch.tensor): cycle count/listing\n predictions (torch.tensor): input data\n\n Returns:\n torch.tensor: processed results\n \"\"\"\n # If this is slow we can probably remove the for loop\n result = torch.zeros_like(predictions)\n uc = cycles[:, 0] # Correct but dangerous for future expansion\n for i in range(uc[-1] + 1):\n curr = uc == i\n vals, _ = torch.max(predictions[curr], axis=0)\n result[curr] = vals\n\n return result\n\n\ndef make_tension_tests(rates, temperatures, elimits, nsteps):\n \"\"\"\n Produce tension test (time,strain,temperature) history blocks\n given tensor inputs for the strain rates, temperatures, and\n maximum strain of each test\n\n Args:\n rates (torch.tensor): 1D tensor giving the strain rate of each test\n temperaturess (torch.tensor): 1D tensor giving the constant temperature of each test\n elimits (torch.tensor): 1D tensor giving the maximum strain of each test\n nsteps (torch.tensor): integer number of steps\n\n Returns:\n tuple: tuple of\n :code:`(times, strains, temperatures, cycles)`\n \"\"\"\n nbatch = temperatures.shape[0]\n times = torch.zeros(nsteps, nbatch)\n strains = torch.zeros_like(times)\n temps = torch.zeros_like(strains)\n\n for i in range(nbatch):\n times[:, i] = torch.linspace(0, elimits[i] / rates[i], nsteps)\n strains[:, i] = torch.linspace(0, elimits[i], nsteps)\n temps[:, i] = temperatures[i]\n\n return times, strains, temps, torch.zeros_like(times, dtype=int)\n\n\ndef make_creep_tests(\n stress, temperature, rate, hold_times, nsteps_load, nsteps_hold, logspace=False\n):\n \"\"\"\n Produce creep test input (time,stress,temperature) given tensor\n inputs for the target stress, target temperature, loading rate\n\n Args:\n stress (torch.tensor): 1D tensor of target stresses\n temperature (torch.tensor): 1D tensor of target temperature\n rate (torch.tensor): 1D tensor of target rates\n hold_times (torch.tensor): 1D tensor of hold times\n nsteps_load (torch.tensor): number of time steps to load up the sample\n nsteps_hold (torch.tensor): number of time steps to hold the sample\n\n Keyword Args:\n logspace (bool): log-space time increments during holds\n\n Returns:\n tuple: tuple of\n :code:`(times, strains, temperatures, cycles)`\n \"\"\"\n nbatch = stress.shape[0]\n nsteps = nsteps_load + nsteps_hold\n\n stresses = torch.zeros(nsteps, nbatch)\n times = torch.zeros_like(stresses)\n temperatures = torch.zeros_like(stresses)\n\n for i, (s, t, lr, T) in enumerate(zip(stress, hold_times, rate, temperature)):\n stresses[:nsteps_load, i] = torch.linspace(0, s, nsteps_load)\n stresses[nsteps_load:, i] = s\n\n times[:nsteps_load, i] = torch.linspace(0, s / lr, nsteps_load)\n temperatures[:, i] = T\n if logspace:\n times[nsteps_load:, i] = torch.logspace(\n torch.log10(times[nsteps_load - 1, i]), torch.log10(t), nsteps_hold + 1\n )[1:]\n else:\n times[nsteps_load:, i] = torch.linspace(\n times[nsteps_load - 1, i], t, nsteps_hold + 1\n )[1:]\n\n cycles = torch.ones_like(times, dtype=int)\n cycles[:nsteps_load] = 0\n\n return times, stresses, temperatures, cycles\n\n\ndef generate_random_tension(strain_rate=[1.0e-6, 1.0e-2], max_strain=0.2):\n \"\"\"\n Generate a random tension test condition in the provided ranges\n\n Keyword Args:\n strain_rate (list): Range of strain rates\n max_strain (float): Maximum strain to simulate\n\n Returns:\n dict: dictionary with :code:`\"max_strain\"`\n and :code:`\"strain_rate\"`\n \"\"\"\n return {\n \"max_strain\": max_strain,\n \"strain_rate\": 10.0\n ** ra.uniform(np.log10(strain_rate[0]), np.log10(strain_rate[1])),\n }\n\n\ndef sample_tension(test, nsteps=50):\n \"\"\"\n Generate the times and strains for a tensile test\n\n Args:\n test (dict): Dictionary defining the test case\n\n Keyword Args:\n nsteps (int): Number of steps to sample\n\n Returns:\n tuple: tuple of :code:`(times, strains)`\n \"\"\"\n tmax = test[\"max_strain\"] / test[\"strain_rate\"]\n times = np.linspace(0, tmax, nsteps)\n strains = times * test[\"strain_rate\"]\n\n return times, strains\n\n\ndef generate_random_cycle(\n max_strain=[0, 0.02],\n R=[-1, 1],\n strain_rate=[1.0e-3, 1.0e-5],\n tension_hold=[0, 1 * 3600.0],\n compression_hold=[0, 600],\n):\n \"\"\"\n Generate a random cycle in the provided ranges\n\n Keyword Args:\n max_strain (list): range of the maximum strains\n R (list): range of R ratios\n strain_rate (list): range of loading strain rates\n tension_hold (list): range of tension hold times\n compression_hold (list): range of compression hold times\n\n Returns:\n dict: dictionary describing cycle, described below\n\n * :code:`\"max_strain\"` -- maximum strain value\n * :code:`\"R\"` -- R ratio :math:`\\\\frac{max}{min}`\n * :code:`\"strain_rate\"` -- strain rate during load/unload\n * :code:`\"tension_hold\"` -- hold on the tension end of the cycle\n * :code:`\"compression_hold\"` -- hold on the compressive end of the cycle\n \"\"\"\n return {\n \"max_strain\": ra.uniform(*max_strain),\n \"R\": ra.uniform(*R),\n \"strain_rate\": 10.0\n ** ra.uniform(np.log10(strain_rate[0]), np.log10(strain_rate[1])),\n \"tension_hold\": ra.uniform(*tension_hold),\n \"compression_hold\": ra.uniform(*compression_hold),\n }\n\n\ndef sample_cycle_normalized_times(cycle, N, nload=10, nhold=10):\n # pylint: disable=too-many-locals\n \"\"\"\n Sample a cyclic test at a normalized series of times\n\n Take a random cycle dictionary and expand into discrete\n times, strains samples where times are the actual, physical\n times, given over the fixed phases\n\n * :math:`0 \\\\rightarrow t_{phase}` -- tension load\n * :math:`t_{phase} \\\\rightarrow 2 t_{phase}` -- tension hold\n * :math:`2 t_{phase} \\\\rightarrow 3 t_{phase}` -- unload\n * :math:`3 t_{phase} \\\\rightarrow 4 t_{phase}` -- compression load\n * :math:`4 t_{phase} \\\\rightarrow 5 t_{phase}` -- compression hold\n * :math:`5 t_{phase} \\\\rightarrow 6 t_{phase}` -- unload\n\n This pattern repeats for N cycles\n\n Args:\n cycle (dict): dictionary defining the load cycle\n N (int): number of repeats to include in the history\n\n Keyword Args:\n nload (int): number of steps to use for the load time\n nhold (int): number of steps to use for the hold time\n \"\"\"\n emax = cycle[\"max_strain\"]\n emin = cycle[\"R\"] * cycle[\"max_strain\"]\n erate = cycle[\"strain_rate\"]\n\n # Segments:\n t1 = np.abs(emax) / erate\n t2 = cycle[\"tension_hold\"]\n t3 = np.abs(emax - emin) / erate\n t4 = cycle[\"compression_hold\"]\n t5 = np.abs(emin) / erate\n divisions = [t1, t2, t3, t4, t5]\n timesteps = [nload, nhold, 2 * nload, nhold, nload]\n cdivisions = np.cumsum(divisions)\n period = cdivisions[-1]\n\n Ntotal = nload * 4 + nhold * 2\n\n times = np.zeros((1 + Ntotal * N,))\n cycles = np.zeros(times.shape, dtype=int)\n\n n = 1\n tc = 0\n for k in range(N):\n for ti, ni in zip(divisions, timesteps):\n times[n : n + ni] = np.linspace(tc, tc + ti, ni + 1)[1:]\n cycles[n : n + ni] = k\n n += ni\n tc += ti\n\n tp = times % period\n strains = np.piecewise(\n tp,\n [\n np.logical_and(tp >= 0, tp < cdivisions[0]),\n np.logical_and(tp >= cdivisions[0], tp < cdivisions[1]),\n np.logical_and(tp >= cdivisions[1], tp < cdivisions[2]),\n np.logical_and(tp >= cdivisions[2], tp < cdivisions[3]),\n np.logical_and(tp >= cdivisions[3], tp < cdivisions[4]),\n ],\n [\n lambda tt: tt / t1 * emax,\n lambda tt: tt * 0 + emax,\n lambda tt: emax - (tt - cdivisions[1]) / t3 * (emax - emin),\n lambda tt: tt * 0 + emin,\n lambda tt: emin - (tt - cdivisions[3]) / t5 * emin,\n ],\n )\n\n return times, strains, cycles\n\n\n# Numerical codes for each test type\nexp_map = {\n \"tensile\": 0,\n \"relaxation\": 1,\n \"strain_cyclic\": 2,\n \"creep\": 3,\n \"stress_cyclic\": 4,\n \"abstract_tensile\": 5,\n \"direct_data\": 6,\n}\n# Function to use to process each test type\nexp_fns = {\n \"tensile\": format_tensile,\n \"relaxation\": format_relaxation,\n \"strain_cyclic\": format_cyclic,\n \"creep\": format_relaxation,\n \"stress_cyclic\": format_cyclic,\n \"abstract_tensile\": format_abstract_tensile,\n \"direct_data\": format_direct_data,\n}\n# Map to numbers instead\nexp_fns_num = {exp_map[k]: v for k, v in exp_fns.items()}\n\n# Map control type to number\ncontrol_map = {\"strain\": 0, \"stress\": 1}\n",
"# pylint: disable=abstract-method, no-self-use, useless-super-delegation, line-too-long, duplicate-code\n\n\"\"\"\n Module containing inelastic flow rules. These provide the rate of the\n viscoplastic strain and internal variables as a function of the stress,\n the current values of the internal variables, the time, and the temperature.\n\n So these objects define two functions\n\n .. math::\n\n \\\\sigma, h, t, T \\\\rightarrow \\\\dot{\\\\varepsilon}_{in}\n\n \\\\sigma, h, t, T \\\\rightarrow \\\\dot{h}\n\n In addition, the object needs to define the derivative of the inelastic\n strain rate and internal variable evolution rates with respect to the\n current values of stress and the current values of the internal variables.\n The objects return \"self\" derivatives (i.e. the derivative of the inelastic\n strain rate with respect to stress and the derivative of the internal\n variable rate with respect to the internal variables) along with the rates\n themselves. The \"cross\" derivatives are defined with separate methods.\n\"\"\"\n\nimport numpy as np\n\nimport torch\nfrom torch import nn\n\nfrom pyoptmat import utility\n\n\nclass FlowRule(nn.Module):\n \"\"\"\n Superclass for flow rule models\n\n This implementation provides default zero cross derivatives and that's it.\n \"\"\"\n\n def __init__(self):\n super().__init__()\n\n def dflow_dhist(self, s, h, t, T):\n \"\"\"\n The derivative of the flow rate with respect to the internal variables\n\n The superclass implementation provides a default of zero with the\n right shape.\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): internal variables\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n torch.tensor: derivative of flow rate with respect to the\n internal variables\n \"\"\"\n return torch.zeros(s.shape + (1,) + h.shape[1:])\n\n def dhist_dstress(self, s, h, t, T):\n \"\"\"\n The derivative of the flow rate with respect to the stress\n\n The superclass implementation provides a default of zero with the\n right shape.\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): internal variables\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n torch.tensor: derivative of flow rate with respect to the stress\n \"\"\"\n return torch.zeros(h.shape + s.shape[1:])\n\n\nclass SuperimposedFlowRule(FlowRule):\n \"\"\"\n Superimpose multiple flow rules with\n\n .. math::\n\n \\\\dot{\\\\varepsilon}_{in}=\\\\sum_i \\\\dot{\\\\varepsilon}_{in,i}\n\n and the history the union of all the individual models\n\n Args:\n models (list): list of the individual models\n\n \"\"\"\n\n def __init__(self, models):\n super().__init__()\n self.models = nn.ModuleList(models)\n\n self.nmodels = len(self.models)\n self.nhist_per = [m.nhist for m in self.models]\n self.offsets = [0] + list(np.cumsum(self.nhist_per))[:-1]\n\n @property\n def nhist(self):\n \"\"\"\n The number of internal variables\n \"\"\"\n return sum(self.nhist_per)\n\n def flow_rate(self, s, h, t, T):\n \"\"\"\n The uniaxial flow rate itself and the derivative\n with respect to stress\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n tuple(torch.tensor, torch.tensor): the flow rate and the derivative\n of the flow rate with\n respect to stress\n \"\"\"\n rate = torch.zeros_like(s)\n drate = torch.zeros_like(s)\n\n for o, n, model in zip(self.offsets, self.nhist_per, self.models):\n ratei, dratei = model.flow_rate(s, h[:, o : o + n], t, T)\n rate += ratei\n drate += dratei\n\n return (rate, drate)\n\n def dflow_dhist(self, s, h, t, T):\n \"\"\"\n The derivative of the flow rate with respect to the internal variables\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n torch.tensor: the derivative of the flow rate\n \"\"\"\n res = torch.zeros(s.shape[:1] + (1,) + h.shape[1:], device=h.device)\n\n for o, n, model in zip(self.offsets, self.nhist_per, self.models):\n dratei = model.dflow_dhist(s, h[:, o : o + n], t, T)\n res[:, :, o : o + n] = dratei\n\n return res\n\n def history_rate(self, s, h, t, T):\n \"\"\"\n The history rate and the derivative of the history rate with respect\n to the current history\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n tuple(torch.tensor, torch.tensor): the history rate and the\n derivative of the history rate\n with respect to history\n \"\"\"\n rate = torch.zeros_like(h)\n drate = torch.zeros(h.shape + h.shape[-1:], device=h.device)\n\n for o, n, model in zip(self.offsets, self.nhist_per, self.models):\n ratei, dratei = model.history_rate(s, h[:, o : o + n], t, T)\n rate[:, o : o + n] = ratei\n drate[:, o : o + n, o : o + n] = dratei\n\n return (rate, drate)\n\n def dhist_dstress(self, s, h, t, T):\n \"\"\"\n The derivative of the history rate with respect to the stress\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n torch.tensor: the derivative of the flow rate\n \"\"\"\n res = torch.zeros(h.shape + s.shape[1:], device=h.device)\n\n for o, n, model in zip(self.offsets, self.nhist_per, self.models):\n dratei = model.dhist_dstress(s, h[:, o : o + n], t, T)\n res[:, o : o + n] = dratei\n\n return res\n\n\nclass PerfectViscoplasticity(FlowRule):\n \"\"\"\n Perfect viscoplasticity defined as\n\n .. math::\n\n \\\\dot{\\\\varepsilon}_{in}=\\\\left(\\\\frac{\\\\left|\\\\sigma\\\\right|}{\\\\eta}\\\\right)^{n}\\\\operatorname{sign}\\\\left(\\\\sigma\\\\right)\n\n \\\\dot{h} = \\\\emptyset\n\n Args:\n n (|TP|): rate sensitivity\n eta (|TP|): flow viscosity\n \"\"\"\n\n def __init__(self, n, eta):\n super().__init__()\n self.n = n\n self.eta = eta\n\n def flow_rate(self, s, h, t, T):\n \"\"\"\n The uniaxial flow rate itself and the derivative\n with respect to stress\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n tuple(torch.tensor, torch.tensor): the flow rate and the derivative\n of the flow rate with\n respect to stress\n \"\"\"\n return (\n (torch.abs(s) / self.eta(T)) ** self.n(T) * torch.sign(s),\n self.n(T) * (torch.abs(s) / self.eta(T)) ** (self.n(T) - 1) / self.eta(T),\n )\n\n @property\n def nhist(self):\n \"\"\"\n The number of internal variables\n\n Here 0...\n \"\"\"\n return 0\n\n def history_rate(self, s, h, t, T):\n \"\"\"\n The history rate and the derivative of the history rate with respect\n to the current history\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n tuple(torch.tensor, torch.tensor): the history rate and the\n derivative of the history rate\n with respect to history\n \"\"\"\n return torch.zeros_like(h), torch.zeros(h.shape + h.shape[-1:])\n\n\nclass IsoKinViscoplasticity(FlowRule):\n \"\"\"\n Viscoplasticity with isotropic and kinematic hardening, defined as\n\n .. math::\n\n \\\\dot{\\\\varepsilon}_{in}=\\\\left\\\\langle \\\\frac{\\\\left|\\\\sigma-x\\\\right|-s_{0}-k}{\\\\eta}\\\\right\\\\rangle ^{n}\\\\operatorname{sign}\\\\left(\\\\sigma-X\\\\right)\n\n and where the :py:class:`pyoptmat.hardening.IsotropicHardeningModel` and\n :py:class:`pyoptmat.hardening.KinematicHardeningModel` objects determine the\n history rate.\n\n The :py:class:`pyoptmat.hardening.IsotropicHardeningModel` and\n :py:class:`pyoptmat.hardening.KinematicHardeningModel` objects each define both a\n set of internal variables, including the corresponding rate forms and Jacobians,\n but also a map from those internal variables to the isotropic hardening\n value :math:`k` (for :py:class:`pyoptmat.hardening.IsotropicHardeningModel`)\n and the kinematic hardening value :math:`x`\n (for :py:class:`pyoptmat.hardening.KinematicHardeningModel`), along with\n the derivatives of those maps. All this information is required to assemble\n the information this class needs to provide.\n\n Args:\n n (|TP|): rate sensitivity\n eta (|TP|): flow viscosity\n s0 (|TP|): initial value of flow stress (i.e. the threshold stress)\n isotropic (:py:class:`pyoptmat.hardening.IsotropicHardeningModel`): object providing the isotropic hardening model\n kinematic (:py:class:`pyoptmat.hardening.IsotropicHardeningModel`): object providing the kinematic hardening model\n \"\"\"\n\n def __init__(self, n, eta, s0, isotropic, kinematic):\n super().__init__()\n self.isotropic = isotropic\n self.kinematic = kinematic\n self.n = n\n self.eta = eta\n self.s0 = s0\n\n def flow_rate(self, s, h, t, T):\n \"\"\"\n The flow rate itself and the derivative with respect to stress\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n tuple(torch.tensor, torch.tensor): the flow rate and the derivative of the flow rate with\n respect to stress\n \"\"\"\n ih = self.isotropic.value(h[:, : self.isotropic.nhist])\n kh = self.kinematic.value(h[:, self.isotropic.nhist :])\n\n return (\n utility.macaulay((torch.abs(s - kh) - self.s0(T) - ih) / self.eta(T))\n ** self.n(T)\n * torch.sign(s - kh),\n self.n(T)\n * utility.macaulay((torch.abs(s - kh) - self.s0(T) - ih) / self.eta(T))\n ** (self.n(T) - 1)\n / self.eta(T),\n )\n\n def dflow_diso(self, s, h, t, T):\n \"\"\"\n The derivative of the flow rate with respect to the isotropic hardening\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n torch.tensor: the derivative of the flow rate\n \"\"\"\n ih = self.isotropic.value(h[:, : self.isotropic.nhist])\n kh = self.kinematic.value(\n h[:, self.isotropic.nhist : self.isotropic.nhist + self.kinematic.nhist]\n )\n\n iv = (torch.abs(s - kh) - self.s0(T) - ih) / self.eta(T)\n\n return (\n -self.n(T)\n * utility.macaulay(iv) ** (self.n(T) - 1)\n / self.eta(T)\n * torch.sign(s - kh)\n )\n\n def dflow_dkin(self, s, h, t, T):\n \"\"\"\n The derivative of the flow rate with respect to the kinematic hardening\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n torch.tensor: the derivative of the flow rate\n \"\"\"\n ih = self.isotropic.value(h[:, : self.isotropic.nhist])\n kh = self.kinematic.value(\n h[:, self.isotropic.nhist : self.isotropic.nhist + self.kinematic.nhist]\n )\n\n return (\n -self.n(T)\n * utility.macaulay((torch.abs(s - kh) - self.s0(T) - ih) / self.eta(T))\n ** (self.n(T) - 1)\n / self.eta(T)\n )\n\n @property\n def nhist(self):\n \"\"\"\n The number of internal variables, here the sum from the isotropic\n and kinematic hardening models\n \"\"\"\n return self.isotropic.nhist + self.kinematic.nhist\n\n def history_rate(self, s, h, t, T):\n \"\"\"\n The vector of the rates of the internal variables split into\n portions defined by each hardening model\n\n The first chunk of entries is for the isotropic hardening,\n the second for the kinematic hardening.\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n tuple(torch.tensor, torch.tensor): the history rate and the\n derivative of the history rate\n with respect to history\n \"\"\"\n hrate = torch.zeros_like(h)\n hdiv = torch.zeros(h.shape + h.shape[-1:], device=h.device)\n erate, _ = self.flow_rate(s, h, t, T)\n\n hiso = h[:, : self.isotropic.nhist]\n hkin = h[:, self.isotropic.nhist :]\n\n hrate[:, : self.isotropic.nhist] = self.isotropic.history_rate(\n s, hiso, t, erate, T\n )\n hrate[:, self.isotropic.nhist :] = self.kinematic.history_rate(\n s, hkin, t, erate, T\n )\n\n # History partials\n hdiv[\n :, : self.isotropic.nhist, : self.isotropic.nhist\n ] = self.isotropic.dhistory_rate_dhistory(s, hiso, t, erate, T)\n hdiv[\n :, self.isotropic.nhist :, self.isotropic.nhist :\n ] = self.kinematic.dhistory_rate_dhistory(s, hkin, t, erate, T)\n\n # Strain rate components\n hdiv[:, : self.isotropic.nhist, : self.isotropic.nhist] += torch.matmul(\n self.isotropic.dhistory_rate_derate(s, hiso, t, erate, T),\n torch.matmul(\n self.dflow_diso(s, h, t, T)[:, None, None],\n self.isotropic.dvalue(hiso)[:, None, :],\n ),\n )\n hdiv[:, : self.isotropic.nhist, self.isotropic.nhist :] += torch.matmul(\n self.isotropic.dhistory_rate_derate(s, hiso, t, erate, T),\n torch.matmul(\n self.dflow_dkin(s, h, t, T)[:, None, None],\n self.kinematic.dvalue(hkin)[:, None, :],\n ),\n )\n hdiv[:, self.isotropic.nhist :, : self.isotropic.nhist] += torch.matmul(\n self.kinematic.dhistory_rate_derate(s, hkin, t, erate, T),\n torch.matmul(\n self.dflow_diso(s, h, t, T)[:, None, None],\n self.isotropic.dvalue(hiso)[:, None, :],\n ),\n )\n hdiv[:, self.isotropic.nhist :, self.isotropic.nhist :] += torch.matmul(\n self.kinematic.dhistory_rate_derate(s, hkin, t, erate, T),\n torch.matmul(\n self.dflow_dkin(s, h, t, T)[:, None, None],\n self.kinematic.dvalue(hkin)[:, None, :],\n ),\n )\n\n return hrate, hdiv\n\n def dflow_dhist(self, s, h, t, T):\n \"\"\"\n The derivative of the flow rate with respect to the internal variables\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n torch.tensor: the derivative of the flow rate\n \"\"\"\n res = torch.zeros(s.shape[:1] + (1,) + h.shape[1:], device=h.device)\n\n hiso = h[:, : self.isotropic.nhist]\n hkin = h[:, self.isotropic.nhist :]\n\n res[:, 0, : self.isotropic.nhist] = self.dflow_diso(s, h, t, T)[\n :, None\n ] * self.isotropic.dvalue(hiso)\n res[:, 0, self.isotropic.nhist :] = self.dflow_dkin(s, h, t, T)[\n :, None\n ] * self.kinematic.dvalue(hkin)\n\n return res\n\n def dhist_dstress(self, s, h, t, T):\n \"\"\"\n The derivative of the history rate with respect to the stress\n\n Args:\n s (torch.tensor): stress\n h (torch.tensor): history\n t (torch.tensor): time\n T (torch.tensor): temperature\n\n Returns:\n torch.tensor: the derivative of the flow rate\n \"\"\"\n res = torch.zeros(h.shape + s.shape[1:], device=h.device)\n\n erate, derate = self.flow_rate(s, h, t, T)\n\n hiso = h[:, : self.isotropic.nhist]\n hkin = h[:, self.isotropic.nhist :]\n\n res[:, : self.isotropic.nhist] = (\n self.isotropic.dhistory_rate_dstress(s, hiso, t, erate, T)\n + self.isotropic.dhistory_rate_derate(s, hiso, t, erate, T).bmm(\n derate[..., None, None]\n )[..., 0]\n )\n res[:, self.isotropic.nhist :] = (\n self.kinematic.dhistory_rate_dstress(s, hkin, t, erate, T)\n + self.kinematic.dhistory_rate_derate(s, hkin, t, erate, T).bmm(\n derate[..., None, None]\n )[..., 0]\n )\n\n return res\n"
] |
[
[
"torch.set_default_tensor_type",
"matplotlib.pyplot.tight_layout",
"torch.tensor",
"matplotlib.pyplot.plot",
"numpy.random.uniform",
"matplotlib.pyplot.ylabel",
"torch.cuda.is_available",
"torch.device",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.show",
"torch.nn.MSELoss",
"matplotlib.pyplot.figure"
],
[
"torch.max",
"numpy.linspace",
"torch.zeros",
"torch.sum",
"numpy.cumsum",
"torch.where",
"torch.device",
"torch.log10",
"torch.tensor",
"numpy.zeros",
"torch.ones_like",
"torch.linspace",
"torch.empty_like",
"torch.empty",
"torch.zeros_like",
"numpy.log10",
"numpy.logical_and",
"numpy.abs",
"numpy.random.uniform"
],
[
"torch.abs",
"torch.sign",
"torch.zeros",
"torch.nn.ModuleList",
"torch.zeros_like",
"numpy.cumsum"
]
] |
sadlyfell/bullbot
|
[
"b6ef96f61678fab4a245d8ccddf9d1ae7aae9fee"
] |
[
"pajbot/modules/roulette.py"
] |
[
"import datetime\nimport logging\n\nfrom numpy import random\n\nimport pajbot.exc\nimport pajbot.models\nfrom pajbot import utils\nfrom pajbot.managers.db import DBManager\nfrom pajbot.managers.handler import HandlerManager\nfrom pajbot.models.command import Command\nfrom pajbot.models.command import CommandExample\nfrom pajbot.models.roulette import Roulette\nfrom pajbot.modules import BaseModule\nfrom pajbot.modules import ModuleSetting\n\nlog = logging.getLogger(__name__)\n\n\nclass RouletteModule(BaseModule):\n\n ID = __name__.split(\".\")[-1]\n NAME = \"Roulette\"\n DESCRIPTION = \"Lets players roulette with themselves for points\"\n CATEGORY = \"Game\"\n SETTINGS = [\n ModuleSetting(\n key=\"message_won\",\n label=\"Won message | Available arguments: {bet}, {points}, {user}\",\n type=\"text\",\n required=True,\n placeholder=\"{user} won {bet} points in roulette and now has {points} points! FeelsGoodMan\",\n default=\"{user} won {bet} points in roulette and now has {points} points! FeelsGoodMan\",\n constraints={\"min_str_len\": 10, \"max_str_len\": 400},\n ),\n ModuleSetting(\n key=\"message_lost\",\n label=\"Lost message | Available arguments: {bet}, {points}, {user}\",\n type=\"text\",\n required=True,\n placeholder=\"{user} lost {bet} points in roulette and now has {points} points! FeelsBadMan\",\n default=\"{user} lost {bet} points in roulette and now has {points} points! FeelsBadMan\",\n constraints={\"min_str_len\": 10, \"max_str_len\": 400},\n ),\n ModuleSetting(\n key=\"rigged_percentage\",\n label=\"Rigged %, lower = more chance of winning. 50 = 50% of winning. 25 = 75% of winning\",\n type=\"number\",\n required=True,\n placeholder=\"\",\n default=50,\n constraints={\"min_value\": 1, \"max_value\": 100},\n ),\n ModuleSetting(\n key=\"online_global_cd\",\n label=\"Global cooldown (seconds)\",\n type=\"number\",\n required=True,\n placeholder=\"\",\n default=0,\n constraints={\"min_value\": 0, \"max_value\": 120},\n ),\n ModuleSetting(\n key=\"online_user_cd\",\n label=\"Per-user cooldown (seconds)\",\n type=\"number\",\n required=True,\n placeholder=\"\",\n default=60,\n constraints={\"min_value\": 0, \"max_value\": 240},\n ),\n ModuleSetting(\n key=\"min_roulette_amount\",\n label=\"Minimum roulette amount\",\n type=\"number\",\n required=True,\n placeholder=\"\",\n default=1,\n constraints={\"min_value\": 1, \"max_value\": 3000},\n ),\n ModuleSetting(\n key=\"can_execute_with_whisper\",\n label=\"Allow users to roulette in whispers\",\n type=\"boolean\",\n required=True,\n default=False,\n ),\n ModuleSetting(\n key=\"options_output\",\n label=\"Result output options\",\n type=\"options\",\n required=True,\n default=\"1. Show results in chat\",\n options=[\n \"1. Show results in chat\",\n \"2. Show results in whispers\",\n \"3. Show results in chat if it's over X points else it will be whispered.\",\n \"4. Combine output in chat\",\n ],\n ),\n ModuleSetting(\n key=\"min_show_points\",\n label=\"Min points you need to win or lose (if options 3)\",\n type=\"number\",\n required=True,\n placeholder=\"\",\n default=100,\n constraints={\"min_value\": 1, \"max_value\": 150000},\n ),\n ModuleSetting(\n key=\"only_roulette_after_sub\",\n label=\"Only allow roulettes after sub\",\n type=\"boolean\",\n required=True,\n default=False,\n ),\n ModuleSetting(\n key=\"after_sub_roulette_time\",\n label=\"How long after a sub people can roulette (seconds)\",\n type=\"number\",\n required=True,\n placeholder=\"\",\n default=30,\n constraints={\"min_value\": 5, \"max_value\": 3600},\n ),\n ]\n\n def __init__(self, bot):\n super().__init__(bot)\n self.last_sub = None\n self.output_buffer = \"\"\n self.output_buffer_args = []\n self.last_add = None\n\n def load_commands(self, **options):\n self.commands[\"roulette\"] = Command.raw_command(\n self.roulette,\n delay_all=self.settings[\"online_global_cd\"],\n delay_user=self.settings[\"online_user_cd\"],\n description=\"Roulette for points\",\n can_execute_with_whisper=self.settings[\"can_execute_with_whisper\"],\n examples=[\n CommandExample(\n None,\n \"Roulette for all of your 69 points \"\n \"({}% winrate)\".format(100 - self.settings[\"rigged_percentage\"]),\n chat=\"user:!roulette\\n\"\n \"bot:datguy1 won 69 points in roulette and now has 138 points! Always lucky PogChamp\",\n description=\"Do a roulette for 69 points\",\n ).parse()\n ],\n )\n\n def rigged_random_result(self):\n return random.randint(1, 100) > self.settings[\"rigged_percentage\"]\n\n def roulette(self, **options):\n if self.settings[\"only_roulette_after_sub\"]:\n if self.last_sub is None:\n return False\n if utils.now() - self.last_sub > datetime.timedelta(seconds=self.settings[\"after_sub_roulette_time\"]):\n return False\n\n message = options[\"message\"]\n user = options[\"source\"]\n bot = options[\"bot\"]\n\n if message:\n bot.whisper(user.username, \"The command is only !roulette and it wagers all your points SmileyFace\")\n return False\n\n try:\n bet = utils.parse_points_amount(user, \"all\")\n except pajbot.exc.InvalidPointAmount as e:\n bot.whisper(user.username, str(e))\n return False\n\n if bet < self.settings[\"min_roulette_amount\"]:\n bot.whisper(\n user.username,\n \"You can only roulette for {}+ points FeelsWeirdMan\".format(self.settings[\"min_roulette_amount\"]),\n )\n return False\n\n # Calculating the result\n result = self.rigged_random_result()\n\n points = bet if result else -bet\n user.points += points\n\n with DBManager.create_session_scope() as db_session:\n r = Roulette(user.id, points)\n db_session.add(r)\n\n arguments = {\"bet\": bet, \"user\": user.username_raw, \"points\": user.points_available(), \"win\": points > 0}\n\n if points > 0:\n out_message = self.get_phrase(\"message_won\", **arguments)\n else:\n out_message = self.get_phrase(\"message_lost\", **arguments)\n\n if user.subscriber:\n bot.me(out_message)\n\n HandlerManager.trigger(\"on_roulette_finish\", user=user, points=points)\n\n def on_tick(self, **rest):\n if self.output_buffer == \"\":\n return\n\n if self.last_add is None:\n return\n\n diff = utils.now() - self.last_add\n\n if diff.seconds > 3:\n self.flush_output_buffer()\n\n def flush_output_buffer(self):\n msg = self.output_buffer\n self.bot.me(msg)\n self.output_buffer = \"\"\n self.output_buffer_args = []\n\n def add_message(self, bot, arguments):\n parts = []\n new_buffer = \"Roulette: \"\n win_emote = \"forsenPls\"\n lose_emote = \"forsenSWA\"\n for arg in self.output_buffer_args:\n parts.append(\n \"{} {} {}{}\".format(\n win_emote if arg[\"win\"] else lose_emote, arg[\"user\"], \"+\" if arg[\"win\"] else \"-\", arg[\"bet\"]\n )\n )\n\n parts.append(\n \"{} {} {}{}\".format(\n win_emote if arguments[\"win\"] else lose_emote,\n arguments[\"user\"],\n \"+\" if arguments[\"win\"] else \"-\",\n arguments[\"bet\"],\n )\n )\n\n log.debug(parts)\n new_buffer += \", \".join(parts)\n\n if len(new_buffer) > 480:\n self.flush_output_buffer()\n else:\n self.output_buffer = new_buffer\n log.info(\"Set output buffer to \" + new_buffer)\n\n self.output_buffer_args.append(arguments)\n\n self.last_add = utils.now()\n\n def on_user_sub(self, **rest):\n self.last_sub = utils.now()\n if self.settings[\"only_roulette_after_sub\"]:\n self.bot.say(\n \"Rouletting is now allowed for {} seconds! PogChamp\".format(self.settings[\"after_sub_roulette_time\"])\n )\n\n def on_user_resub(self, **rest):\n self.last_sub = utils.now()\n if self.settings[\"only_roulette_after_sub\"]:\n self.bot.say(\n \"Rouletting is now allowed for {} seconds! PogChamp\".format(self.settings[\"after_sub_roulette_time\"])\n )\n\n def enable(self, bot):\n HandlerManager.add_handler(\"on_user_sub\", self.on_user_sub)\n HandlerManager.add_handler(\"on_user_resub\", self.on_user_resub)\n HandlerManager.add_handler(\"on_tick\", self.on_tick)\n\n def disable(self, bot):\n HandlerManager.remove_handler(\"on_user_sub\", self.on_user_sub)\n HandlerManager.remove_handler(\"on_user_resub\", self.on_user_resub)\n HandlerManager.remove_handler(\"on_tick\", self.on_tick)\n"
] |
[
[
"numpy.random.randint"
]
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.