repo_name
stringlengths 6
130
| hexsha
list | file_path
list | code
list | apis
list |
---|---|---|---|---|
JanCaha/gdalhelpers | [
"925ecb2552b697b5970617484f1fc259f844ba04"
]
| [
"tests/functions/test_create_points_at_angles_distance.py"
]
| [
"import unittest\nimport os\nimport math\nfrom osgeo import ogr\nimport numpy as np\nfrom gdalhelpers.functions.create_points_at_angles_distance import create_points_at_angles_distance\n\nPOINTS_PATH = os.path.join(os.path.dirname(__file__), \"..\", \"test_data\", \"points.gpkg\")\n\n\nclass CreatePointsAtAnglesDistanceTestCase(unittest.TestCase):\n\n def setUp(self):\n self.points_ds = ogr.Open(POINTS_PATH)\n\n def tearDown(self):\n self.points_ds = None\n\n def test_create_points_at_angles_distance(self):\n\n angles = np.arange(0, 360, 10).tolist()\n result = create_points_at_angles_distance(self.points_ds, angles,\n distance=10, angles_specification_degrees=True)\n\n self.assertIsInstance(result, ogr.DataSource)\n self.assertEqual(result.GetLayer().GetFeatureCount(), self.points_ds.GetLayer().GetFeatureCount() * len(angles))\n\n angles = np.arange(-math.pi, math.pi, (2*math.pi)/36).tolist()\n result = create_points_at_angles_distance(self.points_ds, angles,\n distance=10, angles_specification_degrees=False)\n\n self.assertIsInstance(result, ogr.DataSource)\n self.assertEqual(result.GetLayer().GetFeatureCount(), self.points_ds.GetLayer().GetFeatureCount() * len(angles))\n\n with self.assertRaisesRegex(TypeError, \"must be either `int` or `float`\"):\n angles_wrong = [\"string\"] + angles\n result = create_points_at_angles_distance(self.points_ds, angles_wrong,\n distance=20, angles_specification_degrees=False)\n"
]
| [
[
"numpy.arange"
]
]
|
DevmallyaK/Loss-Optimizer-Using-Pytorch | [
"d837852c451ebac57819363e8fe572a655b57783"
]
| [
"loss & Optimizer.py"
]
| [
"# 1) Design model (input, output, forward pass with different layers)\r\n# 2) Construct loss and optimizer\r\n# 3) Training loop\r\n# - Forward = compute prediction and loss\r\n# - Backward = compute gradients\r\n# - Update weights\r\n\r\nimport torch\r\nimport torch.nn as nn\r\n\r\n# Linear regression\r\n# f = w * x\r\n\r\n# here : f = 2 * x\r\n\r\n# 0) Training samples\r\nX = torch.tensor([1, 2, 3, 4], dtype=torch.float32)\r\nY = torch.tensor([2, 4, 6, 8], dtype=torch.float32)\r\n\r\n# 1) Design Model: Weights to optimize and forward function\r\nw = torch.tensor(0.0, dtype=torch.float32, requires_grad=True)\r\n\r\ndef forward(x):\r\n return w * x\r\n\r\nprint(f'Prediction before training: f(5) = {forward(5).item():.3f}')\r\n\r\n# 2) Define loss and optimizer\r\nlearning_rate = 0.01\r\nn_iters = 100\r\n\r\n# callable function\r\nloss = nn.MSELoss()\r\n\r\noptimizer = torch.optim.SGD([w], lr=learning_rate)\r\n\r\n# 3) Training loop\r\nfor epoch in range(n_iters):\r\n # predict = forward pass\r\n y_predicted = forward(X)\r\n\r\n # loss\r\n l = loss(Y, y_predicted)\r\n\r\n # calculate gradients = backward pass\r\n l.backward()\r\n\r\n # update weights\r\n optimizer.step()\r\n\r\n # zero the gradients after updating\r\n optimizer.zero_grad()\r\n\r\n if epoch % 10 == 0:\r\n print('epoch ', epoch+1, ': w = ', w, ' loss = ', l)\r\n\r\nprint(f'Prediction after training: f(5) = {forward(5).item():.3f}')"
]
| [
[
"torch.optim.SGD",
"torch.nn.MSELoss",
"torch.tensor"
]
]
|
ganesh314159/manimce | [
"0690508b580a58825721a1bd4206592bb420dd14"
]
| [
"manim/mobject/geometry.py"
]
| [
"r\"\"\"Mobjects that are simple geometric shapes.\n\nExamples\n--------\n\n.. manim:: UsefulAnnotations\n :save_last_frame:\n\n class UsefulAnnotations(Scene):\n def construct(self):\n m0 = Dot()\n m1 = AnnotationDot()\n m2 = LabeledDot(\"ii\")\n m3 = LabeledDot(MathTex(r\"\\alpha\").set_color(ORANGE))\n m4 = CurvedArrow(2*LEFT, 2*RIGHT, radius= -5)\n m5 = CurvedArrow(2*LEFT, 2*RIGHT, radius= 8)\n m6 = CurvedDoubleArrow(ORIGIN, 2*RIGHT)\n\n self.add(m0, m1, m2, m3, m4, m5, m6)\n for i, mobj in enumerate(self.mobjects):\n mobj.shift(DOWN * (i-3))\n\n\"\"\"\n\n__all__ = [\n \"TipableVMobject\",\n \"Arc\",\n \"ArcBetweenPoints\",\n \"CurvedArrow\",\n \"CurvedDoubleArrow\",\n \"Circle\",\n \"Dot\",\n \"AnnotationDot\",\n \"LabeledDot\",\n \"Ellipse\",\n \"AnnularSector\",\n \"Sector\",\n \"Annulus\",\n \"Line\",\n \"DashedLine\",\n \"TangentLine\",\n \"Elbow\",\n \"Arrow\",\n \"Vector\",\n \"DoubleArrow\",\n \"CubicBezier\",\n \"Polygram\",\n \"Polygon\",\n \"RegularPolygram\",\n \"RegularPolygon\",\n \"Star\",\n \"ArcPolygon\",\n \"ArcPolygonFromArcs\",\n \"Triangle\",\n \"ArrowTip\",\n \"Rectangle\",\n \"Square\",\n \"RoundedRectangle\",\n \"Cutout\",\n \"Angle\",\n \"RightAngle\",\n]\n\nimport math\nimport warnings\nfrom typing import Iterable, Optional, Sequence\n\nimport numpy as np\nfrom colour import Color\n\nfrom manim.mobject.opengl_mobject import OpenGLMobject\n\nfrom .. import config, logger\nfrom ..constants import *\nfrom ..mobject.mobject import Mobject\nfrom ..mobject.types.vectorized_mobject import DashedVMobject, VGroup, VMobject\nfrom ..utils.color import *\nfrom ..utils.iterables import adjacent_n_tuples, adjacent_pairs\nfrom ..utils.simple_functions import fdiv\nfrom ..utils.space_ops import (\n angle_between_vectors,\n angle_of_vector,\n compass_directions,\n line_intersection,\n normalize,\n regular_vertices,\n rotate_vector,\n)\nfrom .opengl_compatibility import ConvertToOpenGL\n\n\nclass TipableVMobject(VMobject, metaclass=ConvertToOpenGL):\n \"\"\"\n Meant for shared functionality between Arc and Line.\n Functionality can be classified broadly into these groups:\n\n * Adding, Creating, Modifying tips\n - add_tip calls create_tip, before pushing the new tip\n into the TipableVMobject's list of submobjects\n - stylistic and positional configuration\n\n * Checking for tips\n - Boolean checks for whether the TipableVMobject has a tip\n and a starting tip\n\n * Getters\n - Straightforward accessors, returning information pertaining\n to the TipableVMobject instance's tip(s), its length etc\n\n \"\"\"\n\n def __init__(\n self,\n tip_length=DEFAULT_ARROW_TIP_LENGTH,\n normal_vector=OUT,\n tip_style={},\n **kwargs,\n ):\n self.tip_length = tip_length\n self.normal_vector = normal_vector\n self.tip_style = tip_style\n super().__init__(**kwargs)\n\n # Adding, Creating, Modifying tips\n\n def add_tip(self, tip=None, tip_shape=None, tip_length=None, at_start=False):\n \"\"\"\n Adds a tip to the TipableVMobject instance, recognising\n that the endpoints might need to be switched if it's\n a 'starting tip' or not.\n \"\"\"\n if tip is None:\n tip = self.create_tip(tip_shape, tip_length, at_start)\n else:\n self.position_tip(tip, at_start)\n self.reset_endpoints_based_on_tip(tip, at_start)\n self.asign_tip_attr(tip, at_start)\n self.add(tip)\n return self\n\n def create_tip(self, tip_shape=None, tip_length=None, at_start=False):\n \"\"\"\n Stylises the tip, positions it spatially, and returns\n the newly instantiated tip to the caller.\n \"\"\"\n tip = self.get_unpositioned_tip(tip_shape, tip_length)\n self.position_tip(tip, at_start)\n return tip\n\n def get_unpositioned_tip(self, tip_shape=None, tip_length=None):\n \"\"\"\n Returns a tip that has been stylistically configured,\n but has not yet been given a position in space.\n \"\"\"\n if tip_shape is None:\n tip_shape = ArrowTriangleFilledTip\n if tip_length is None:\n tip_length = self.get_default_tip_length()\n color = self.get_color()\n style = {\"fill_color\": color, \"stroke_color\": color}\n style.update(self.tip_style)\n tip = tip_shape(length=tip_length, **style)\n return tip\n\n def position_tip(self, tip, at_start=False):\n # Last two control points, defining both\n # the end, and the tangency direction\n if at_start:\n anchor = self.get_start()\n handle = self.get_first_handle()\n else:\n handle = self.get_last_handle()\n anchor = self.get_end()\n tip.rotate(angle_of_vector(handle - anchor) - PI - tip.tip_angle)\n tip.shift(anchor - tip.tip_point)\n return tip\n\n def reset_endpoints_based_on_tip(self, tip, at_start):\n if self.get_length() == 0:\n # Zero length, put_start_and_end_on wouldn't work\n return self\n\n if at_start:\n self.put_start_and_end_on(tip.base, self.get_end())\n else:\n self.put_start_and_end_on(self.get_start(), tip.base)\n return self\n\n def asign_tip_attr(self, tip, at_start):\n if at_start:\n self.start_tip = tip\n else:\n self.tip = tip\n return self\n\n # Checking for tips\n\n def has_tip(self):\n return hasattr(self, \"tip\") and self.tip in self\n\n def has_start_tip(self):\n return hasattr(self, \"start_tip\") and self.start_tip in self\n\n # Getters\n\n def pop_tips(self):\n start, end = self.get_start_and_end()\n result = self.get_group_class()()\n if self.has_tip():\n result.add(self.tip)\n self.remove(self.tip)\n if self.has_start_tip():\n result.add(self.start_tip)\n self.remove(self.start_tip)\n self.put_start_and_end_on(start, end)\n return result\n\n def get_tips(self):\n \"\"\"\n Returns a VGroup (collection of VMobjects) containing\n the TipableVMObject instance's tips.\n \"\"\"\n result = self.get_group_class()()\n if hasattr(self, \"tip\"):\n result.add(self.tip)\n if hasattr(self, \"start_tip\"):\n result.add(self.start_tip)\n return result\n\n def get_tip(self):\n \"\"\"Returns the TipableVMobject instance's (first) tip,\n otherwise throws an exception.\"\"\"\n tips = self.get_tips()\n if len(tips) == 0:\n raise Exception(\"tip not found\")\n else:\n return tips[0]\n\n def get_default_tip_length(self):\n return self.tip_length\n\n def get_first_handle(self):\n return self.get_points()[1]\n\n def get_last_handle(self):\n return self.get_points()[-2]\n\n def get_end(self):\n if self.has_tip():\n return self.tip.get_start()\n else:\n return super().get_end()\n\n def get_start(self):\n if self.has_start_tip():\n return self.start_tip.get_start()\n else:\n return super().get_start()\n\n def get_length(self):\n start, end = self.get_start_and_end()\n return np.linalg.norm(start - end)\n\n\nclass Arc(TipableVMobject):\n \"\"\"A circular arc.\"\"\"\n\n def __init__(\n self,\n radius: float = 1.0,\n start_angle=0,\n angle=TAU / 4,\n num_components=9,\n anchors_span_full_range=True,\n arc_center=ORIGIN,\n **kwargs,\n ):\n if radius is None: # apparently None is passed by ArcBetweenPoints\n radius = 1.0\n self.radius = radius\n self.num_components = num_components\n self.anchors_span_full_range = anchors_span_full_range\n self.arc_center = arc_center\n self.start_angle = start_angle\n self.angle = angle\n self._failed_to_get_center = False\n super().__init__(**kwargs)\n\n def generate_points(self):\n self.set_pre_positioned_points()\n self.scale(self.radius, about_point=ORIGIN)\n self.shift(self.arc_center)\n\n # Points are set a bit differently when rendering via OpenGL.\n # TODO: refactor Arc so that only one strategy for setting points\n # has to be used.\n def init_points(self):\n self.set_points(\n Arc.create_quadratic_bezier_points(\n angle=self.angle,\n start_angle=self.start_angle,\n n_components=self.num_components,\n )\n )\n self.scale(self.radius, about_point=ORIGIN)\n self.shift(self.arc_center)\n\n @staticmethod\n def create_quadratic_bezier_points(angle, start_angle=0, n_components=8):\n samples = np.array(\n [\n [np.cos(a), np.sin(a), 0]\n for a in np.linspace(\n start_angle,\n start_angle + angle,\n 2 * n_components + 1,\n )\n ]\n )\n theta = angle / n_components\n samples[1::2] /= np.cos(theta / 2)\n\n points = np.zeros((3 * n_components, 3))\n points[0::3] = samples[0:-1:2]\n points[1::3] = samples[1::2]\n points[2::3] = samples[2::2]\n return points\n\n def set_pre_positioned_points(self):\n anchors = np.array(\n [\n np.cos(a) * RIGHT + np.sin(a) * UP\n for a in np.linspace(\n self.start_angle, self.start_angle + self.angle, self.num_components\n )\n ]\n )\n # Figure out which control points will give the\n # Appropriate tangent lines to the circle\n d_theta = self.angle / (self.num_components - 1.0)\n tangent_vectors = np.zeros(anchors.shape)\n # Rotate all 90 degrees, via (x, y) -> (-y, x)\n tangent_vectors[:, 1] = anchors[:, 0]\n tangent_vectors[:, 0] = -anchors[:, 1]\n # Use tangent vectors to deduce anchors\n handles1 = anchors[:-1] + (d_theta / 3) * tangent_vectors[:-1]\n handles2 = anchors[1:] - (d_theta / 3) * tangent_vectors[1:]\n self.set_anchors_and_handles(anchors[:-1], handles1, handles2, anchors[1:])\n\n def get_arc_center(self, warning=True):\n \"\"\"\n Looks at the normals to the first two\n anchors, and finds their intersection points\n \"\"\"\n # First two anchors and handles\n a1, h1, h2, a2 = self.get_points()[:4]\n\n if np.all(a1 == a2):\n # For a1 and a2 to lie at the same point arc radius\n # must be zero. Thus arc_center will also lie at\n # that point.\n return a1\n # Tangent vectors\n t1 = h1 - a1\n t2 = h2 - a2\n # Normals\n n1 = rotate_vector(t1, TAU / 4)\n n2 = rotate_vector(t2, TAU / 4)\n try:\n return line_intersection(line1=(a1, a1 + n1), line2=(a2, a2 + n2))\n except Exception:\n if warning:\n warnings.warn(\"Can't find Arc center, using ORIGIN instead\")\n self._failed_to_get_center = True\n return np.array(ORIGIN)\n\n def move_arc_center_to(self, point):\n self.shift(point - self.get_arc_center())\n return self\n\n def stop_angle(self):\n return angle_of_vector(self.get_points()[-1] - self.get_arc_center()) % TAU\n\n\nclass ArcBetweenPoints(Arc):\n \"\"\"\n Inherits from Arc and additionally takes 2 points between which the arc is spanned.\n \"\"\"\n\n def __init__(self, start, end, angle=TAU / 4, radius=None, **kwargs):\n if radius is not None:\n self.radius = radius\n if radius < 0:\n sign = -2\n radius *= -1\n else:\n sign = 2\n halfdist = np.linalg.norm(np.array(start) - np.array(end)) / 2\n if radius < halfdist:\n raise ValueError(\n \"\"\"ArcBetweenPoints called with a radius that is\n smaller than half the distance between the points.\"\"\"\n )\n arc_height = radius - math.sqrt(radius ** 2 - halfdist ** 2)\n angle = math.acos((radius - arc_height) / radius) * sign\n\n Arc.__init__(self, radius=radius, angle=angle, **kwargs)\n if angle == 0:\n self.set_points_as_corners([LEFT, RIGHT])\n self.put_start_and_end_on(start, end)\n\n if radius is None:\n center = self.get_arc_center(warning=False)\n if not self._failed_to_get_center:\n self.radius = np.linalg.norm(np.array(start) - np.array(center))\n else:\n self.radius = math.inf\n\n\nclass CurvedArrow(ArcBetweenPoints):\n def __init__(self, start_point, end_point, **kwargs):\n super().__init__(start_point, end_point, **kwargs)\n self.add_tip(tip_shape=kwargs.pop(\"tip_shape\", ArrowTriangleFilledTip))\n\n\nclass CurvedDoubleArrow(CurvedArrow):\n def __init__(self, start_point, end_point, **kwargs):\n if \"tip_shape_end\" in kwargs:\n kwargs[\"tip_shape\"] = kwargs.pop(\"tip_shape_end\")\n tip_shape_start = kwargs.pop(\"tip_shape_start\", ArrowTriangleFilledTip)\n super().__init__(start_point, end_point, **kwargs)\n self.add_tip(at_start=True, tip_shape=tip_shape_start)\n\n\nclass Circle(Arc):\n \"\"\"A circle.\n\n Parameters\n ----------\n color : :class:`~.Colors`, optional\n The color of the shape.\n close_new_points : :class:`bool`, optional\n No purpose.\n anchors_span_full_range : :class:`bool`, optional\n No purpose.\n kwargs : Any\n Additional arguments to be passed to :class:`Arc`\n\n Examples\n --------\n\n .. manim:: CircleExample\n :save_last_frame:\n\n class CircleExample(Scene):\n def construct(self):\n circle_1 = Circle(radius=1.0)\n circle_2 = Circle(radius=1.5, color=GREEN)\n circle_3 = Circle(radius=1.0, color=BLUE_B, fill_opacity=1)\n\n circle_group = Group(circle_1, circle_2, circle_3).arrange(buff=1)\n self.add(circle_group)\n \"\"\"\n\n def __init__(\n self,\n radius: float = None,\n color=RED,\n close_new_points=True,\n anchors_span_full_range=False,\n **kwargs,\n ):\n Arc.__init__(\n self,\n radius=radius,\n start_angle=0,\n angle=TAU,\n color=color,\n close_new_points=close_new_points,\n anchors_span_full_range=anchors_span_full_range,\n **kwargs,\n )\n\n def surround(self, mobject, dim_to_match=0, stretch=False, buffer_factor=1.2):\n \"\"\"Modifies a circle so that it surrounds a given mobject.\n\n Parameters\n ----------\n mobject : :class:`~.Mobject`\n The mobject that the circle will be surrounding.\n dim_to_match : :class:`int`, optional\n buffer_factor : :class:`float`, optional\n Scales the circle with respect to the mobject. A `buffer_factor` < 1 makes the circle smaller than the mobject.\n stretch : :class:`bool`, optional\n Stretches the circle to fit more tightly around the mobject. Note: Does not work with :class:`Line`\n\n Examples\n --------\n\n .. manim:: CircleSurround\n :save_last_frame:\n\n class CircleSurround(Scene):\n def construct(self):\n triangle1 = Triangle()\n circle1 = Circle().surround(triangle1)\n group1 = Group(triangle1,circle1) # treat the two mobjects as one\n\n line2 = Line()\n circle2 = Circle().surround(line2, buffer_factor=2.0)\n group2 = Group(line2,circle2)\n\n # buffer_factor < 1, so the circle is smaller than the square\n square3 = Square()\n circle3 = Circle().surround(square3, buffer_factor=0.5)\n group3 = Group(square3, circle3)\n\n group = Group(group1, group2, group3).arrange(buff=1)\n self.add(group)\n \"\"\"\n\n # Ignores dim_to_match and stretch; result will always be a circle\n # TODO: Perhaps create an ellipse class to handle single-dimension stretching\n\n # Something goes wrong here when surrounding lines?\n # TODO: Figure out and fix\n self.replace(mobject, dim_to_match, stretch)\n\n self.width = np.sqrt(mobject.width ** 2 + mobject.height ** 2)\n return self.scale(buffer_factor)\n\n def point_at_angle(self, angle):\n \"\"\"Returns the position of a point on the circle.\n\n Parameters\n ----------\n angle : class: `float`\n The angle of the point along the circle in radians.\n\n Examples\n --------\n\n .. manim:: PointAtAngleExample\n :save_last_frame:\n\n class PointAtAngleExample(Scene):\n def construct(self):\n circle = Circle(radius=2.0)\n p1 = circle.point_at_angle(PI/2)\n p2 = circle.point_at_angle(270*DEGREES)\n\n s1 = Square(side_length=0.25).move_to(p1)\n s2 = Square(side_length=0.25).move_to(p2)\n self.add(circle, s1, s2)\n\n Returns\n -------\n :class:`numpy.ndarray`\n The location of the point along the circle's circumference.\n \"\"\"\n\n start_angle = angle_of_vector(self.get_points()[0] - self.get_center())\n return self.point_from_proportion((angle - start_angle) / TAU)\n\n\nclass Dot(Circle):\n \"\"\"A circle with a very small radius.\n\n Parameters\n ----------\n point : Union[:class:`list`, :class:`numpy.ndarray`], optional\n The location of the dot.\n radius : Optional[:class:`float`]\n The radius of the dot.\n stroke_width : :class:`float`, optional\n The thickness of the outline of the dot.\n fill_opacity : :class:`float`, optional\n The opacity of the dot's fill_colour\n color : :class:`~.Colors`, optional\n The color of the dot.\n kwargs : Any\n Additional arguments to be passed to :class:`Circle`\n\n Examples\n --------\n\n .. manim:: DotExample\n :save_last_frame:\n\n class DotExample(Scene):\n def construct(self):\n dot1 = Dot(point=LEFT, radius=0.08)\n dot2 = Dot(point=ORIGIN)\n dot3 = Dot(point=RIGHT)\n self.add(dot1,dot2,dot3)\n \"\"\"\n\n def __init__(\n self,\n point=ORIGIN,\n radius: float = DEFAULT_DOT_RADIUS,\n stroke_width=0,\n fill_opacity=1.0,\n color=WHITE,\n **kwargs,\n ):\n super().__init__(\n arc_center=point,\n radius=radius,\n stroke_width=stroke_width,\n fill_opacity=fill_opacity,\n color=color,\n **kwargs,\n )\n\n\nclass AnnotationDot(Dot):\n \"\"\"\n A dot with bigger radius and bold stroke to annotate scenes.\n \"\"\"\n\n def __init__(\n self,\n radius: float = DEFAULT_DOT_RADIUS * 1.3,\n stroke_width=5,\n stroke_color=WHITE,\n fill_color=BLUE,\n **kwargs,\n ):\n super().__init__(\n radius=radius,\n stroke_width=stroke_width,\n stroke_color=stroke_color,\n fill_color=fill_color,\n **kwargs,\n )\n\n\nclass LabeledDot(Dot):\n \"\"\"A :class:`Dot` containing a label in its center.\n\n Parameters\n ----------\n label : Union[:class:`str`, :class:`~.SingleStringMathTex`, :class:`~.Text`, :class:`~.Tex`]\n The label of the :class:`Dot`. This is rendered as :class:`~.MathTex`\n by default (i.e., when passing a :class:`str`), but other classes\n representing rendered strings like :class:`~.Text` or :class:`~.Tex`\n can be passed as well.\n\n radius : :class:`float`\n The radius of the :class:`Dot`. If ``None`` (the default), the radius\n is calculated based on the size of the ``label``.\n\n Examples\n --------\n\n .. manim:: SeveralLabeledDots\n :save_last_frame:\n\n class SeveralLabeledDots(Scene):\n def construct(self):\n sq = Square(fill_color=RED, fill_opacity=1)\n self.add(sq)\n dot1 = LabeledDot(Tex(\"42\", color=RED))\n dot2 = LabeledDot(MathTex(\"a\", color=GREEN))\n dot3 = LabeledDot(Text(\"ii\", color=BLUE))\n dot4 = LabeledDot(\"3\")\n dot1.next_to(sq, UL)\n dot2.next_to(sq, UR)\n dot3.next_to(sq, DL)\n dot4.next_to(sq, DR)\n self.add(dot1, dot2, dot3, dot4)\n \"\"\"\n\n def __init__(self, label, radius=None, **kwargs) -> None:\n if isinstance(label, str):\n from manim import MathTex\n\n rendered_label = MathTex(label, color=BLACK)\n else:\n rendered_label = label\n\n if radius is None:\n radius = 0.1 + max(rendered_label.width, rendered_label.height) / 2\n Dot.__init__(self, radius=radius, **kwargs)\n rendered_label.move_to(self.get_center())\n self.add(rendered_label)\n\n\nclass Ellipse(Circle):\n \"\"\"A circular shape; oval, circle.\n\n Parameters\n ----------\n width : :class:`float`, optional\n The horizontal width of the ellipse.\n height : :class:`float`, optional\n The vertical height of the ellipse.\n kwargs : Any\n Additional arguments to be passed to :class:`Circle`\n\n Examples\n --------\n\n .. manim:: EllipseExample\n :save_last_frame:\n\n class EllipseExample(Scene):\n def construct(self):\n ellipse_1 = Ellipse(width=2.0, height=4.0, color=BLUE_B)\n ellipse_2 = Ellipse(width=4.0, height=1.0, color=BLUE_D)\n ellipse_group = Group(ellipse_1,ellipse_2).arrange(buff=1)\n self.add(ellipse_group)\n \"\"\"\n\n def __init__(self, width=2, height=1, **kwargs):\n super().__init__(**kwargs)\n self.stretch_to_fit_width(width)\n self.stretch_to_fit_height(height)\n\n\nclass AnnularSector(Arc):\n def __init__(\n self,\n inner_radius=1,\n outer_radius=2,\n angle=TAU / 4,\n start_angle=0,\n fill_opacity=1,\n stroke_width=0,\n color=WHITE,\n **kwargs,\n ):\n self.inner_radius = inner_radius\n self.outer_radius = outer_radius\n super().__init__(\n start_angle=start_angle,\n angle=angle,\n fill_opacity=fill_opacity,\n stroke_width=stroke_width,\n color=color,\n **kwargs,\n )\n\n def generate_points(self):\n inner_arc, outer_arc = [\n Arc(\n start_angle=self.start_angle,\n angle=self.angle,\n radius=radius,\n arc_center=self.arc_center,\n )\n for radius in (self.inner_radius, self.outer_radius)\n ]\n outer_arc.reverse_points()\n self.append_points(inner_arc.get_points())\n self.add_line_to(outer_arc.get_points()[0])\n self.append_points(outer_arc.get_points())\n self.add_line_to(inner_arc.get_points()[0])\n\n init_points = generate_points\n\n\nclass Sector(AnnularSector):\n def __init__(self, outer_radius=1, inner_radius=0, **kwargs):\n super().__init__(inner_radius=inner_radius, outer_radius=outer_radius, **kwargs)\n\n\nclass Annulus(Circle):\n def __init__(\n self,\n inner_radius=1,\n outer_radius=2,\n fill_opacity=1,\n stroke_width=0,\n color=WHITE,\n mark_paths_closed=False,\n **kwargs,\n ):\n self.mark_paths_closed = mark_paths_closed # is this even used?\n self.inner_radius = inner_radius\n self.outer_radius = outer_radius\n super().__init__(\n fill_opacity=fill_opacity, stroke_width=stroke_width, color=color, **kwargs\n )\n\n def generate_points(self):\n self.radius = self.outer_radius\n outer_circle = Circle(radius=self.outer_radius)\n inner_circle = Circle(radius=self.inner_radius)\n inner_circle.reverse_points()\n self.append_points(outer_circle.get_points())\n self.append_points(inner_circle.get_points())\n self.shift(self.arc_center)\n\n init_points = generate_points\n\n\nclass Line(TipableVMobject):\n def __init__(self, start=LEFT, end=RIGHT, buff=0, path_arc=None, **kwargs):\n self.dim = 3\n self.buff = buff\n self.path_arc = path_arc\n self.set_start_and_end_attrs(start, end)\n super().__init__(**kwargs)\n\n def generate_points(self):\n self.set_points_by_ends(\n start=self.start, end=self.end, buff=self.buff, path_arc=self.path_arc\n )\n\n def set_points_by_ends(self, start, end, buff=0, path_arc=0):\n if path_arc:\n arc = ArcBetweenPoints(self.start, self.end, angle=self.path_arc)\n self.set_points(arc.get_points())\n else:\n self.set_points_as_corners([start, end])\n\n self.account_for_buff(buff)\n\n init_points = generate_points\n\n def set_path_arc(self, new_value):\n self.path_arc = new_value\n self.init_points()\n\n def account_for_buff(self, buff):\n if buff == 0:\n return\n #\n if self.path_arc == 0:\n length = self.get_length()\n else:\n length = self.get_arc_length()\n #\n if length < 2 * buff:\n return\n buff_proportion = buff / length\n self.pointwise_become_partial(self, buff_proportion, 1 - buff_proportion)\n return self\n\n def set_start_and_end_attrs(self, start, end):\n # If either start or end are Mobjects, this\n # gives their centers\n rough_start = self.pointify(start)\n rough_end = self.pointify(end)\n vect = normalize(rough_end - rough_start)\n # Now that we know the direction between them,\n # we can find the appropriate boundary point from\n # start and end, if they're mobjects\n self.start = self.pointify(start, vect)\n self.end = self.pointify(end, -vect)\n\n def pointify(self, mob_or_point, direction=None):\n if isinstance(mob_or_point, (Mobject, OpenGLMobject)):\n mob = mob_or_point\n if direction is None:\n return mob.get_center()\n else:\n return mob.get_boundary_point(direction)\n return np.array(mob_or_point)\n\n def put_start_and_end_on(self, start: Sequence[float], end: Sequence[float]):\n \"\"\"Sets starts and end coordinates of a line.\n Examples\n --------\n .. manim:: LineExample\n\n class LineExample(Scene):\n def construct(self):\n d = VGroup()\n for i in range(0,10):\n d.add(Dot())\n d.arrange_in_grid(buff=1)\n self.add(d)\n l= Line(d[0], d[1])\n self.add(l)\n self.wait()\n l.put_start_and_end_on(d[1].get_center(), d[2].get_center())\n self.wait()\n l.put_start_and_end_on(d[4].get_center(), d[7].get_center())\n self.wait()\n \"\"\"\n curr_start, curr_end = self.get_start_and_end()\n if np.all(curr_start == curr_end):\n # TODO, any problems with resetting\n # these attrs?\n self.start = start\n self.end = end\n self.generate_points()\n return super().put_start_and_end_on(start, end)\n\n def get_vector(self):\n return self.get_end() - self.get_start()\n\n def get_unit_vector(self):\n return normalize(self.get_vector())\n\n def get_angle(self):\n return angle_of_vector(self.get_vector())\n\n def get_projection(self, point: Sequence[float]) -> Sequence[float]:\n \"\"\"Returns the projection of a point onto a line.\n\n Parameters\n ----------\n point\n The point to which the line is projected.\n\n \"\"\"\n\n start = self.get_start()\n end = self.get_end()\n unit_vect = normalize(end - start)\n return start + np.dot(point - start, unit_vect) * unit_vect\n\n def get_slope(self):\n return np.tan(self.get_angle())\n\n def set_angle(self, angle, about_point=None):\n if about_point is None:\n about_point = self.get_start()\n\n self.rotate(\n angle - self.get_angle(),\n about_point=about_point,\n )\n\n return self\n\n def set_length(self, length):\n return self.scale(length / self.get_length())\n\n def set_opacity(self, opacity, family=True):\n # Overwrite default, which would set\n # the fill opacity\n self.set_stroke(opacity=opacity)\n if family:\n for sm in self.submobjects:\n sm.set_opacity(opacity, family)\n return self\n\n\nclass DashedLine(Line):\n \"\"\"A dashed :class:`Line`.\n\n Parameters\n ----------\n args : Any\n Arguments to be passed to :class:`Line`\n dash_length : :class:`float`, optional\n The length of each individual dash of the line.\n dash_spacing : Optional[:class:`float`]\n No purpose.\n positive_space_ratio : :class:`float`, optional\n The ratio of empty space to dash space. Range of 0-1.\n kwargs : Any\n Additional arguments to be passed to :class:`Line`\n\n Examples\n --------\n .. manim:: DashedLineExample\n :save_last_frame:\n\n class DashedLineExample(Scene):\n def construct(self):\n # dash_length increased\n dashed_1 = DashedLine(config.left_side, config.right_side, dash_length=2.0).shift(UP*2)\n # normal\n dashed_2 = DashedLine(config.left_side, config.right_side)\n # positive_space_ratio decreased\n dashed_3 = DashedLine(config.left_side, config.right_side, positive_space_ratio=0.1).shift(DOWN*2)\n self.add(dashed_1, dashed_2, dashed_3)\n\n See Also\n --------\n :class:`~.DashedVMobject`\n \"\"\"\n\n def __init__(\n self,\n *args,\n dash_length=DEFAULT_DASH_LENGTH,\n dash_spacing=None,\n positive_space_ratio=0.5,\n **kwargs,\n ):\n self.dash_length = dash_length\n self.dash_spacing = (dash_spacing,)\n self.positive_space_ratio = positive_space_ratio\n super().__init__(*args, **kwargs)\n dashes = DashedVMobject(\n self,\n num_dashes=self.calculate_num_dashes(),\n positive_space_ratio=positive_space_ratio,\n )\n self.clear_points()\n self.add(*dashes)\n\n def calculate_num_dashes(self) -> int:\n \"\"\"Returns the number of dashes in the dashed line.\n\n Examples\n --------\n ::\n\n >>> DashedLine().calculate_num_dashes()\n 20\n \"\"\"\n\n try:\n full_length = self.dash_length / self.positive_space_ratio\n return int(np.ceil(self.get_length() / full_length))\n except ZeroDivisionError:\n return 1\n\n def calculate_positive_space_ratio(self):\n return fdiv(self.dash_length, self.dash_length + self.dash_spacing)\n\n def get_start(self) -> np.ndarray:\n \"\"\"Returns the start point of the line.\n\n Examples\n --------\n ::\n\n >>> DashedLine().get_start()\n array([-1., 0., 0.])\n \"\"\"\n\n if len(self.submobjects) > 0:\n return self.submobjects[0].get_start()\n else:\n return Line.get_start(self)\n\n def get_end(self) -> np.ndarray:\n \"\"\"Returns the end point of the line.\n\n Examples\n --------\n ::\n\n >>> DashedLine().get_end()\n array([0.99871795, 0. , 0. ])\n \"\"\"\n\n if len(self.submobjects) > 0:\n return self.submobjects[-1].get_end()\n else:\n return super().get_end()\n\n def get_first_handle(self) -> np.ndarray:\n \"\"\"Returns the point of the first handle.\n\n Examples\n --------\n ::\n\n >>> DashedLine().get_first_handle()\n array([-0.98333333, 0. , 0. ])\n \"\"\"\n\n return self.submobjects[0].get_points()[1]\n\n def get_last_handle(self) -> np.ndarray:\n \"\"\"Returns the point of the last handle.\n\n Examples\n --------\n ::\n\n >>> DashedLine().get_last_handle()\n array([0.98205128, 0. , 0. ])\n \"\"\"\n\n return self.submobjects[-1].get_points()[-2]\n\n\nclass TangentLine(Line):\n \"\"\"Constructs a line tangent to a :class:`~.VMobject` at a specific point.\n\n Parameters\n ----------\n vmob : :class:`~.VMobject`\n The VMobject on which the tangent line is drawn.\n alpha : :class:`float`\n How far along the shape that the line will be constructed. range: 0-1.\n length : :class:`float`, optional\n Length of the tangent line.\n d_alpha: :class:`float`, optional\n The ``dx`` value\n kwargs : Any\n Additional arguments to be passed to :class:`Line`\n\n Examples\n --------\n\n .. manim:: TangentLineExample\n :save_last_frame:\n\n class TangentLineExample(Scene):\n def construct(self):\n circle = Circle(radius=2)\n line_1 = TangentLine(circle, alpha=0.0, length=4, color=BLUE_D) # right\n line_2 = TangentLine(circle, alpha=0.4, length=4, color=GREEN) # top left\n self.add(circle, line_1, line_2)\n\n See Also\n --------\n :meth:`~.VMobject.point_from_proportion`\n \"\"\"\n\n def __init__(self, vmob, alpha, length=1, d_alpha=1e-6, **kwargs):\n self.length = length\n self.d_alpha = d_alpha\n da = self.d_alpha\n a1 = np.clip(alpha - da, 0, 1)\n a2 = np.clip(alpha + da, 0, 1)\n super().__init__(\n vmob.point_from_proportion(a1), vmob.point_from_proportion(a2), **kwargs\n )\n self.scale(self.length / self.get_length())\n\n\nclass Elbow(VMobject, metaclass=ConvertToOpenGL):\n \"\"\"Two lines that create a right angle about each other: L-shape.\n\n Parameters\n ----------\n width : :class:`float`, optional\n The length of the elbow's sides.\n angle : :class:`float`, optional\n The rotation of the elbow.\n kwargs : Any\n Additional arguments to be passed to :class:`~.VMobject`\n\n Examples\n --------\n\n .. manim:: ElbowExample\n :save_last_frame:\n\n class ElbowExample(Scene):\n def construct(self):\n elbow_1 = Elbow()\n elbow_2 = Elbow(width=2.0)\n elbow_3 = Elbow(width=2.0, angle=5*PI/4)\n\n elbow_group = Group(elbow_1, elbow_2, elbow_3).arrange(buff=1)\n self.add(elbow_group)\n\n See Also\n --------\n :class:`RightAngle`\n \"\"\"\n\n def __init__(self, width=0.2, angle=0, **kwargs):\n self.angle = angle\n super().__init__(**kwargs)\n self.set_points_as_corners([UP, UP + RIGHT, RIGHT])\n self.scale_to_fit_width(width, about_point=ORIGIN)\n self.rotate(self.angle, about_point=ORIGIN)\n\n\nclass Arrow(Line):\n \"\"\"An arrow.\n\n Parameters\n ----------\n args : Any\n Arguments to be passed to :class:`Line`.\n stroke_width : :class:`float`, optional\n The thickness of the arrow. Influenced by :attr:`max_stroke_width_to_length_ratio`.\n buff : :class:`float`, optional\n The distance of the arrow from its start and end points.\n max_tip_length_to_length_ratio : :class:`float`, optional\n :attr:`tip_length` scales with the length of the arrow. Increasing this ratio raises the max value of :attr:`tip_length`.\n max_stroke_width_to_length_ratio : :class:`float`, optional\n :attr:`stroke_width` scales with the length of the arrow. Increasing this ratio ratios the max value of :attr:`stroke_width`.\n preserve_tip_size_when_scaling : :class:`bool`, optional\n No purpose.\n kwargs : Any\n Additional arguments to be passed to :class:`Line`.\n\n Examples\n --------\n\n .. manim:: ArrowExample\n :save_last_frame:\n\n from manim.mobject.geometry import ArrowSquareTip\n class ArrowExample(Scene):\n def construct(self):\n arrow_1 = Arrow(start=RIGHT, end=LEFT, color=GOLD)\n arrow_2 = Arrow(start=RIGHT, end=LEFT, color=GOLD, tip_shape=ArrowSquareTip).shift(DOWN)\n g1 = Group(arrow_1, arrow_2)\n\n # the effect of buff\n square = Square(color=MAROON_A)\n arrow_3 = Arrow(start=LEFT, end=RIGHT)\n arrow_4 = Arrow(start=LEFT, end=RIGHT, buff=0).next_to(arrow_1, UP)\n g2 = Group(arrow_3, arrow_4, square)\n\n # a shorter arrow has a shorter tip and smaller stroke width\n arrow_5 = Arrow(start=ORIGIN, end=config.top).shift(LEFT * 4)\n arrow_6 = Arrow(start=config.top + DOWN, end=config.top).shift(LEFT * 3)\n g3 = Group(arrow_5, arrow_6)\n\n self.add(Group(g1, g2, g3).arrange(buff=2))\n\n See Also\n --------\n :class:`ArrowTip`\n :class:`CurvedArrow`\n \"\"\"\n\n def __init__(\n self,\n *args,\n stroke_width=6,\n buff=MED_SMALL_BUFF,\n max_tip_length_to_length_ratio=0.25,\n max_stroke_width_to_length_ratio=5,\n preserve_tip_size_when_scaling=True,\n **kwargs,\n ):\n self.max_tip_length_to_length_ratio = max_tip_length_to_length_ratio\n self.max_stroke_width_to_length_ratio = max_stroke_width_to_length_ratio\n self.preserve_tip_size_when_scaling = (\n preserve_tip_size_when_scaling # is this used anywhere\n )\n tip_shape = kwargs.pop(\"tip_shape\", ArrowTriangleFilledTip)\n super().__init__(*args, buff=buff, stroke_width=stroke_width, **kwargs)\n # TODO, should this be affected when\n # Arrow.set_stroke is called?\n self.initial_stroke_width = self.stroke_width\n self.add_tip(tip_shape=tip_shape)\n self.set_stroke_width_from_length()\n\n def scale(self, factor, scale_tips=False, **kwargs):\n r\"\"\"Scale an arrow, but keep stroke width and arrow tip size fixed.\n\n See Also\n --------\n :meth:`~.Mobject.scale`\n\n Examples\n --------\n ::\n\n >>> arrow = Arrow(np.array([-1, -1, 0]), np.array([1, 1, 0]), buff=0)\n >>> scaled_arrow = arrow.scale(2)\n >>> np.round(scaled_arrow.get_start_and_end(), 8) + 0\n array([[-2., -2., 0.],\n [ 2., 2., 0.]])\n >>> arrow.tip.length == scaled_arrow.tip.length\n True\n\n Manually scaling the object using the default method\n :meth:`~.Mobject.scale` does not have the same properties::\n\n >>> new_arrow = Arrow(np.array([-1, -1, 0]), np.array([1, 1, 0]), buff=0)\n >>> another_scaled_arrow = VMobject.scale(new_arrow, 2)\n >>> another_scaled_arrow.tip.length == arrow.tip.length\n False\n\n \"\"\"\n if self.get_length() == 0:\n return self\n\n if scale_tips:\n super().scale(factor, **kwargs)\n self.set_stroke_width_from_length()\n return self\n\n has_tip = self.has_tip()\n has_start_tip = self.has_start_tip()\n if has_tip or has_start_tip:\n old_tips = self.pop_tips()\n\n super().scale(factor, **kwargs)\n self.set_stroke_width_from_length()\n\n if has_tip:\n self.add_tip(tip=old_tips[0])\n if has_start_tip:\n self.add_tip(tip=old_tips[1], at_start=True)\n return self\n\n def get_normal_vector(self) -> np.ndarray:\n \"\"\"Returns the normal of a vector.\n\n Examples\n --------\n ::\n\n >>> Arrow().get_normal_vector() + 0. # add 0. to avoid negative 0 in output\n array([ 0., 0., -1.])\n \"\"\"\n\n p0, p1, p2 = self.tip.get_start_anchors()[:3]\n return normalize(np.cross(p2 - p1, p1 - p0))\n\n def reset_normal_vector(self):\n \"\"\"Resets the normal of a vector\"\"\"\n self.normal_vector = self.get_normal_vector()\n return self\n\n def get_default_tip_length(self) -> float:\n \"\"\"Returns the default tip_length of the arrow.\n\n Examples\n --------\n\n ::\n\n >>> Arrow().get_default_tip_length()\n 0.35\n \"\"\"\n\n max_ratio = self.max_tip_length_to_length_ratio\n return min(self.tip_length, max_ratio * self.get_length())\n\n def set_stroke_width_from_length(self):\n \"\"\"Used internally. Sets stroke width based on length.\"\"\"\n max_ratio = self.max_stroke_width_to_length_ratio\n if config.renderer == \"opengl\":\n self.set_stroke(\n width=min(self.initial_stroke_width, max_ratio * self.get_length()),\n recurse=False,\n )\n else:\n self.set_stroke(\n width=min(self.initial_stroke_width, max_ratio * self.get_length()),\n family=False,\n )\n return self\n\n\nclass Vector(Arrow):\n \"\"\"A vector specialized for use in graphs.\n\n Parameters\n ----------\n direction : Union[:class:`list`, :class:`numpy.ndarray`]\n The direction of the arrow.\n buff : :class:`float`\n The distance of the vector from its endpoints.\n kwargs : Any\n Additional arguments to be passed to :class:`Arrow`\n\n Examples\n --------\n\n .. manim:: VectorExample\n :save_last_frame:\n\n class VectorExample(Scene):\n def construct(self):\n plane = NumberPlane()\n vector_1 = Vector([1,2])\n vector_2 = Vector([-5,-2])\n self.add(plane, vector_1, vector_2)\n \"\"\"\n\n def __init__(self, direction=RIGHT, buff=0, **kwargs):\n self.buff = buff\n if len(direction) == 2:\n direction = np.hstack([direction, 0])\n\n super().__init__(ORIGIN, direction, buff=buff, **kwargs)\n\n def coordinate_label(\n self, integer_labels: bool = True, n_dim: int = 2, color: str = WHITE\n ):\n \"\"\"Creates a label based on the coordinates of the vector.\n\n Parameters\n ----------\n integer_labels\n Whether or not to round the coordinates to integers.\n n_dim\n The number of dimensions of the vector.\n color\n The color of the label.\n\n Examples\n --------\n\n .. manim VectorCoordinateLabel\n :save_last_frame:\n\n class VectorCoordinateLabel(Scene):\n def construct(self):\n plane = NumberPlane()\n\n vect_1 = Vector([1, 2])\n vect_2 = Vector([-3, -2])\n label_1 = vect1.coordinate_label()\n label_2 = vect2.coordinate_label(color=YELLOW)\n\n self.add(plane, vect_1, vect_2, label_1, label_2)\n \"\"\"\n # avoiding circular imports\n from .matrix import Matrix\n\n vect = np.array(self.get_end())\n if integer_labels:\n vect = np.round(vect).astype(int)\n vect = vect[:n_dim]\n vect = vect.reshape((n_dim, 1))\n\n label = Matrix(vect)\n label.scale(LARGE_BUFF - 0.2)\n\n shift_dir = np.array(self.get_end())\n if shift_dir[0] >= 0: # Pointing right\n shift_dir -= label.get_left() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * LEFT\n else: # Pointing left\n shift_dir -= label.get_right() + DEFAULT_MOBJECT_TO_MOBJECT_BUFFER * RIGHT\n label.shift(shift_dir)\n label.set_color(color)\n return label\n\n\nclass DoubleArrow(Arrow):\n \"\"\"An arrow with tips on both ends.\n\n Parameters\n ----------\n args : Any\n Arguments to be passed to :class:`Arrow`\n kwargs : Any\n Additional arguments to be passed to :class:`Arrow`\n\n Examples\n --------\n\n .. manim:: DoubleArrowExample\n :save_last_frame:\n\n from manim.mobject.geometry import ArrowCircleFilledTip\n class DoubleArrowExample(Scene):\n def construct(self):\n circle = Circle(radius=2.0)\n d_arrow = DoubleArrow(start=circle.get_left(), end=circle.get_right())\n d_arrow_2 = DoubleArrow(tip_shape_end=ArrowCircleFilledTip, tip_shape_start=ArrowCircleFilledTip)\n group = Group(Group(circle, d_arrow), d_arrow_2).arrange(UP, buff=1)\n self.add(group)\n\n See Also\n --------\n :class:`ArrowTip`\n :class:`CurvedDoubleArrow`\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n if \"tip_shape_end\" in kwargs:\n kwargs[\"tip_shape\"] = kwargs.pop(\"tip_shape_end\")\n tip_shape_start = kwargs.pop(\"tip_shape_start\", ArrowTriangleFilledTip)\n super().__init__(*args, **kwargs)\n self.add_tip(at_start=True, tip_shape=tip_shape_start)\n\n\nclass CubicBezier(VMobject, metaclass=ConvertToOpenGL):\n \"\"\"\n Example\n -------\n\n .. manim:: BezierSplineExample\n :save_last_frame:\n\n class BezierSplineExample(Scene):\n def construct(self):\n p1 = np.array([-3, 1, 0])\n p1b = p1 + [1, 0, 0]\n d1 = Dot(point=p1).set_color(BLUE)\n l1 = Line(p1, p1b)\n p2 = np.array([3, -1, 0])\n p2b = p2 - [1, 0, 0]\n d2 = Dot(point=p2).set_color(RED)\n l2 = Line(p2, p2b)\n bezier = CubicBezier(p1b, p1b + 3 * RIGHT, p2b - 3 * RIGHT, p2b)\n self.add(l1, d1, l2, d2, bezier)\n\n \"\"\"\n\n def __init__(self, start_anchor, start_handle, end_handle, end_anchor, **kwargs):\n super().__init__(**kwargs)\n self.add_cubic_bezier_curve(start_anchor, start_handle, end_handle, end_anchor)\n\n\nclass Polygram(VMobject, metaclass=ConvertToOpenGL):\n \"\"\"A generalized :class:`Polygon`, allowing for disconnected sets of edges.\n\n Parameters\n ----------\n vertex_groups\n The groups of vertices making up the :class:`Polygram`.\n\n The first vertex in each group is repeated to close the shape.\n Each point must be 3-dimensional: ``[x,y,z]``\n color\n The color of the :class:`Polygram`.\n kwargs\n Forwarded to the parent constructor.\n\n Examples\n --------\n .. manim:: PolygramExample\n\n import numpy as np\n\n class PolygramExample(Scene):\n def construct(self):\n hexagram = Polygram(\n [[0, 2, 0], [-np.sqrt(3), -1, 0], [np.sqrt(3), -1, 0]],\n [[-np.sqrt(3), 1, 0], [0, -2, 0], [np.sqrt(3), 1, 0]],\n )\n self.add(hexagram)\n\n dot = Dot()\n self.play(MoveAlongPath(dot, hexagram), run_time=5, rate_func=linear)\n self.remove(dot)\n self.wait()\n\n\n \"\"\"\n\n def __init__(self, *vertex_groups: Iterable[Sequence[float]], color=BLUE, **kwargs):\n super().__init__(color=color, **kwargs)\n\n for vertices in vertex_groups:\n # Allow any iterable to be passed\n vertices = iter(vertices)\n first_vertex = next(vertices)\n first_vertex = np.array(first_vertex)\n\n self.start_new_path(first_vertex)\n self.add_points_as_corners(\n [*[np.array(vertex) for vertex in vertices], first_vertex]\n )\n\n def get_vertices(self) -> np.ndarray:\n \"\"\"Gets the vertices of the :class:`Polygram`.\n\n Returns\n -------\n :class:`numpy.ndarray`\n The vertices of the :class:`Polygram`.\n\n Examples\n --------\n ::\n\n >>> sq = Square()\n >>> sq.get_vertices()\n array([[ 1., 1., 0.],\n [-1., 1., 0.],\n [-1., -1., 0.],\n [ 1., -1., 0.]])\n \"\"\"\n\n return self.get_start_anchors()\n\n def get_vertex_groups(self) -> np.ndarray:\n \"\"\"Gets the vertex groups of the :class:`Polygram`.\n\n Returns\n -------\n :class:`numpy.ndarray`\n The vertex groups of the :class:`Polygram`.\n\n Examples\n --------\n ::\n\n >>> poly = Polygram([ORIGIN, RIGHT, UP], [LEFT, LEFT + UP, 2 * LEFT])\n >>> poly.get_vertex_groups()\n array([[[ 0., 0., 0.],\n [ 1., 0., 0.],\n [ 0., 1., 0.]],\n <BLANKLINE>\n [[-1., 0., 0.],\n [-1., 1., 0.],\n [-2., 0., 0.]]])\n \"\"\"\n\n vertex_groups = []\n\n group = []\n for start, end in zip(self.get_start_anchors(), self.get_end_anchors()):\n group.append(start)\n\n if self.consider_points_equals(end, group[0]):\n vertex_groups.append(group)\n group = []\n\n return np.array(vertex_groups)\n\n def round_corners(self, radius: float = 0.5):\n \"\"\"Rounds off the corners of the :class:`Polygram`.\n\n Parameters\n ----------\n radius\n The curvature of the corners of the :class:`Polygram`.\n\n Examples\n --------\n\n .. manim:: PolygramRoundCorners\n :save_last_frame:\n\n class PolygramRoundCorners(Scene):\n def construct(self):\n star = Star(outer_radius=2)\n\n shapes = VGroup(star)\n shapes.add(star.copy().round_corners(radius=0.1))\n shapes.add(star.copy().round_corners(radius=0.25))\n\n shapes.arrange(RIGHT)\n self.add(shapes)\n\n See Also\n --------\n :class:`RoundedRectangle`\n \"\"\"\n\n if radius == 0:\n return self\n\n new_points = []\n\n for vertices in self.get_vertex_groups():\n arcs = []\n for v1, v2, v3 in adjacent_n_tuples(vertices, 3):\n vect1 = v2 - v1\n vect2 = v3 - v2\n unit_vect1 = normalize(vect1)\n unit_vect2 = normalize(vect2)\n\n angle = angle_between_vectors(vect1, vect2)\n # Negative radius gives concave curves\n angle *= np.sign(radius)\n\n # Distance between vertex and start of the arc\n cut_off_length = radius * np.tan(angle / 2)\n\n # Determines counterclockwise vs. clockwise\n sign = np.sign(np.cross(vect1, vect2)[2])\n\n arc = ArcBetweenPoints(\n v2 - unit_vect1 * cut_off_length,\n v2 + unit_vect2 * cut_off_length,\n angle=sign * angle,\n )\n arcs.append(arc)\n\n # To ensure that we loop through starting with last\n arcs = [arcs[-1], *arcs[:-1]]\n for arc1, arc2 in adjacent_pairs(arcs):\n new_points.extend(arc1.get_points())\n\n line = Line(arc1.get_end(), arc2.get_start())\n\n # Make sure anchors are evenly distributed\n len_ratio = line.get_length() / arc1.get_arc_length()\n\n line.insert_n_curves(int(arc1.get_num_curves() * len_ratio))\n\n new_points.extend(line.get_points())\n\n self.set_points(new_points)\n\n return self\n\n\nclass Polygon(Polygram):\n \"\"\"A shape consisting of one closed loop of vertices.\n\n Parameters\n ----------\n vertices\n The vertices of the :class:`Polygon`.\n kwargs\n Forwarded to the parent constructor.\n\n Examples\n --------\n\n .. manim:: PolygonExample\n :save_last_frame:\n\n class PolygonExample(Scene):\n def construct(self):\n isosceles = Polygon([-5, 1.5, 0], [-2, 1.5, 0], [-3.5, -2, 0])\n position_list = [\n [4, 1, 0], # middle right\n [4, -2.5, 0], # bottom right\n [0, -2.5, 0], # bottom left\n [0, 3, 0], # top left\n [2, 1, 0], # middle\n [4, 3, 0], # top right\n ]\n square_and_triangles = Polygon(*position_list, color=PURPLE_B)\n self.add(isosceles, square_and_triangles)\n \"\"\"\n\n def __init__(self, *vertices: Sequence[float], **kwargs):\n super().__init__(vertices, **kwargs)\n\n\nclass RegularPolygram(Polygram):\n \"\"\"A :class:`Polygram` with regularly spaced vertices.\n\n Parameters\n ----------\n num_vertices\n The number of vertices.\n density\n The density of the :class:`RegularPolygram`.\n\n Can be thought of as how many vertices to hop\n to draw a line between them. Every ``density``-th\n vertex is connected.\n radius\n The radius of the circle that the vertices are placed on.\n start_angle\n The angle the vertices start at; the rotation of\n the :class:`RegularPolygram`.\n kwargs\n Forwarded to the parent constructor.\n\n Examples\n --------\n .. manim:: RegularPolygramExample\n :save_last_frame:\n\n class RegularPolygramExample(Scene):\n def construct(self):\n pentagram = RegularPolygram(5, radius=2)\n self.add(pentagram)\n \"\"\"\n\n def __init__(\n self,\n num_vertices: int,\n *,\n density: int = 2,\n radius: float = 1,\n start_angle: Optional[float] = None,\n **kwargs,\n ):\n # Regular polygrams can be expressed by the number of their vertices\n # and their density. This relation can be expressed as its Schlรคfli\n # symbol: {num_vertices/density}.\n #\n # For instance, a pentagon can be expressed as {5/1} or just {5}.\n # A pentagram, however, can be expressed as {5/2}.\n # A hexagram *would* be expressed as {6/2}, except that 6 and 2\n # are not coprime, and it can be simplified to 2{3}, which corresponds\n # to the fact that a hexagram is actually made up of 2 triangles.\n #\n # See https://en.wikipedia.org/wiki/Polygram_(geometry)#Generalized_regular_polygons\n # for more information.\n\n num_gons = np.gcd(num_vertices, density)\n num_vertices //= num_gons\n density //= num_gons\n\n # Utility function for generating the individual\n # polygon vertices.\n def gen_polygon_vertices(start_angle):\n reg_vertices, start_angle = regular_vertices(\n num_vertices, radius=radius, start_angle=start_angle\n )\n\n vertices = []\n i = 0\n while True:\n vertices.append(reg_vertices[i])\n\n i += density\n i %= num_vertices\n if i == 0:\n break\n\n return vertices, start_angle\n\n first_group, self.start_angle = gen_polygon_vertices(start_angle)\n vertex_groups = [first_group]\n\n for i in range(1, num_gons):\n start_angle = self.start_angle + (i / num_gons) * TAU / num_vertices\n group, _ = gen_polygon_vertices(start_angle)\n\n vertex_groups.append(group)\n\n super().__init__(*vertex_groups, **kwargs)\n\n\nclass RegularPolygon(RegularPolygram):\n \"\"\"An n-sided regular :class:`Polygon`.\n\n Parameters\n ----------\n n\n The number of sides of the :class:`RegularPolygon`.\n kwargs\n Forwarded to the parent constructor.\n\n Examples\n --------\n\n .. manim:: RegularPolygonExample\n :save_last_frame:\n\n class RegularPolygonExample(Scene):\n def construct(self):\n poly_1 = RegularPolygon(n=6)\n poly_2 = RegularPolygon(n=6, start_angle=30*DEGREES, color=GREEN)\n poly_3 = RegularPolygon(n=10, color=RED)\n\n poly_group = Group(poly_1, poly_2, poly_3).scale(1.5).arrange(buff=1)\n self.add(poly_group)\n \"\"\"\n\n def __init__(self, n: int = 6, **kwargs):\n super().__init__(n, density=1, **kwargs)\n\n\nclass Star(Polygon):\n \"\"\"A regular polygram without the intersecting lines.\n\n Parameters\n ----------\n n\n How many points on the :class:`Star`.\n outer_radius\n The radius of the circle that the outer vertices are placed on.\n inner_radius\n The radius of the circle that the inner vertices are placed on.\n\n If unspecified, the inner radius will be\n calculated such that the edges of the :class:`Star`\n perfectly follow the edges of its :class:`RegularPolygram`\n counterpart.\n density\n The density of the :class:`Star`. Only used if\n ``inner_radius`` is unspecified.\n\n See :class:`RegularPolygram` for more information.\n start_angle\n The angle the vertices start at; the rotation of\n the :class:`Star`.\n kwargs\n Forwardeds to the parent constructor.\n\n Raises\n ------\n :exc:`ValueError`\n If ``inner_radius`` is unspecified and ``density``\n is not in the range ``[1, n/2)``.\n\n Examples\n --------\n .. manim:: StarExample\n :save_as_gif:\n\n class StarExample(Scene):\n def construct(self):\n pentagram = RegularPolygram(5, radius=2)\n star = Star(outer_radius=2, color=RED)\n\n self.add(pentagram)\n self.play(Create(star), run_time=3)\n self.play(FadeOut(star), run_time=2)\n\n .. manim:: DifferentDensitiesExample\n :save_last_frame:\n\n class DifferentDensitiesExample(Scene):\n def construct(self):\n density_2 = Star(7, outer_radius=2, density=2, color=RED)\n density_3 = Star(7, outer_radius=2, density=3, color=PURPLE)\n\n self.add(VGroup(density_2, density_3).arrange(RIGHT))\n\n \"\"\"\n\n def __init__(\n self,\n n: int = 5,\n *,\n outer_radius: float = 1,\n inner_radius: Optional[float] = None,\n density: int = 2,\n start_angle: Optional[float] = TAU / 4,\n **kwargs,\n ):\n inner_angle = TAU / (2 * n)\n\n if inner_radius is None:\n # See https://math.stackexchange.com/a/2136292 for an\n # overview of how to calculate the inner radius of a\n # perfect star.\n\n if density <= 0 or density >= n / 2:\n raise ValueError(\n f\"Incompatible density {density} for number of points {n}\"\n )\n\n outer_angle = TAU * density / n\n inverse_x = 1 - np.tan(inner_angle) * (\n (np.cos(outer_angle) - 1) / np.sin(outer_angle)\n )\n\n inner_radius = outer_radius / (np.cos(inner_angle) * inverse_x)\n\n outer_vertices, self.start_angle = regular_vertices(\n n, radius=outer_radius, start_angle=start_angle\n )\n inner_vertices, _ = regular_vertices(\n n, radius=inner_radius, start_angle=self.start_angle + inner_angle\n )\n\n vertices = []\n for pair in zip(outer_vertices, inner_vertices):\n vertices.extend(pair)\n\n super().__init__(*vertices, **kwargs)\n\n\nclass ArcPolygon(VMobject, metaclass=ConvertToOpenGL):\n \"\"\"A generalized polygon allowing for points to be connected with arcs.\n\n This version tries to stick close to the way :class:`Polygon` is used. Points\n can be passed to it directly which are used to generate the according arcs\n (using :class:`ArcBetweenPoints`). An angle or radius can be passed to it to\n use across all arcs, but to configure arcs individually an ``arc_config`` list\n has to be passed with the syntax explained below.\n\n .. tip::\n\n Two instances of :class:`ArcPolygon` can be transformed properly into one\n another as well. Be advised that any arc initialized with ``angle=0``\n will actually be a straight line, so if a straight section should seamlessly\n transform into an arced section or vice versa, initialize the straight section\n with a negligible angle instead (such as ``angle=0.0001``).\n\n There is an alternative version (:class:`ArcPolygonFromArcs`) that is instantiated\n with pre-defined arcs.\n\n See Also\n --------\n :class:`ArcPolygonFromArcs`\n\n Parameters\n ----------\n vertices : Union[:class:`list`, :class:`np.array`]\n A list of vertices, start and end points for the arc segments.\n angle : :class:`float`\n The angle used for constructing the arcs. If no other parameters\n are set, this angle is used to construct all arcs.\n radius : Optional[:class:`float`]\n The circle radius used to construct the arcs. If specified,\n overrides the specified ``angle``.\n arc_config : Optional[Union[List[:class:`dict`]], :class:`dict`]\n When passing a ``dict``, its content will be passed as keyword\n arguments to :class:`~.ArcBetweenPoints`. Otherwise, a list\n of dictionaries containing values that are passed as keyword\n arguments for every individual arc can be passed.\n kwargs\n Further keyword arguments that are passed to the constructor of\n :class:`~.VMobject`.\n\n Attributes\n ----------\n arcs : :class:`list`\n The arcs created from the input parameters::\n\n >>> from manim import ArcPolygon\n >>> ap = ArcPolygon([0, 0, 0], [2, 0, 0], [0, 2, 0])\n >>> ap.arcs\n [ArcBetweenPoints, ArcBetweenPoints, ArcBetweenPoints]\n\n Examples\n --------\n\n .. manim:: SeveralArcPolygons\n\n class SeveralArcPolygons(Scene):\n def construct(self):\n a = [0, 0, 0]\n b = [2, 0, 0]\n c = [0, 2, 0]\n ap1 = ArcPolygon(a, b, c, radius=2)\n ap2 = ArcPolygon(a, b, c, angle=45*DEGREES)\n ap3 = ArcPolygon(a, b, c, arc_config={'radius': 1.7, 'color': RED})\n ap4 = ArcPolygon(a, b, c, color=RED, fill_opacity=1,\n arc_config=[{'radius': 1.7, 'color': RED},\n {'angle': 20*DEGREES, 'color': BLUE},\n {'radius': 1}])\n ap_group = VGroup(ap1, ap2, ap3, ap4).arrange()\n self.play(*[Create(ap) for ap in [ap1, ap2, ap3, ap4]])\n self.wait()\n\n For further examples see :class:`ArcPolygonFromArcs`.\n \"\"\"\n\n def __init__(self, *vertices, angle=PI / 4, radius=None, arc_config=None, **kwargs):\n n = len(vertices)\n point_pairs = [(vertices[k], vertices[(k + 1) % n]) for k in range(n)]\n\n if not arc_config:\n if radius:\n all_arc_configs = [{\"radius\": radius} for pair in point_pairs]\n else:\n all_arc_configs = [{\"angle\": angle} for pair in point_pairs]\n elif isinstance(arc_config, dict):\n all_arc_configs = [arc_config for pair in point_pairs]\n else:\n assert len(arc_config) == n\n all_arc_configs = arc_config\n\n arcs = [\n ArcBetweenPoints(*pair, **conf)\n for (pair, conf) in zip(point_pairs, all_arc_configs)\n ]\n\n super().__init__(**kwargs)\n # Adding the arcs like this makes ArcPolygon double as a VGroup.\n # Also makes changes to the ArcPolygon, such as scaling, affect\n # the arcs, so that their new values are usable.\n self.add(*arcs)\n for arc in arcs:\n self.append_points(arc.get_points())\n\n # This enables the use of ArcPolygon.arcs as a convenience\n # because ArcPolygon[0] returns itself, not the first Arc.\n self.arcs = arcs\n\n\nclass ArcPolygonFromArcs(VMobject, metaclass=ConvertToOpenGL):\n \"\"\"A generalized polygon allowing for points to be connected with arcs.\n\n This version takes in pre-defined arcs to generate the arcpolygon and introduces\n little new syntax. However unlike :class:`Polygon` it can't be created with points\n directly.\n\n For proper appearance the passed arcs should connect seamlessly:\n ``[a,b][b,c][c,a]``\n\n If there are any gaps between the arcs, those will be filled in\n with straight lines, which can be used deliberately for any straight\n sections. Arcs can also be passed as straight lines such as an arc\n initialized with ``angle=0``.\n\n .. tip::\n\n Two instances of :class:`ArcPolygon` can be transformed properly into\n one another as well. Be advised that any arc initialized with ``angle=0``\n will actually be a straight line, so if a straight section should seamlessly\n transform into an arced section or vice versa, initialize the straight\n section with a negligible angle instead (such as ``angle=0.0001``).\n\n There is an alternative version (:class:`ArcPolygon`) that can be instantiated\n with points.\n\n See Also\n --------\n :class:`ArcPolygon`\n\n Parameters\n ----------\n arcs : Union[:class:`Arc`, :class:`ArcBetweenPoints`]\n These are the arcs from which the arcpolygon is assembled.\n kwargs\n Keyword arguments that are passed to the constructor of\n :class:`~.VMobject`. Affects how the ArcPolygon itself is drawn,\n but doesn't affect passed arcs.\n\n Attributes\n ----------\n arcs : :class:`list`\n The arcs used to initialize the ArcPolygonFromArcs::\n\n >>> from manim import ArcPolygonFromArcs, Arc, ArcBetweenPoints\n >>> ap = ArcPolygonFromArcs(Arc(), ArcBetweenPoints([1,0,0], [0,1,0]), Arc())\n >>> ap.arcs\n [Arc, ArcBetweenPoints, Arc]\n\n Examples\n --------\n One example of an arcpolygon is the Reuleaux triangle.\n Instead of 3 straight lines connecting the outer points,\n a Reuleaux triangle has 3 arcs connecting those points,\n making a shape with constant width.\n\n Passed arcs are stored as submobjects in the arcpolygon.\n This means that the arcs are changed along with the arcpolygon,\n for example when it's shifted, and these arcs can be manipulated\n after the arcpolygon has been initialized.\n\n Also both the arcs contained in an :class:`~.ArcPolygonFromArcs`, as well as the\n arcpolygon itself are drawn, which affects draw time in :class:`~.Create`\n for example. In most cases the arcs themselves don't\n need to be drawn, in which case they can be passed as invisible.\n\n .. manim:: ArcPolygonExample\n\n class ArcPolygonExample(Scene):\n def construct(self):\n arc_conf = {\"stroke_width\": 0}\n poly_conf = {\"stroke_width\": 10, \"stroke_color\": BLUE,\n \"fill_opacity\": 1, \"color\": PURPLE}\n a = [-1, 0, 0]\n b = [1, 0, 0]\n c = [0, np.sqrt(3), 0]\n arc0 = ArcBetweenPoints(a, b, radius=2, **arc_conf)\n arc1 = ArcBetweenPoints(b, c, radius=2, **arc_conf)\n arc2 = ArcBetweenPoints(c, a, radius=2, **arc_conf)\n reuleaux_tri = ArcPolygonFromArcs(arc0, arc1, arc2, **poly_conf)\n self.play(FadeIn(reuleaux_tri))\n self.wait(2)\n\n The arcpolygon itself can also be hidden so that instead only the contained\n arcs are drawn. This can be used to easily debug arcs or to highlight them.\n\n .. manim:: ArcPolygonExample2\n\n class ArcPolygonExample2(Scene):\n def construct(self):\n arc_conf = {\"stroke_width\": 3, \"stroke_color\": BLUE,\n \"fill_opacity\": 0.5, \"color\": GREEN}\n poly_conf = {\"color\": None}\n a = [-1, 0, 0]\n b = [1, 0, 0]\n c = [0, np.sqrt(3), 0]\n arc0 = ArcBetweenPoints(a, b, radius=2, **arc_conf)\n arc1 = ArcBetweenPoints(b, c, radius=2, **arc_conf)\n arc2 = ArcBetweenPoints(c, a, radius=2, stroke_color=RED)\n reuleaux_tri = ArcPolygonFromArcs(arc0, arc1, arc2, **poly_conf)\n self.play(FadeIn(reuleaux_tri))\n self.wait(2)\n\n \"\"\"\n\n def __init__(self, *arcs, **kwargs):\n if not all(isinstance(m, (Arc, ArcBetweenPoints)) for m in arcs):\n raise ValueError(\n \"All ArcPolygon submobjects must be of type Arc/ArcBetweenPoints\"\n )\n super().__init__(**kwargs)\n # Adding the arcs like this makes ArcPolygonFromArcs double as a VGroup.\n # Also makes changes to the ArcPolygonFromArcs, such as scaling, affect\n # the arcs, so that their new values are usable.\n self.add(*arcs)\n # This enables the use of ArcPolygonFromArcs.arcs as a convenience\n # because ArcPolygonFromArcs[0] returns itself, not the first Arc.\n self.arcs = [*arcs]\n for arc1, arc2 in adjacent_pairs(arcs):\n self.append_points(arc1.points)\n line = Line(arc1.get_end(), arc2.get_start())\n len_ratio = line.get_length() / arc1.get_arc_length()\n if math.isnan(len_ratio) or math.isinf(len_ratio):\n continue\n line.insert_n_curves(int(arc1.get_num_curves() * len_ratio))\n self.append_points(line.get_points())\n\n\nclass Triangle(RegularPolygon):\n \"\"\"An equilateral triangle.\n\n Parameters\n ----------\n kwargs : Any\n Additional arguments to be passed to :class:`RegularPolygon`\n\n Examples\n --------\n\n .. manim:: TriangleExample\n :save_last_frame:\n\n class TriangleExample(Scene):\n def construct(self):\n triangle_1 = Triangle()\n triangle_2 = Triangle().scale(2).rotate(60*DEGREES)\n tri_group = Group(triangle_1, triangle_2).arrange(buff=1)\n self.add(tri_group)\n \"\"\"\n\n def __init__(self, **kwargs):\n super().__init__(n=3, **kwargs)\n\n\nclass Rectangle(Polygon):\n \"\"\"A quadrilateral with two sets of parallel sides.\n\n Parameters\n ----------\n color : :class:`~.Colors`, optional\n The color of the rectangle.\n height : :class:`float`, optional\n The vertical height of the rectangle.\n width : :class:`float`, optional\n The horizontal width of the rectangle.\n grid_xstep : :class:`float`, optional\n Space between vertical grid lines.\n grid_ystep : :class:`float`, optional\n Space between horizontal grid lines.\n mark_paths_closed : :class:`bool`, optional\n No purpose.\n close_new_points : :class:`bool`, optional\n No purpose.\n kwargs : Any\n Additional arguments to be passed to :class:`Polygon`\n\n Examples\n ----------\n\n .. manim:: RectangleExample\n :save_last_frame:\n\n class RectangleExample(Scene):\n def construct(self):\n rect1 = Rectangle(width=4.0, height=2.0, grid_xstep=1.0, grid_ystep=0.5)\n rect2 = Rectangle(width=1.0, height=4.0)\n\n rects = Group(rect1,rect2).arrange(buff=1)\n self.add(rects)\n \"\"\"\n\n def __init__(\n self,\n color: Color = WHITE,\n height: float = 2.0,\n width: float = 4.0,\n grid_xstep: Optional[float] = None,\n grid_ystep: Optional[float] = None,\n mark_paths_closed=True,\n close_new_points=True,\n **kwargs,\n ):\n self.mark_paths_closed = mark_paths_closed\n self.close_new_points = close_new_points\n super().__init__(UR, UL, DL, DR, color=color, **kwargs)\n self.stretch_to_fit_width(width)\n self.stretch_to_fit_height(height)\n v = self.get_vertices()\n if grid_xstep is not None:\n grid_xstep = abs(grid_xstep)\n count = int(width / grid_xstep)\n grid = VGroup(\n *[\n Line(\n v[1] + i * grid_xstep * RIGHT,\n v[1] + i * grid_xstep * RIGHT + height * DOWN,\n color=color,\n )\n for i in range(1, count)\n ]\n )\n self.add(grid)\n if grid_ystep is not None:\n grid_ystep = abs(grid_ystep)\n count = int(height / grid_ystep)\n grid = VGroup(\n *[\n Line(\n v[1] + i * grid_ystep * DOWN,\n v[1] + i * grid_ystep * DOWN + width * RIGHT,\n color=color,\n )\n for i in range(1, count)\n ]\n )\n self.add(grid)\n\n\nclass Square(Rectangle):\n \"\"\"A rectangle with equal side lengths.\n\n Parameters\n ----------\n side_length : :class:`float`, optional\n The length of the sides of the square.\n kwargs : Any\n Additional arguments to be passed to :class:`Square`\n\n Examples\n --------\n\n .. manim:: SquareExample\n :save_last_frame:\n\n class SquareExample(Scene):\n def construct(self):\n square_1 = Square(side_length=2.0).shift(DOWN)\n square_2 = Square(side_length=1.0).next_to(square_1, direction=UP)\n square_3 = Square(side_length=0.5).next_to(square_2, direction=UP)\n self.add(square_1, square_2, square_3)\n \"\"\"\n\n def __init__(self, side_length=2.0, **kwargs):\n self.side_length = side_length\n super().__init__(height=side_length, width=side_length, **kwargs)\n\n\nclass RoundedRectangle(Rectangle):\n \"\"\"A rectangle with rounded corners.\n\n Parameters\n ----------\n corner_radius : :class:`float`, optional\n The curvature of the corners of the rectangle.\n kwargs : Any\n Additional arguments to be passed to :class:`Rectangle`\n\n Examples\n --------\n\n .. manim:: RoundedRectangleExample\n :save_last_frame:\n\n class RoundedRectangleExample(Scene):\n def construct(self):\n rect_1 = RoundedRectangle(corner_radius=0.5)\n rect_2 = RoundedRectangle(corner_radius=1.5, height=4.0, width=4.0)\n\n rect_group = Group(rect_1, rect_2).arrange(buff=1)\n self.add(rect_group)\n \"\"\"\n\n def __init__(self, corner_radius=0.5, **kwargs):\n self.corner_radius = corner_radius\n super().__init__(**kwargs)\n self.round_corners(self.corner_radius)\n\n\nclass ArrowTip(VMobject, metaclass=ConvertToOpenGL):\n r\"\"\"Base class for arrow tips.\n\n See Also\n --------\n :class:`ArrowTriangleTip`\n :class:`ArrowTriangleFilledTip`\n :class:`ArrowCircleTip`\n :class:`ArrowCircleFilledTip`\n :class:`ArrowSquareTip`\n :class:`ArrowSquareFilledTip`\n\n Examples\n --------\n Cannot be used directly, only intended for inheritance::\n\n >>> tip = ArrowTip()\n Traceback (most recent call last):\n ...\n NotImplementedError: Has to be implemented in inheriting subclasses.\n\n Instead, use one of the pre-defined ones, or make\n a custom one like this:\n\n .. manim:: CustomTipExample\n\n >>> class MyCustomArrowTip(ArrowTip, RegularPolygon):\n ... def __init__(self, **kwargs):\n ... RegularPolygon.__init__(self, n=5, **kwargs)\n ... length = 0.35\n ... self.width = length\n ... self.stretch_to_fit_height(length)\n >>> arr = Arrow(np.array([-2, -2, 0]), np.array([2, 2, 0]),\n ... tip_shape=MyCustomArrowTip)\n >>> isinstance(arr.tip, RegularPolygon)\n True\n >>> from manim import Scene\n >>> class CustomTipExample(Scene):\n ... def construct(self):\n ... self.play(Create(arr))\n\n Using a class inherited from :class:`ArrowTip` to get a non-filled\n tip is a shorthand to manually specifying the arrow tip style as follows::\n\n >>> arrow = Arrow(np.array([0, 0, 0]), np.array([1, 1, 0]),\n ... tip_style={'fill_opacity': 0, 'stroke_width': 3})\n\n The following example illustrates the usage of all of the predefined\n arrow tips.\n\n .. manim:: ArrowTipsShowcase\n :save_last_frame:\n\n from manim.mobject.geometry import ArrowTriangleTip, ArrowSquareTip, ArrowSquareFilledTip,\\\n ArrowCircleTip, ArrowCircleFilledTip\n class ArrowTipsShowcase(Scene):\n def construct(self):\n a00 = Arrow(start=[-2, 3, 0], end=[2, 3, 0], color=YELLOW)\n a11 = Arrow(start=[-2, 2, 0], end=[2, 2, 0], tip_shape=ArrowTriangleTip)\n a12 = Arrow(start=[-2, 1, 0], end=[2, 1, 0])\n a21 = Arrow(start=[-2, 0, 0], end=[2, 0, 0], tip_shape=ArrowSquareTip)\n a22 = Arrow([-2, -1, 0], [2, -1, 0], tip_shape=ArrowSquareFilledTip)\n a31 = Arrow([-2, -2, 0], [2, -2, 0], tip_shape=ArrowCircleTip)\n a32 = Arrow([-2, -3, 0], [2, -3, 0], tip_shape=ArrowCircleFilledTip)\n b11 = a11.copy().scale(0.5, scale_tips=True).next_to(a11, RIGHT)\n b12 = a12.copy().scale(0.5, scale_tips=True).next_to(a12, RIGHT)\n b21 = a21.copy().scale(0.5, scale_tips=True).next_to(a21, RIGHT)\n self.add(a00, a11, a12, a21, a22, a31, a32, b11, b12, b21)\n\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n raise NotImplementedError(\"Has to be implemented in inheriting subclasses.\")\n\n @property\n def base(self):\n r\"\"\"The base point of the arrow tip.\n\n This is the point connecting to the arrow line.\n\n Examples\n --------\n ::\n\n >>> arrow = Arrow(np.array([0, 0, 0]), np.array([2, 0, 0]), buff=0)\n >>> arrow.tip.base.round(2) + 0. # add 0. to avoid negative 0 in output\n array([1.65, 0. , 0. ])\n\n \"\"\"\n return self.point_from_proportion(0.5)\n\n @property\n def tip_point(self):\n r\"\"\"The tip point of the arrow tip.\n\n Examples\n --------\n ::\n\n >>> arrow = Arrow(np.array([0, 0, 0]), np.array([2, 0, 0]), buff=0)\n >>> arrow.tip.tip_point.round(2) + 0.\n array([2., 0., 0.])\n\n \"\"\"\n return self.get_points()[0]\n\n @property\n def vector(self):\n r\"\"\"The vector pointing from the base point to the tip point.\n\n Examples\n --------\n ::\n\n >>> arrow = Arrow(np.array([0, 0, 0]), np.array([2, 2, 0]), buff=0)\n >>> arrow.tip.vector.round(2) + 0.\n array([0.25, 0.25, 0. ])\n\n \"\"\"\n return self.tip_point - self.base\n\n @property\n def tip_angle(self):\n r\"\"\"The angle of the arrow tip.\n\n Examples\n --------\n ::\n\n >>> arrow = Arrow(np.array([0, 0, 0]), np.array([1, 1, 0]), buff=0)\n >>> round(arrow.tip.tip_angle, 5) == round(PI/4, 5)\n True\n\n \"\"\"\n return angle_of_vector(self.vector)\n\n @property\n def length(self):\n r\"\"\"The length of the arrow tip.\n\n Examples\n --------\n ::\n\n >>> arrow = Arrow(np.array([0, 0, 0]), np.array([1, 2, 0]))\n >>> round(arrow.tip.length, 3)\n 0.35\n\n \"\"\"\n return np.linalg.norm(self.vector)\n\n\nclass ArrowTriangleTip(ArrowTip, Triangle):\n r\"\"\"Triangular arrow tip.\"\"\"\n\n def __init__(\n self,\n fill_opacity=0,\n stroke_width=3,\n length=DEFAULT_ARROW_TIP_LENGTH,\n start_angle=PI,\n **kwargs,\n ):\n Triangle.__init__(\n self,\n fill_opacity=fill_opacity,\n stroke_width=stroke_width,\n start_angle=start_angle,\n **kwargs,\n )\n self.width = length\n self.stretch_to_fit_height(length)\n\n\nclass ArrowTriangleFilledTip(ArrowTriangleTip):\n r\"\"\"Triangular arrow tip with filled tip.\n\n This is the default arrow tip shape.\n \"\"\"\n\n def __init__(self, fill_opacity=1, stroke_width=0, **kwargs):\n super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs)\n\n\nclass ArrowCircleTip(ArrowTip, Circle):\n r\"\"\"Circular arrow tip.\"\"\"\n\n def __init__(\n self,\n fill_opacity=0,\n stroke_width=3,\n length=DEFAULT_ARROW_TIP_LENGTH,\n start_angle=PI,\n **kwargs,\n ):\n self.start_angle = start_angle\n Circle.__init__(\n self, fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs\n )\n self.width = length\n self.stretch_to_fit_height(length)\n\n\nclass ArrowCircleFilledTip(ArrowCircleTip):\n r\"\"\"Circular arrow tip with filled tip.\"\"\"\n\n def __init__(self, fill_opacity=1, stroke_width=0, **kwargs):\n super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs)\n\n\nclass ArrowSquareTip(ArrowTip, Square):\n r\"\"\"Square arrow tip.\"\"\"\n\n def __init__(\n self,\n fill_opacity=0,\n stroke_width=3,\n length=DEFAULT_ARROW_TIP_LENGTH,\n start_angle=PI,\n **kwargs,\n ):\n self.start_angle = start_angle\n Square.__init__(\n self,\n fill_opacity=fill_opacity,\n stroke_width=stroke_width,\n side_length=length,\n **kwargs,\n )\n self.width = length\n self.stretch_to_fit_height(length)\n\n\nclass ArrowSquareFilledTip(ArrowSquareTip):\n r\"\"\"Square arrow tip with filled tip.\"\"\"\n\n def __init__(self, fill_opacity=1, stroke_width=0, **kwargs):\n super().__init__(fill_opacity=fill_opacity, stroke_width=stroke_width, **kwargs)\n\n\nclass Cutout(VMobject, metaclass=ConvertToOpenGL):\n \"\"\"A shape with smaller cutouts.\n\n .. warning::\n\n Technically, this class behaves similar to a symmetric difference: if\n parts of the ``mobjects`` are not located within the ``main_shape``,\n these parts will be added to the resulting :class:`~.VMobject`.\n\n Parameters\n ----------\n main_shape : :class:`~.VMobject`\n The primary shape from which cutouts are made.\n mobjects : :class:`~.VMobject`\n The smaller shapes which are to be cut out of the ``main_shape``.\n kwargs\n Further keyword arguments that are passed to the constructor of\n :class:`~.VMobject`.\n\n Examples\n --------\n .. manim:: CutoutExample\n\n class CutoutExample(Scene):\n def construct(self):\n s1 = Square().scale(2.5)\n s2 = Triangle().shift(DOWN + RIGHT).scale(0.5)\n s3 = Square().shift(UP + RIGHT).scale(0.5)\n s4 = RegularPolygon(5).shift(DOWN + LEFT).scale(0.5)\n s5 = RegularPolygon(6).shift(UP + LEFT).scale(0.5)\n c = Cutout(s1, s2, s3, s4, s5, fill_opacity=1, color=BLUE, stroke_color=RED)\n self.play(Write(c), run_time=4)\n self.wait()\n \"\"\"\n\n def __init__(self, main_shape, *mobjects, **kwargs):\n super().__init__(**kwargs)\n self.append_points(main_shape.get_points())\n if main_shape.get_direction() == \"CW\":\n sub_direction = \"CCW\"\n else:\n sub_direction = \"CW\"\n for mobject in mobjects:\n self.append_points(mobject.force_direction(sub_direction).get_points())\n\n\nclass Angle(VMobject, metaclass=ConvertToOpenGL):\n \"\"\"A circular arc or elbow-type mobject representing an angle of two lines.\n\n Parameters\n ----------\n line1 :\n The first line.\n line2 :\n The second line.\n radius :\n The radius of the :class:`Arc`.\n quadrant : Sequence[:class:`int`]\n A sequence of two :class:`int` numbers determining which of the 4 quadrants should be used.\n The first value indicates whether to anchor the arc on the first line closer to the end point (1)\n or start point (-1), and the second value functions similarly for the\n end (1) or start (-1) of the second line.\n Possibilities: (1,1), (-1,1), (1,-1), (-1,-1).\n other_angle :\n Toggles between the two possible angles defined by two points and an arc center. If set to\n False (default), the arc will always go counterclockwise from the point on line1 until\n the point on line2 is reached. If set to True, the angle will go clockwise from line1 to line2.\n dot : :class:`bool`\n Allows for a :class:`Dot` in the arc. Mainly used as an convention to indicate a right angle.\n The dot can be customized in the next three parameters.\n dot_radius : :class:`float`\n The radius of the :class:`Dot`. If not specified otherwise, this radius will be 1/10 of the arc radius.\n dot_distance : :class:`float`\n Relative distance from the center to the arc: 0 puts the dot in the center and 1 on the arc itself.\n dot_color : :class:`~.Colors`\n The color of the :class:`Dot`.\n elbow : :class:`bool`\n Produces an elbow-type mobject indicating a right angle, see :class:`RightAngle` for more information\n and a shorthand.\n **kwargs\n Further keyword arguments that are passed to the constructor of :class:`Arc` or :class:`Elbow`.\n\n Examples\n --------\n The first example shows some right angles with a dot in the middle while the second example shows\n all 8 possible angles defined by two lines.\n\n .. manim:: RightArcAngleExample\n :save_last_frame:\n\n class RightArcAngleExample(Scene):\n def construct(self):\n line1 = Line( LEFT, RIGHT )\n line2 = Line( DOWN, UP )\n rightarcangles = [\n Angle(line1, line2, dot=True),\n Angle(line1, line2, radius=0.4, quadrant=(1,-1), dot=True, other_angle=True),\n Angle(line1, line2, radius=0.5, quadrant=(-1,1), stroke_width=8, dot=True, dot_color=YELLOW, dot_radius=0.04, other_angle=True),\n Angle(line1, line2, radius=0.7, quadrant=(-1,-1), color=RED, dot=True, dot_color=GREEN, dot_radius=0.08),\n ]\n plots = VGroup()\n for angle in rightarcangles:\n plot=VGroup(line1.copy(),line2.copy(), angle)\n plots.add(plot)\n plots.arrange(buff=1.5)\n self.add(plots)\n\n .. manim:: AngleExample\n :save_last_frame:\n\n class AngleExample(Scene):\n def construct(self):\n line1 = Line( LEFT + (1/3) * UP, RIGHT + (1/3) * DOWN )\n line2 = Line( DOWN + (1/3) * RIGHT, UP + (1/3) * LEFT )\n angles = [\n Angle(line1, line2),\n Angle(line1, line2, radius=0.4, quadrant=(1,-1), other_angle=True),\n Angle(line1, line2, radius=0.5, quadrant=(-1,1), stroke_width=8, other_angle=True),\n Angle(line1, line2, radius=0.7, quadrant=(-1,-1), color=RED),\n Angle(line1, line2, other_angle=True),\n Angle(line1, line2, radius=0.4, quadrant=(1,-1)),\n Angle(line1, line2, radius=0.5, quadrant=(-1,1), stroke_width=8),\n Angle(line1, line2, radius=0.7, quadrant=(-1,-1), color=RED, other_angle=True),\n ]\n plots = VGroup()\n for angle in angles:\n plot=VGroup(line1.copy(),line2.copy(), angle)\n plots.add(VGroup(plot,SurroundingRectangle(plot, buff=0.3)))\n plots.arrange_in_grid(rows=2,buff=1)\n self.add(plots)\n\n .. manim:: FilledAngle\n :save_last_frame:\n\n class FilledAngle(Scene):\n def construct(self):\n l1 = Line(ORIGIN, 2 * UP + RIGHT).set_color(GREEN)\n l2 = (\n Line(ORIGIN, 2 * UP + RIGHT)\n .set_color(GREEN)\n .rotate(-20 * DEGREES, about_point=ORIGIN)\n )\n norm = l1.get_length()\n a1 = Angle(l1, l2, other_angle=True, radius=norm - 0.5).set_color(GREEN)\n a2 = Angle(l1, l2, other_angle=True, radius=norm).set_color(GREEN)\n q1 = a1.get_points() # save all coordinates of points of angle a1\n q2 = a2.reverse_direction().get_points() # save all coordinates of points of angle a1 (in reversed direction)\n pnts = np.concatenate([q1, q2, q1[0].reshape(1, 3)]) # adds points and ensures that path starts and ends at same point\n mfill = VMobject().set_color(ORANGE)\n mfill.set_points_as_corners(pnts).set_fill(GREEN, opacity=1)\n self.add(l1, l2)\n self.add(mfill)\n\n \"\"\"\n\n def __init__(\n self,\n line1: Line,\n line2: Line,\n radius: float = None,\n quadrant=(1, 1),\n other_angle: bool = False,\n dot=False,\n dot_radius=None,\n dot_distance=0.55,\n dot_color=WHITE,\n elbow=False,\n **kwargs,\n ):\n super().__init__(**kwargs)\n self.quadrant = quadrant\n self.dot_distance = dot_distance\n self.elbow = elbow\n inter = line_intersection(\n [line1.get_start(), line1.get_end()], [line2.get_start(), line2.get_end()]\n )\n\n if radius is None:\n if quadrant[0] == 1:\n dist_1 = np.linalg.norm(line1.get_end() - inter)\n else:\n dist_1 = np.linalg.norm(line1.get_start() - inter)\n if quadrant[1] == 1:\n dist_2 = np.linalg.norm(line2.get_end() - inter)\n else:\n dist_2 = np.linalg.norm(line2.get_start() - inter)\n if np.minimum(dist_1, dist_2) < 0.6:\n radius = (2 / 3) * np.minimum(dist_1, dist_2)\n else:\n radius = 0.4\n else:\n self.radius = radius\n\n anchor_angle_1 = inter + quadrant[0] * radius * line1.get_unit_vector()\n anchor_angle_2 = inter + quadrant[1] * radius * line2.get_unit_vector()\n\n if elbow:\n anchor_middle = (\n inter\n + quadrant[0] * radius * line1.get_unit_vector()\n + quadrant[1] * radius * line2.get_unit_vector()\n )\n angle_mobject = Elbow(**kwargs)\n angle_mobject.set_points_as_corners(\n [anchor_angle_1, anchor_middle, anchor_angle_2]\n )\n else:\n angle_1 = angle_of_vector(anchor_angle_1 - inter)\n angle_2 = angle_of_vector(anchor_angle_2 - inter)\n\n if not other_angle:\n start_angle = angle_1\n if angle_2 > angle_1:\n angle_fin = angle_2 - angle_1\n else:\n angle_fin = 2 * np.pi - (angle_1 - angle_2)\n else:\n start_angle = angle_1\n if angle_2 < angle_1:\n angle_fin = -angle_1 + angle_2\n else:\n angle_fin = -2 * np.pi + (angle_2 - angle_1)\n\n angle_mobject = Arc(\n radius=radius,\n angle=angle_fin,\n start_angle=start_angle,\n arc_center=inter,\n **kwargs,\n )\n\n if dot:\n if dot_radius is None:\n dot_radius = radius / 10\n else:\n self.dot_radius = dot_radius\n right_dot = Dot(ORIGIN, radius=dot_radius, color=dot_color)\n dot_anchor = (\n inter\n + (self.get_center() - inter)\n / np.linalg.norm(self.get_center() - inter)\n * radius\n * dot_distance\n )\n right_dot.move_to(dot_anchor)\n self.add(right_dot)\n\n self.set_points(angle_mobject.get_points())\n\n\nclass RightAngle(Angle):\n \"\"\"An elbow-type mobject representing a right angle between two lines.\n\n Parameters\n ----------\n line1 : :class:`Line`\n The first line.\n line2 : :class:`Line`\n The second line.\n length : :class:`float`\n The length of the arms.\n **kwargs\n Further keyword arguments that are passed to the constructor of :class:`Angle`.\n\n Examples\n --------\n\n .. manim:: RightAngleExample\n :save_last_frame:\n\n class RightAngleExample(Scene):\n def construct(self):\n line1 = Line( LEFT, RIGHT )\n line2 = Line( DOWN, UP )\n rightangles = [\n RightAngle(line1, line2),\n RightAngle(line1, line2, length=0.4, quadrant=(1,-1)),\n RightAngle(line1, line2, length=0.5, quadrant=(-1,1), stroke_width=8),\n RightAngle(line1, line2, length=0.7, quadrant=(-1,-1), color=RED),\n ]\n plots = VGroup()\n for rightangle in rightangles:\n plot=VGroup(line1.copy(),line2.copy(), rightangle)\n plots.add(plot)\n plots.arrange(buff=1.5)\n self.add(plots)\n \"\"\"\n\n def __init__(self, line1, line2, length=None, **kwargs):\n super().__init__(line1, line2, radius=length, elbow=True, **kwargs)\n"
]
| [
[
"numpy.hstack",
"numpy.dot",
"numpy.minimum",
"numpy.sqrt",
"numpy.linspace",
"numpy.clip",
"numpy.cos",
"numpy.linalg.norm",
"numpy.sin",
"numpy.all",
"numpy.sign",
"numpy.round",
"numpy.tan",
"numpy.gcd",
"numpy.cross",
"numpy.array",
"numpy.zeros"
]
]
|
joshr2020/Code-Reuse-Estimation | [
"632eb823baf22a4ba4decf3d37239a228b2fa31f"
]
| [
"src/binary_compare.py"
]
| [
"'''\nCopyright (C) 2017 Aurin Chakravarty & Joshua Russo.\n'''\nimport os\nimport argparse\nimport sys\nimport pandas as pd\nimport subprocess\n\ndef getTotalSize(x):\n '''\n Sums up all string values in base 16 and converts to base 10.\n\n x is a dictionary with keys as symbols and values as sizes in base 16.\n '''\n x_total = 0\n for size in x:\n x_total += int(x.get(size), 16)\n return x_total\n\ndef jaccard(x, y):\n '''\n Compares two dictionaries using the jaccard index.\n '''\n keysx = set(x.keys())\n keysy = set(y.keys())\n intersection = keysx.intersection(keysy)\n x_total = getTotalSize(x)\n y_total = getTotalSize(y)\n\n overlap_size = 0\n for key in intersection:\n if int(x.get(key), 16) == int(y.get(key), 16):\n overlap_size += int(x.get(key), 16)\n\n result = float(overlap_size) / float(x_total + y_total - overlap_size)\n return result\n\n\ndef gatherNMDump(exe, rootdir):\n '''\n Populates dataframe with nm output of exe file.\n '''\n index = exe.rfind(\"/\")\n justExeName = exe[index + 1:]\n with open(rootdir + \"/.bin/\" + justExeName + \"_dump.txt\", \"w\") as write_out:\n subprocess.run(['nm', '-S', exe], stdout=write_out)\n fileName = write_out.name\n\n tempFileName = fileName.rsplit(\".\", 1)[0]\n # filter out symbols without associated sizes\n with open(tempFileName + \"_filtered.txt\", 'w+') as outfile:\n with open(fileName) as file2:\n for line in file2:\n line = line.lstrip()\n if(line.count(' ') == 3):\n outfile.write(line)\n df = pd.read_table(outfile.name, header = None, delim_whitespace=True)\n df.columns = ['Address', 'Size', 'Type', 'Symbol_Name']\n df.reset_index().to_json(orient='records')\n return df\n\ndef compare(input, rootdir):\n '''\n Two file compare from filenames to result.\n '''\n df = gatherNMDump(input[0], rootdir)\n df2 = gatherNMDump(input[1], rootdir)\n\n dict1 = df.set_index('Symbol_Name')['Size'].to_dict()\n dict2 = df2.set_index('Symbol_Name')['Size'].to_dict()\n\n result = jaccard(dict1, dict2)\n\n print('%s, %s, %f' % (os.path.abspath(input[0]), os.path.abspath(input[1])\n , result))\n\ndef multiCompare(input, rootdir):\n '''\n Multiple file compare with input as a directory.\n '''\n filenames = os.listdir(input[0])\n filepaths = []\n for name in filenames:\n filepaths.append(input[0] + \"/\" + name)\n\n for x in range(0, int(input[1])):\n for y in range(x, int(input[1])):\n if x == y:\n continue\n else:\n compare([filepaths[x], filepaths[y]], rootdir)\n\ndef main(argv):\n rootdir = os.getcwd()\n rootdir = os.path.dirname(rootdir)\n if not os.path.exists(rootdir + \"/.bin/\"):\n os.makedirs(rootdir + \"/.bin/\")\n\n parser = argparse.ArgumentParser(description='Compare binaries.')\n subparsers = parser.add_subparsers(help='sub-command help')\n parser_many = subparsers.add_parser('many', help='recurse help')\n parser_many.add_argument('dir', help='dir to compare pairs')\n parser_many.add_argument('number_of_comparisons',\n help='number of comparisons', type=int)\n parser_two = subparsers.add_parser('two', help='two file help')\n parser_two.add_argument('file1', help='file to compare')\n parser_two.add_argument('file2', help='file to compare')\n\n args = parser.parse_args()\n args_dict = vars(args)\n if 'dir' in args_dict.keys():\n multiCompare([args_dict['dir'],\n args_dict['number_of_comparisons']], rootdir)\n else:\n compare([args_dict['file1'], args_dict['file2']], rootdir)\n\nif __name__ == \"__main__\":\n main(sys.argv[0:])\n"
]
| [
[
"pandas.read_table"
]
]
|
mads-br/optimal-ph | [
"c5d11ae739c472b0f85db0e2aec2bab625c65710"
]
| [
"src/model.py"
]
| [
"from sklearn import tree\nimport numpy as np\nimport pickle\n\n\nclass BaselineModel:\n def __init__(self, model_file_path):\n self.model_file_path = model_file_path\n\n def vectorize_sequences(self, sequence_array):\n vectorize_on_length = np.vectorize(len)\n return np.reshape(vectorize_on_length(sequence_array), (-1, 1))\n\n def train(self, df_train):\n X = self.vectorize_sequences(df_train['sequence'].to_numpy())\n y = df_train['mean_growth_PH'].to_numpy()\n\n model = tree.DecisionTreeRegressor()\n model.fit(X, y)\n\n with open(self.model_file_path, 'wb') as model_file:\n pickle.dump(model, model_file)\n\n def predict(self, df_test):\n with open(self.model_file_path, 'rb') as model_file:\n model: tree.DecisionTreeRegressor = pickle.load(model_file)\n\n X = df_test['sequence'].to_numpy()\n X_vectorized = self.vectorize_sequences(X)\n return model.predict(X_vectorized)\n"
]
| [
[
"numpy.vectorize",
"sklearn.tree.DecisionTreeRegressor"
]
]
|
marcoancona/DASP | [
"cbd82b36443199f11fa04ecb0322fa68f5505b2c"
]
| [
"utils/utils.py"
]
| [
"from skimage import feature, transform\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport scipy\nimport datetime\nimport os\nfrom matplotlib.ticker import FormatStrFormatter\n\n\nCOLORS = [\"#4e79a7\",\n \"#59a14f\",\n \"#9c755f\",\n \"#edc948\",\n \"#bab0ac\",\n \"#e15759\",\n \"#b07aa1\",\n \"#f28e2b\"]\n\n\ndef color_for_label(label):\n l = label.lower()\n if \"integrated\" in l:\n return COLORS[0]\n elif \"occlusion\" in l:\n return COLORS[1]\n elif \"revcancel\" in l:\n return COLORS[2]\n elif \"mix\" in l:\n return \"#666666\"\n elif \"rescale\" in l:\n return COLORS[5]\n elif \"ours\" in l or \"dasp\" in l:\n return \"orange\"\n elif \"sampling\" in l:\n return COLORS[6]\n else:\n return \"#FFFFFF\"\n\n\ndef _ensure_dir(path):\n if not os.path.exists(path):\n os.makedirs(path)\n\n\ndef get_plot_filename(plot_name, experiment_name):\n folder = \"results/\" + experiment_name + \"/\"\n _ensure_dir(folder)\n t = datetime.datetime.now().isoformat()[:-7]\n return folder + plot_name + \"_\" + experiment_name + \"_\" + t + \".pdf\"\n\n\ndef _isiterable(p_object):\n try:\n it = iter(p_object)\n except TypeError:\n return False\n return True\n\n\ndef plot(data, xi=None, cmap='RdBu_r', axis=plt, percentile=100, dilation=3.0, alpha=0.8):\n dx, dy = 0.05, 0.05\n xx = np.arange(0.0, data.shape[1], dx)\n yy = np.arange(0.0, data.shape[0], dy)\n xmin, xmax, ymin, ymax = np.amin(xx), np.amax(xx), np.amin(yy), np.amax(yy)\n extent = xmin, xmax, ymin, ymax\n cmap_xi = plt.get_cmap('Greys_r')\n cmap_xi.set_bad(alpha=0)\n overlay = None\n if xi is not None:\n # Compute edges (to overlay to heatmaps later)\n xi_greyscale = xi if len(xi.shape) == 2 else np.mean(xi, axis=-1)\n in_image_upscaled = transform.rescale(xi_greyscale, dilation, mode='constant')\n edges = feature.canny(in_image_upscaled).astype(float)\n edges[edges < 0.5] = np.nan\n edges[:5, :] = np.nan\n edges[-5:, :] = np.nan\n edges[:, :5] = np.nan\n edges[:, -5:] = np.nan\n overlay = edges\n\n abs_max = np.percentile(np.abs(data), percentile)\n abs_min = abs_max\n\n if len(data.shape) == 3:\n data = np.mean(data, 2)\n axis.imshow(data, extent=extent, interpolation='none', cmap=cmap, vmin=-abs_min, vmax=abs_max)\n if overlay is not None:\n axis.imshow(overlay, extent=extent, interpolation='none', cmap=cmap_xi, alpha=alpha)\n axis.axis('off')\n return axis\n\n\ndef plot_attribution_maps(name, xs, attributions, names, idxs=None, percentile=100, dilation=3.0, alpha=0.8, show_original=False):\n if idxs is None:\n idxs = list(range(len(attributions[0])))\n if show_original:\n names.insert(0, 'Input')\n rows = len(idxs)\n cols = len(names)\n fig, axes = plt.subplots(nrows=rows, ncols=cols, figsize=(12, 2*rows))\n for ax, col in zip(axes[0] if _isiterable(axes[0]) else axes, names):\n ax.set_title(col, fontsize= 14)\n\n for i, idx in enumerate(idxs):\n if show_original:\n ax = axes[i, 0] if _isiterable(axes[0]) else axes[0]\n ax.axis('off')\n ax.imshow(xs[idx])\n\n for j, attribution in enumerate(attributions):\n if show_original:\n j += 1\n ax = axes[i, j] if _isiterable(axes[0]) else axes[j]\n attribution_map = attribution[idx]\n original_sample = xs[idx]\n plot(attribution_map, original_sample, axis=ax, percentile=percentile, dilation=dilation, alpha=alpha)\n fig.tight_layout()\n plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0.1, hspace=0.2)\n\n plt.show()\n fig.savefig(get_plot_filename('maps', name), bbox_inches = \"tight\")\n\n\ndef _compare_attributions(attributions, metric='mse'):\n n = attributions[0].shape[0]\n values = np.zeros((len(attributions), len(attributions), n))\n\n for i, a1 in enumerate(attributions):\n for j, a2 in enumerate(attributions):\n for idx in range(n):\n if i >= j:\n x1 = np.array(a1[idx]).reshape(-1)\n x2 = np.array(a2[idx]).reshape(-1)\n v = np.nan\n if metric == 'mse':\n v = (np.mean((x1-x2)**2.0))**0.5\n elif metric == 'corr':\n v = scipy.stats.spearmanr(x1, x2)[0]\n values[i, j, idx] = v\n values[j, i, idx] = values[i, j, idx, ]\n return values\n\n\ndef _plot_boxplot(plot_data, permuted_names, yaxis, experiment_name):\n fig, ax = plt.subplots(figsize=(6, 3))\n bplot = ax.boxplot(plot_data, showfliers=False, patch_artist=True, medianprops=dict(color=\"#FF0000AA\"), )\n ax.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',\n alpha=0.5)\n\n ax.yaxis.set_major_formatter(FormatStrFormatter('%.2f'))\n\n # fill with colors\n for bplot in (bplot, ):\n for patch, name in zip(bplot['boxes'], permuted_names):\n patch.set_facecolor(color_for_label(name))\n\n ## change color and linewidth of the whiskers\n for whisker in bplot['whiskers']:\n whisker.set(color='#222222', linewidth=1)\n\n ## change color and linewidth of the caps\n for cap in bplot['caps']:\n cap.set(color='#222222', linewidth=1)\n\n # Set the borders to a given color...\n ax.tick_params(color=\"#666666\", labelcolor=\"#666666\")\n for spine in ax.spines.values():\n spine.set_edgecolor(\"#666666\")\n\n plt.ylabel(yaxis)\n plt.tick_params(color=\"#222222\", labelcolor=\"#222222\")\n ax.set_xticklabels(permuted_names,rotation=0, fontsize=12)\n plt.subplots_adjust(left=0.1, bottom=0.2, right=1, top=0.95, wspace=0.0, hspace=0.0)\n fig.savefig(get_plot_filename(yaxis.split(\" \")[0].lower(), experiment_name))\n\n\ndef plot_mse_comparison(name, attributions, names, gt_idx=None):\n\n plot_data = _compare_attributions(attributions, metric='mse')\n plot_data = plot_data[gt_idx, :, :]\n\n permutation = np.argsort(-np.mean(plot_data, 1))\n\n plot_data = plot_data[permutation]\n\n permuted_names = [names[i] for i in permutation]\n gt_permuted_index = permuted_names.index(names[gt_idx])\n\n plot_data = plot_data.tolist()\n plot_data.pop(gt_permuted_index)\n permuted_names.pop(gt_permuted_index)\n\n _plot_boxplot(plot_data, permuted_names, 'RMSE', name)\n\n\ndef plot_correlation_comparison(name, attributions, names, gt_idx=None):\n\n plot_data = _compare_attributions(attributions, metric='corr')\n plot_data = plot_data[gt_idx, :, :]\n\n permutation = np.argsort(np.mean(plot_data, 1))\n\n plot_data = plot_data[permutation]\n\n permuted_names = [names[i] for i in permutation]\n gt_permuted_index = permuted_names.index(names[gt_idx])\n\n plot_data = plot_data.tolist()\n plot_data.pop(gt_permuted_index)\n permuted_names.pop(gt_permuted_index)\n\n _plot_boxplot(plot_data, permuted_names, \"Spearman's rank correlation\", name)\n"
]
| [
[
"numpy.amax",
"numpy.abs",
"numpy.amin",
"numpy.arange",
"scipy.stats.spearmanr",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.get_cmap",
"numpy.mean",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.ticker.FormatStrFormatter",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.tick_params",
"matplotlib.pyplot.ylabel"
]
]
|
anrahman1/ARMS | [
"c569bc215d30fd6318e627c9600e9463aaeb2293"
]
| [
"Alex Code/deep_experiment.py"
]
| [
"\"\"\"Adapted from http://www.wildml.com/2015/12/implementing-a-cnn-for-text-classification-in-tensorflow/\"\"\"\nimport math\nimport os\n\nimport tensorflow as tf\nimport numpy as np\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.metrics.classification import accuracy_score\n\nfrom seq_deep_cnn import SeqDeepCNN\nfrom load_data import load_data_subset, pad_examples, convert_labels\nfrom length_threshold import get_examples_below_length_threshold\nfrom statistics import mean\n\n# Test data\neval_test_performance = True\n\n# Experiment parameters\nnum_folds = 3\nnum_epochs = 800\nbatch_size = 10\nlength_threshold = 0.95\n\n# Model parameters\nfilter_length = [30, 30]\nnum_filters = [60, 1000]\npool_window = 10\n\ndropout_keep_prob = 0.7\n\n# Cross validation model tracking\ncrossval_models = []\ncrossval_accuracies = []\ncrossval_training_accuracies = []\n\n\"\"\"Helper functions for getting epochs & batches\"\"\"\n\ndef shuffle_for_epoch(X, y):\n size = X.shape[0]\n shuffle_indicies = np.random.permutation(size)\n return X[shuffle_indicies], y[shuffle_indicies]\n\n\ndef get_batch(X, y, batch_num, batch_size):\n start = batch_num * batch_size\n end = (batch_num + 1) * batch_size\n\n if end >= X.shape[0]:\n return X[start:], y[start:]\n else:\n return X[start:end], y[start:end]\n\n\n\"\"\"Get Data\"\"\"\nexamples, labels = load_data_subset(indices_path=\"Data/train_indices.csv\")\nlength_threshold, examples, labels = get_examples_below_length_threshold(examples, labels, threshold=length_threshold)\n\nX, X_masks = pad_examples(examples)\ny = convert_labels(labels, sorted(list(set(labels))))\n\n\"\"\"Split off validation set\"\"\"\nsss = StratifiedShuffleSplit(1, train_size=0.8)\nfor train_index, val_idex in sss.split(X=X, y=y):\n X_train = X[train_index]\n y_train = y[train_index]\n X_val = X[val_idex]\n y_val = y[val_idex]\n\nfor fold in range(num_folds):\n \"\"\"Split off cross validation fold\"\"\"\n sss = StratifiedShuffleSplit(1, train_size=0.8)\n for train_index, crossval_index in sss.split(X=X_train, y=y_train):\n X_trainfold = X_train[train_index]\n y_trainfold = y_train[train_index]\n X_valfold = X_train[crossval_index]\n y_valfold = y_train[crossval_index]\n\n with tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=True,\n )\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n\n seq_cnn = SeqDeepCNN(\n sequence_length=X.shape[1],\n num_classes=y.shape[1],\n filter_lengths=filter_length,\n num_filters=num_filters,\n pool_window=pool_window,\n dropout_keep=dropout_keep_prob\n )\n\n \"\"\" Configure optimizer \"\"\"\n global_step = tf.Variable(0, name=\"global_step\", trainable=False)\n optimizer = tf.train.AdamOptimizer(1e-4)\n gradients = optimizer.compute_gradients(seq_cnn.loss)\n train_op = optimizer.apply_gradients(gradients, global_step=global_step)\n\n \"\"\" Initialize \"\"\"\n sess.run(tf.initialize_all_variables())\n\n \"\"\" Set up model saving, model for fold 1 saved in Models/1/ \"\"\"\n checkpoint_dir = os.path.abspath(os.path.join(\"Models\", str(fold)))\n if not os.path.exists(checkpoint_dir):\n os.makedirs(checkpoint_dir)\n saver = tf.train.Saver(tf.all_variables())\n checkpoint_prefix = os.path.join(checkpoint_dir, \"model\")\n\n \"\"\" Training procedure \"\"\"\n num_batches = math.floor(X_trainfold.shape[0] / batch_size)\n for epoch in range(num_epochs):\n # at every epoch, shuffle the data\n X_shuff, y_shuff = shuffle_for_epoch(X_trainfold, y_trainfold)\n for b in range(num_batches):\n x_batch, y_batch = get_batch(X_shuff, y_shuff, batch_num=b, batch_size=batch_size)\n\n feed_dict = {\n seq_cnn.X: x_batch,\n seq_cnn.y: y_batch\n }\n\n _, loss, step = sess.run(\n [train_op, seq_cnn.loss, global_step],\n feed_dict=feed_dict\n )\n\n print(\"fold: {} step: {}, loss {:g}\".format(fold, step, loss))\n\n \"\"\" Evaluate on cross-validation fold \"\"\"\n feed_dict = {\n seq_cnn.X: X_valfold,\n seq_cnn.y: y_valfold\n }\n\n predictions = sess.run(seq_cnn.predictions, feed_dict=feed_dict)\n # have to convert y_val back from one_hot into class number\n y_val_classes = np.array([np.argmax(y_val_i) for y_val_i in y_valfold])\n accuracy = accuracy_score(y_true=y_val_classes, y_pred=predictions)\n\n \"\"\" Get training accuracy for diagnostic purposes\"\"\"\n training_feed_dict = {\n seq_cnn.X: X_trainfold,\n seq_cnn.y: y_trainfold\n }\n training_predictions = sess.run(seq_cnn.predictions, feed_dict=training_feed_dict)\n y_train_classes = np.array([np.argmax(y_train_i) for y_train_i in y_trainfold])\n training_accuracy = accuracy_score(y_true=y_train_classes, y_pred=training_predictions)\n\n # Save model 'checkpoint' (all weights) in a temp directory\n model_path = saver.save(sess, checkpoint_prefix)\n crossval_models.append(model_path)\n\n # Record accuracy on current fold for model comparison\n crossval_accuracies.append(accuracy)\n crossval_training_accuracies.append(training_accuracy)\n print(\"Accuracy for fold {}: {}\".format(fold, accuracy))\n\nprint('\\nAccuracies\\n')\nfor acc in crossval_accuracies:\n print(acc)\n\nprint('Mean crossval accuracy: {}'.format(mean(crossval_accuracies)))\n\nbest_model_ID = crossval_accuracies.index(max(crossval_accuracies))\nprint('Best performing model: {}'.format(best_model_ID))\nprint('With training accuracy: {}\\n'.format(crossval_training_accuracies[best_model_ID]))\n\n\"\"\" Evaluate best performing model on validation set \"\"\"\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=True,\n )\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n seq_cnn = SeqDeepCNN(\n sequence_length=X.shape[1],\n num_classes=y.shape[1],\n filter_lengths=filter_length,\n num_filters=num_filters,\n pool_window=pool_window\n )\n\n\n saver = tf.train.Saver(tf.all_variables())\n saver.restore(sess, crossval_models[best_model_ID])\n\n feed_dict = {\n seq_cnn.X: X_val,\n seq_cnn.y: y_val\n }\n\n predictions = sess.run(seq_cnn.predictions, feed_dict=feed_dict)\n # have to convert y_val back from one_hot into class number\n y_val_classes = np.array([np.argmax(y_val_i) for y_val_i in y_val])\n accuracy = accuracy_score(y_true=y_val_classes, y_pred=predictions)\n\nprint(\"Final accuracy: {}\".format(accuracy))\n\nif not eval_test_performance:\n exit()\n\n\"\"\" Evaluate best performing model on test set \"\"\"\n\nprint(\"Running test data\")\n\n# Get test data\nexamples_test, labels_test = load_data_subset(indices_path=\"Data/test_indices.csv\")\nX_test, _ = pad_examples(examples_test)\n\n# Test examples have to be truncated to length calculated from training set\nX_test = X_test[:, :X.shape[1]]\n\nprint(X_test.shape)\n\nlabelset_test = sorted(list(set(labels_test)))\n\ny_test = convert_labels(labels_test, labelset_test)\n\nwith tf.Graph().as_default():\n session_conf = tf.ConfigProto(\n allow_soft_placement=True,\n )\n sess = tf.Session(config=session_conf)\n with sess.as_default():\n seq_cnn = SeqDeepCNN(\n sequence_length=X_test.shape[1],\n num_classes=y_test.shape[1],\n filter_lengths=filter_length,\n num_filters=num_filters,\n pool_window=pool_window\n )\n\n\n saver = tf.train.Saver(tf.all_variables())\n saver.restore(sess, crossval_models[best_model_ID])\n\n feed_dict = {\n seq_cnn.X: X_test,\n seq_cnn.y: y_test\n }\n\n predictions = sess.run(seq_cnn.predictions, feed_dict=feed_dict)\n # have to convert y_val back from one_hot into class number\n y_test_classes = np.array([np.argmax(y_test_i) for y_test_i in y_test])\n accuracy = accuracy_score(y_true=y_test_classes, y_pred=predictions)\n print(\"Final test data accuracy: {}\".format(accuracy))\n\n print('\\nPer class accuracies')\n for test_class, test_label_display in enumerate(labelset_test):\n class_indices = [i for i in range(y_test.shape[0]) if np.argmax(y_test[i]) == test_class]\n\n X_class_test = X_test[class_indices]\n y_class_test = y_test[class_indices]\n\n feed_dict = {\n seq_cnn.X: X_class_test,\n seq_cnn.y: y_class_test\n }\n\n class_predictions = sess.run(seq_cnn.predictions, feed_dict=feed_dict)\n class_y_categorical = np.array([np.argmax(y_test_i) for y_test_i in y_class_test])\n class_accuracy = accuracy_score(y_true=class_y_categorical, y_pred=class_predictions)\n\n print(\"Class: {}, Ex: {}, Accuracy: {}\".format(test_label_display, len(X_class_test), class_accuracy))\n\n\n\n\n"
]
| [
[
"tensorflow.Graph",
"tensorflow.all_variables",
"tensorflow.Variable",
"tensorflow.ConfigProto",
"tensorflow.initialize_all_variables",
"numpy.random.permutation",
"numpy.argmax",
"tensorflow.Session",
"tensorflow.train.AdamOptimizer",
"sklearn.metrics.classification.accuracy_score",
"sklearn.model_selection.StratifiedShuffleSplit"
]
]
|
ankit-1517/CIFAR10-with-ResNet | [
"d1e22ab20df005cd6a982ea29b39019b1874c953"
]
| [
"src/cifar_test_ln.py"
]
| [
"import pandas as pd \nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nimport torch\nimport torchvision\nimport torchvision.transforms as transforms\nfrom sklearn.model_selection import train_test_split\nfrom torch.utils.data import TensorDataset, DataLoader, RandomSampler, SequentialSampler\nfrom sklearn.metrics import classification_report\nfrom sklearn.metrics import accuracy_score\nimport pickle\nimport torch.optim as optim\n\n\ndef run_full_code_ln(device, model_file, test_data_file, output_file, n):\n\n\tdef unpickle(file):\n\t\twith open(file, 'rb') as fo:\n\t\t\tdict = pickle.load(fo, encoding='bytes')\n\t\treturn dict\n\n\tdef normalise(X):\n\t\treturn (X - X.mean(axis = 0))/(X.std(axis = 0) + (np.ones((1,X.shape[1]))*(1e-06)))\n\t\n\tdict6 = unpickle(test_data_file)\n\tXtest = np.array(dict6[b'data'])\n\t# Ytest = np.array(dict6[b'labels'])\n\tXtest = normalise(Xtest)\n\tXtest = Xtest.reshape(10000, 3, 32, 32)\n\tXtest = torch.from_numpy(Xtest)\n\t# Ytest = Ytest.astype(int)\n\t# Ytest = torch.from_numpy(Ytest)\n\tXtest = Xtest.to(torch.float32)\n\t# Ytest = Ytest.to(torch.int64)\n\n\tclass LambdaLayer(nn.Module):\n\t\tdef __init__(self, lambd):\n\t\t\tsuper(LambdaLayer, self).__init__()\n\t\t\tself.lambd = lambd\n\n\t\tdef forward(self, x):\n\t\t\treturn self.lambd(x)\n\n\tclass Layer_Normalisation(nn.Module):\n\t\tdef __init__(self, numlayer):\n\t\t\tsuper().__init__()\n\t\t\tself.gamma = nn.Parameter(torch.ones((1, numlayer, 1, 1)), requires_grad = True)\n\t\t\tself.beta = nn.Parameter(torch.zeros((1, numlayer, 1, 1)), requires_grad = True)\n\t\t\tself.eps = 1e-6\n\t\tdef forward(self, x):\n\t\t\tmean = x.mean(dim = (1, 2, 3), keepdim=True)\n\t\t\tvar = ((x - mean)**2).mean(dim = (1, 2, 3), keepdim=True)\n\t\t\tx = (x - mean) / torch.sqrt(var + self.eps)\n\t\t\tx = self.gamma * x + self.beta \n\t\t\treturn x\n\n\tclass ResNetBlock(nn.Module):\n\t\tdef __init__(self, numlayer, n):\n\t\t\tsuper(ResNetBlock, self).__init__()\n\t\t\tself.conv1 = nn.Conv2d(numlayer, numlayer, 3, padding = 1)\n\t\t\tself.layer_norm1 = Layer_Normalisation(numlayer)\n\t\t\tself.conv2 = nn.Conv2d(numlayer, numlayer, 3, padding = 1)\n\t\t\tself.layer_norm2 = Layer_Normalisation(numlayer)\n\t\tdef forward(self, x):\n\t\t\ty = x\n\t\t\tx = self.conv1(x)\n\t\t\tx = self.layer_norm1(x)\n\t\t\tx = F.relu(x)\n\t\t\tx = self.conv2(x)\n\t\t\tx = self.layer_norm2(x)\n\t\t\tx = x + y\n\t\t\tx = F.relu(x);\n\t\t\treturn x\n\n\tclass ResNet_Layer(nn.Module):\n\t\tdef __init__(self, numlayer, n):\n\t\t\tsuper(ResNet_Layer, self).__init__()\n\t\t\tself.conv_blocs = nn.Sequential(*[ResNetBlock(numlayer, n)\n\t\t\t\tfor i in range(0, n)])\n\t\tdef forward(self, x):\n\t\t\tx = self.conv_blocs(x);\n\t\t\treturn x\n\n\tclass ResNet_Downsample(nn.Module):\n\t\tdef __init__(self, numlayerin, numlayerout, n):\n\t\t\tsuper(ResNet_Downsample, self).__init__()\n\t\t\tself.conv1 = nn.Conv2d(numlayerin, numlayerout, 3, stride = 2, padding = 1)\n\t\t\tself.layer_norm1 = Layer_Normalisation(numlayerout)\n\t\t\tself.conv2 = nn.Conv2d(numlayerout, numlayerout, 3, padding = 1)\n\t\t\tself.layer_norm2 = Layer_Normalisation(numlayerout)\n\t\t\tself.s1A = LambdaLayer(lambda x: F.pad(x[:, :, ::2, ::2], (0, 0, 0, 0, int(numlayerin/2), int(numlayerin/2)), \"constant\", 0))\n\t\tdef forward(self, x):\n\t\t\ty = x\n\t\t\tx = self.conv1(x)\n\t\t\tx = self.layer_norm1(x)\n\t\t\tx = F.relu(x)\n\t\t\tx = self.conv2(x)\n\t\t\tx = self.layer_norm2(x)\n\t\t\tx = x + self.s1A(y)\n\t\t\tx = F.relu(x)\n\t\t\treturn x\n\n\tclass ResNet(nn.Module):\n\t\tdef __init__(self, n1, r1):\n\t\t\tsuper(ResNet, self).__init__()\n\t\t\tself.n = n1\n\t\t\tself.r = r1\n\t\t\tself.conv_3_16 = nn.Conv2d(3, 16, 3, padding = 1)\n\t\t\tself.layer_norm1 = Layer_Normalisation(16)\n\t\t\tself.resnet_layer1 = ResNet_Layer(16, n1)\n\t\t\tself.resnet_block1 = ResNet_Downsample(16, 32, n1)\n\t\t\tself.resnet_layer2 = ResNet_Layer(32, n1-1)\n\t\t\tself.resnet_block2 = ResNet_Downsample(32, 64, n1)\n\t\t\tself.resnet_layer3 = ResNet_Layer(64, n1-1)\n\t\t\tself.globalAvg = nn.AdaptiveAvgPool2d((1, 1))\n\t\t\tself.fc1 = nn.Linear(64, self.r)\n\t\tdef forward(self, x):\n\t\t\tx = self.conv_3_16(x)\n\t\t\tx = self.layer_norm1(x)\n\t\t\tx = F.relu(x)\n\t\t\tx = self.resnet_layer1(x)\n\t\t\tx = self.resnet_block1(x)\n\t\t\tx = self.resnet_layer2(x)\n\t\t\tx = self.resnet_block2(x)\n\t\t\tx = self.resnet_layer3(x)\n\t\t\t#Global average pooling\n\t\t\tx = self.globalAvg(x)\n\n\t\t\ty = x.view(-1, 64)\n\t\t\tx = self.fc1(y) \n\t\t\treturn x, y \n\n\tmodel = ResNet(n, 10)\n\tmodel.load_state_dict(torch.load(model_file))\n\tmodel = model.to(device)\n\n\tlen_Xtest = Xtest.shape[0]\n\tfinal_preds = np.array([]).reshape((0, 10))\n\tbatch_size = 128\n\tfor i in range(0, (len_Xtest//batch_size)):\n\t\tx = torch.FloatTensor(Xtest[i*batch_size:(i+1)*batch_size, :]).to(device)\n\t\twith torch.no_grad(): \n\t\t\tpreds, _ = model(x)\n\t\t\tfinal_preds = np.vstack((final_preds, preds.detach().cpu().numpy())) \n\tif(len_Xtest - ((len_Xtest//batch_size)*batch_size) > 0):\n\t\tx = torch.FloatTensor(Xtest[((len_Xtest//batch_size)*batch_size):len_Xtest, :]).to(device)\n\t\twith torch.no_grad(): \n\t\t\tpreds, _ = model(x)\n\t\t\tfinal_preds = np.vstack((final_preds, preds.detach().cpu().numpy()))\n\tprint(final_preds.shape)\n\tfinal_preds = final_preds.argmax(axis = 1)\n\tfinal_preds = final_preds.reshape(final_preds.shape[0])\n\n\n\t# # get predictions for val data\n\t# with torch.no_grad():\n\t# \tpreds, _ = model(Xtest.to(device))\n\t# \tpreds = preds.detach().cpu().numpy()\n\t# # prediction\n\t# prediction = preds.argmax(axis = 1)\n\ts = \"\"\n\tfor x in final_preds:\n\t\ts += str(x) + \"\\n\"\n\twith open(output_file, \"w\") as f:\n\t\tf.write(s)\n\n"
]
| [
[
"torch.ones",
"torch.load",
"torch.zeros",
"torch.sqrt",
"torch.nn.Conv2d",
"torch.from_numpy",
"numpy.ones",
"torch.nn.Linear",
"torch.nn.functional.relu",
"torch.nn.AdaptiveAvgPool2d",
"torch.no_grad",
"torch.FloatTensor",
"numpy.array"
]
]
|
Cannizza-zzk/DL_review | [
"3a329742c4d90727ba341508afec0b4fb0123d5d"
]
| [
"assignments/nndl-exercise/chap14_reinforcement_learning/RL_QG_agent.py"
]
| [
"import tensorflow as tf\nimport os\n\nclass RL_QG_agent:\n def __init__(self):\n self.model_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), \"Reversi\")\n pass # ๅ ๆ่ฟๅฅ่ฏ๏ผๅนถๅกซๅ็ธๅบไปฃ็ \n\n def init_model(self):\n\n # ๅฎไน่ชๅทฑ็ ็ฝ็ป\n self.sess = tf.Session()\n self.saver = tf.train.Saver()\n # ่กฅๅ
จไปฃ็ \n\n\n def place(self,state,enables):\n # ่ฟไธชๅฝๆฐ ไธป่ฆ็จไบๆต่ฏ๏ผ ่ฟๅ็ actionๆฏ 0-63 ไน้ด็ไธไธชๆฐๅผ๏ผ\n # action ่กจ็คบ็ๆฏ ่ฆไธ็ไฝ็ฝฎใ\n action = 123456789 # ๅ ๆ่ฟๅฅ่ฏ๏ผๅนถๅกซๅ็ธๅบไปฃ็ \n\n return action\n\n def save_model(self): # ไฟๅญ ๆจกๅ\n self.saver.save(self.sess, os.path.join(self.model_dir, 'parameter.ckpt'))\n\n def load_model(self):# ้ๆฐๅฏผๅ
ฅๆจกๅ\n self.saver.restore(self.sess, os.path.join(self.model_dir, 'parameter.ckpt'))\n\n # ๅฎไน่ชๅทฑ้่ฆ็ๅฝๆฐ"
]
| [
[
"tensorflow.train.Saver",
"tensorflow.Session"
]
]
|
david8862/tensorflow | [
"3957de13a5e7872143317f4d2721f7bf826da329"
]
| [
"tensorflow/python/compiler/tensorrt/trt_convert.py"
]
| [
"# 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\"\"\"Exposes the Python wrapper conversion to trt_graph.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport collections\nimport os\nimport platform\nimport tempfile\n\nimport six as _six\n\nfrom tensorflow.compiler.tf2tensorrt import wrap_py_utils\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.core.protobuf import meta_graph_pb2\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python.client import session\nfrom tensorflow.python.eager import context\nfrom tensorflow.python.eager import def_function\nfrom tensorflow.python.eager import wrap_function\nfrom tensorflow.python.framework import convert_to_constants\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import errors\nfrom tensorflow.python.framework import graph_util\nfrom tensorflow.python.framework import importer\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.grappler import tf_optimizer\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import gen_resource_variable_ops\nfrom tensorflow.python.platform import tf_logging\nfrom tensorflow.python.saved_model import builder\nfrom tensorflow.python.saved_model import load\nfrom tensorflow.python.saved_model import loader\nfrom tensorflow.python.saved_model import save\nfrom tensorflow.python.saved_model import signature_constants\nfrom tensorflow.python.saved_model import tag_constants\nfrom tensorflow.python.training import saver\nfrom tensorflow.python.training.tracking import tracking\nfrom tensorflow.python.util.lazy_loader import LazyLoader\n\n# Lazily load the op, since it's not available in cpu-only builds. Importing\n# this at top will cause tests that imports TF-TRT fail when they're built\n# and run without CUDA/GPU.\ngen_trt_ops = LazyLoader(\n \"gen_trt_ops\", globals(),\n \"tensorflow.compiler.tf2tensorrt.ops.gen_trt_ops\")\n\n# Register TRT ops in python, so that when users import this module they can\n# execute a TRT-converted graph without calling any of the methods in this\n# module.\nif wrap_py_utils.is_tensorrt_enabled():\n if platform.system() == \"Windows\":\n raise RuntimeError(\"Windows platform is not supported\")\n\n # This will call register_op_list() in\n # tensorflow/python/framework/op_def_registry.py, but it doesn't register\n # the op or the op kernel in C++ runtime.\n gen_trt_ops.trt_engine_op # pylint: disable=pointless-statement\n\n\ndef _to_bytes(s):\n \"\"\"Encode s if it is a sequence of chars.\"\"\"\n if isinstance(s, _six.text_type):\n return s.encode(\"utf-8\", errors=\"surrogateescape\")\n return s\n\n\ndef _to_string(s):\n \"\"\"Decode s if it is a sequence of bytes.\"\"\"\n if isinstance(s, _six.binary_type):\n return s.decode(\"utf-8\")\n return s\n\n\nclass GraphConverter(object):\n \"\"\"Base class for offline converters to optimize SavedModels/GraphDefs.\n\n A `GraphConverter` object encapsulates the environment to convert (optimize) a\n TensorFlow SavedModel or GraphDef.\n\n To create a custom GraphConverter:\n\n ```python\n class MyGraphConverter(GraphConverter):\n ...\n\n def get_rewriter_config(self):\n my_rewriter_config = ...\n return my_rewriter_config\n ```\n\n Then to run the conversion without quantization calibration:\n\n ```python\n my_converter = MyGraphConverter(input_saved_model_dir=\"my_dir\")\n converted_graph_def = my_converter.convert()\n my_converter.save(output_saved_model_dir) # Optional\n ```\n\n To run the conversion with quantization calibration:\n\n ```python\n my_converter = MyGraphConverter(input_saved_model_dir=\"my_dir\")\n my_converter.convert()\n\n # Run calibration 10 times.\n converted_graph_def = my_converter.calibrate(\n fetch_names=['output:0'],\n num_runs=10,\n feed_dict_fn=lambda: {'input:0': my_next_data()})\n\n my_converter.save(output_saved_model_dir) # Optional\n ```\n \"\"\"\n\n # TODO(laigd): clean up the parameters.\n def __init__(self,\n input_saved_model_dir=None,\n input_saved_model_tags=None,\n input_saved_model_signature_key=None,\n input_graph_def=None,\n nodes_blacklist=None,\n session_config=None):\n \"\"\"Initialize the converter.\n\n Args:\n input_saved_model_dir: the directory to load the SavedModel which contains\n the input graph to transforms. Used only when input_graph_def is None.\n input_saved_model_tags: list of tags to load the SavedModel.\n input_saved_model_signature_key: the key of the signature to optimize the\n graph for.\n input_graph_def: a GraphDef object containing a model to be transformed.\n If set to None, the graph will be read from the SavedModel loaded from\n input_saved_model_dir.\n nodes_blacklist: list of node names to prevent the converter from\n touching.\n session_config: the ConfigProto used to create a Session. It's also used\n as a template to create a RewriterConfig for conversion. If not\n specified, a default ConfigProto will be used.\n\n Raises:\n ValueError: if the combination of the parameters is invalid.\n \"\"\"\n if input_graph_def and input_saved_model_dir:\n raise ValueError(\n \"Can only specify one of input_graph_def and input_saved_model_dir\")\n if not input_graph_def and not input_saved_model_dir:\n raise ValueError(\"Must specify one of input_graph_def and \"\n \"input_saved_model_dir\")\n\n self._input_graph_def = input_graph_def\n self._nodes_blacklist = nodes_blacklist\n\n self._input_saved_model_dir = input_saved_model_dir\n self._converted = False\n self._grappler_meta_graph_def = None\n\n self._input_saved_model_tags = (\n input_saved_model_tags or [tag_constants.SERVING])\n self._input_saved_model_signature_key = (\n input_saved_model_signature_key or\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY)\n self._session_config = session_config or config_pb2.ConfigProto()\n\n # For calibration usage.\n self._calibration_graph = None\n self._calibration_sess = None\n self._calibration_data_collected = False\n\n def get_rewriter_config(self):\n \"\"\"Returns a RewriterConfig proto for TRT transformation.\n\n Returns:\n A RewriterConfig proto which will be used to run the conversion using\n Grappler.\n \"\"\"\n raise NotImplementedError(\"get_rewriter_config\")\n\n def _run_conversion(self):\n \"\"\"Run Grappler's OptimizeGraph() tool to convert the graph.\"\"\"\n # Create custom ConfigProto for Grappler.\n grappler_session_config = config_pb2.ConfigProto()\n grappler_session_config.CopyFrom(self._session_config)\n custom_rewriter_config = self.get_rewriter_config()\n grappler_session_config.graph_options.rewrite_options.CopyFrom(\n custom_rewriter_config)\n\n # Run Grappler.\n self._converted_graph_def = tf_optimizer.OptimizeGraph(\n grappler_session_config,\n self._grappler_meta_graph_def,\n graph_id=b\"tf_graph\")\n self._converted = True\n\n def _add_nodes_blacklist(self):\n if self._nodes_blacklist:\n collection_def = self._grappler_meta_graph_def.collection_def[\"train_op\"]\n blacklist = collection_def.node_list.value\n for i in self._nodes_blacklist:\n if isinstance(i, ops.Tensor):\n blacklist.append(_to_bytes(i.name))\n else:\n blacklist.append(_to_bytes(i))\n\n def _convert_graph_def(self):\n \"\"\"Convert the input GraphDef.\"\"\"\n graph = ops.Graph()\n with graph.as_default():\n importer.import_graph_def(self._input_graph_def, name=\"\")\n self._grappler_meta_graph_def = saver.export_meta_graph(\n graph_def=graph.as_graph_def(add_shapes=True), graph=graph)\n self._add_nodes_blacklist()\n\n self._run_conversion()\n\n def _collections_to_keep(self, collection_keys):\n # TODO(laigd): currently we use the collection key to filter out\n # collections that depend on variable ops, but this may miss some\n # other user-defined collections. A better way would be to use\n # CollectionDef::NodeList for the filtering.\n collections_to_remove = (\n ops.GraphKeys._VARIABLE_COLLECTIONS + [\n ops.GraphKeys.TRAIN_OP, ops.GraphKeys.WHILE_CONTEXT,\n ops.GraphKeys.COND_CONTEXT\n ])\n return [key for key in collection_keys if key not in collections_to_remove]\n\n def _convert_saved_model(self):\n \"\"\"Convert the input SavedModel.\"\"\"\n graph = ops.Graph()\n with session.Session(graph=graph, config=self._session_config) as sess:\n input_meta_graph_def = loader.load(sess, self._input_saved_model_tags,\n self._input_saved_model_dir)\n input_signature_def = input_meta_graph_def.signature_def[\n self._input_saved_model_signature_key]\n\n def _gather_names(tensor_info):\n \"\"\"Get the node names from a TensorInfo.\"\"\"\n return set([tensor_info[key].name.split(\":\")[0] for key in tensor_info])\n\n # Get input and outputs from all SignatureDef.\n output_node_names = _gather_names(input_signature_def.inputs).union(\n _gather_names(input_signature_def.outputs))\n\n # Preserve nodes in collection\n for collection_key in self._collections_to_keep(\n input_meta_graph_def.collection_def):\n for op in sess.graph.get_collection(collection_key):\n if isinstance(op, ops.Operation):\n output_node_names.add(op.name.split(\":\")[0])\n\n # Freeze the variables in the SavedModel graph and copy the frozen\n # graph over.\n frozen_graph_def = graph_util.convert_variables_to_constants(\n sess, sess.graph.as_graph_def(add_shapes=True),\n list(output_node_names))\n self._grappler_meta_graph_def = meta_graph_pb2.MetaGraphDef()\n self._grappler_meta_graph_def.graph_def.CopyFrom(frozen_graph_def)\n\n # Copy the collections that are not variables.\n for collection_key in self._collections_to_keep(\n input_meta_graph_def.collection_def):\n self._grappler_meta_graph_def.collection_def[collection_key].CopyFrom(\n input_meta_graph_def.collection_def[collection_key])\n\n self._add_nodes_blacklist()\n\n # Copy other information.\n self._grappler_meta_graph_def.meta_info_def.CopyFrom(\n input_meta_graph_def.meta_info_def)\n self._grappler_meta_graph_def.signature_def[\n self._input_saved_model_signature_key].CopyFrom(input_signature_def)\n # TODO(laigd): maybe add back AssetFileDef.\n\n self._run_conversion()\n\n def convert(self):\n \"\"\"Run the conversion.\n\n Returns:\n The converted GraphDef for TF 1.x, or the converted ConcreteFunction in TF\n 2.0+.\n \"\"\"\n assert not self._converted\n if self._input_graph_def:\n self._convert_graph_def()\n else:\n self._convert_saved_model()\n return self._converted_graph_def\n\n def calibrate(self,\n fetch_names,\n num_runs,\n feed_dict_fn=None,\n input_map_fn=None):\n \"\"\"Run the calibration and return the calibrated GraphDef.\n\n Args:\n fetch_names: a list of output tensor name to fetch during calibration.\n num_runs: number of runs of the graph during calibration.\n feed_dict_fn: a function that returns a dictionary mapping input names (as\n strings) in the GraphDef to be calibrated to values (e.g. Python list,\n numpy arrays, etc). One and only one of `feed_dict_fn` and\n `input_map_fn` should be specified.\n input_map_fn: a function that returns a dictionary mapping input names (as\n strings) in the GraphDef to be calibrated to Tensor objects. The values\n of the named input tensors in the GraphDef to be calibrated will be\n re-mapped to the respective `Tensor` values during calibration. One and\n only one of `feed_dict_fn` and `input_map_fn` should be specified.\n\n Raises:\n ValueError: if the input combination is invalid.\n RuntimeError: if this method is called in eager mode.\n\n Returns:\n The GraphDef after the calibration.\n \"\"\"\n assert self._converted\n assert not self._calibration_sess\n\n if context.executing_eagerly():\n raise RuntimeError(\"Calibration for TF 2.0 is not supported yet.\")\n\n if (feed_dict_fn and input_map_fn) or (not feed_dict_fn and\n not input_map_fn):\n raise ValueError(\n \"Should specify one and only one of feed_dict_fn and input_map_fn.\")\n\n self._calibration_graph = ops.Graph()\n with self._calibration_graph.as_default():\n fetches = importer.import_graph_def(\n self._converted_graph_def,\n input_map=input_map_fn() if input_map_fn else None,\n return_elements=fetch_names,\n name=\"\")\n self._calibration_sess = session.Session(\n graph=self._calibration_graph, config=self._session_config)\n\n for _ in range(num_runs):\n self._calibration_sess.run(\n fetches, feed_dict=feed_dict_fn() if feed_dict_fn else None)\n\n self.finalize_calibration()\n return self._converted_graph_def\n\n def finalize_calibration(self):\n \"\"\"Clean up calibration resources and finalize the calibration.\n\n Implementations need to close self._calibration_sess before returning.\n \"\"\"\n raise NotImplementedError(\"finalize_calibration\")\n\n def save(self, output_saved_model_dir):\n \"\"\"Save the converted graph as a SavedModel.\n\n Args:\n output_saved_model_dir: construct a SavedModel using the converted\n GraphDef and save it to the specified directory. This option only works\n when the input graph is loaded from a SavedModel, i.e. when\n input_saved_model_dir is specified and input_graph_def is None in\n __init__().\n\n Raises:\n ValueError: if the input to the converter is a GraphDef instead of a\n SavedModel.\n \"\"\"\n assert self._converted\n if self._input_graph_def:\n raise ValueError(\n \"Not able to save to a SavedModel since input is a GraphDef\")\n\n def _restore_collections(dest_graph, src_meta_graph_def, collection_keys):\n \"\"\"Restores collections that we need to keep.\"\"\"\n scope = \"\"\n for key in collection_keys:\n collection_def = src_meta_graph_def.collection_def[key]\n kind = collection_def.WhichOneof(\"kind\")\n if kind is None:\n tf_logging.error(\n \"Cannot identify data type for collection %s. Skipping.\", key)\n continue\n from_proto = ops.get_from_proto_function(key)\n if from_proto and kind == \"bytes_list\":\n proto_type = ops.get_collection_proto_type(key)\n # It is assumed that there are no Variables Keys in collections\n for value in collection_def.bytes_list.value:\n proto = proto_type()\n proto.ParseFromString(value)\n try:\n new_value = from_proto(proto, import_scope=scope)\n except:\n continue\n dest_graph.add_to_collection(key, new_value)\n else:\n field = getattr(collection_def, kind)\n if kind == \"node_list\":\n for value in field.value:\n name = ops.prepend_name_scope(value, scope)\n # Since the graph has been optimized, the node may no longer\n # exists\n try:\n col_op = dest_graph.as_graph_element(name)\n except (TypeError, ValueError, KeyError) as e:\n continue\n dest_graph.add_to_collection(key, col_op)\n elif kind == \"int64_list\":\n # NOTE(opensource): This force conversion is to work around the\n # fact that Python2 distinguishes between int and long, while\n # Python3 has only int.\n for value in field.value:\n dest_graph.add_to_collection(key, int(value))\n else:\n for value in field.value:\n dest_graph.add_to_collection(key,\n ops.prepend_name_scope(value, scope))\n\n # Write the transformed graphdef as SavedModel.\n saved_model_builder = builder.SavedModelBuilder(output_saved_model_dir)\n with ops.Graph().as_default():\n importer.import_graph_def(self._converted_graph_def, name=\"\")\n _restore_collections(\n ops.get_default_graph(), self._grappler_meta_graph_def,\n self._collections_to_keep(\n self._grappler_meta_graph_def.collection_def))\n # We don't use any specific converter here.\n with session.Session(config=self._session_config) as sess:\n saved_model_builder.add_meta_graph_and_variables(\n sess,\n self._input_saved_model_tags,\n signature_def_map=self._grappler_meta_graph_def.signature_def)\n # Ignore other meta graphs from the input SavedModel.\n saved_model_builder.save()\n\n\nclass TrtPrecisionMode(object):\n FP32 = \"FP32\"\n FP16 = \"FP16\"\n INT8 = \"INT8\"\n\n @staticmethod\n def supported_precision_modes():\n return [TrtPrecisionMode.FP32, TrtPrecisionMode.FP16, TrtPrecisionMode.INT8]\n\n\n# Use a large enough number as the default max_workspace_size for TRT engines,\n# so it can produce reasonable performance results with the default.\nDEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES = 1 << 30\n\n# TrtConversionParams encapsulates the parameters that are used for TF-TRT\n# conversion.\nTrtConversionParams = collections.namedtuple(\n \"TrtConversionParams\",\n [\n\n # A template RewriterConfig proto used to create a TRT-enabled\n # RewriterConfig. If None, it will use a default one.\n \"rewriter_config_template\",\n\n # The maximum GPU temporary memory which the TRT engine can use at\n # execution time. This corresponds to the 'workspaceSize' parameter of\n # nvinfer1::IBuilder::setMaxWorkspaceSize().\n \"max_workspace_size_bytes\",\n\n # One of TrtPrecisionMode.supported_precision_modes().\n \"precision_mode\",\n\n # The minimum number of nodes required for a subgraph to be replaced by\n # TRTEngineOp.\n \"minimum_segment_size\",\n\n # Whether to generate dynamic TRT ops which will build the TRT network\n # and engine at run time.\n \"is_dynamic_op\",\n\n # Max number of cached TRT engines in dynamic TRT ops. If the number of\n # cached engines is already at max but none of them can serve the input,\n # the TRTEngineOp will fall back to run the TF function based on which\n # the TRTEngineOp is created.\n \"maximum_cached_engines\",\n\n # This argument is ignored if precision_mode is not INT8. If set to\n # True, a calibration graph will be created to calibrate the missing\n # ranges. The calibration graph must be converted to an inference graph\n # by running calibration with calibrate(). If set to False, quantization\n # nodes will be expected for every tensor in the graph (exlcuding those\n # which will be fused). If a range is missing, an error will occur.\n # Please note that accuracy may be negatively affected if there is a\n # mismatch between which tensors TRT quantizes and which tensors were\n # trained with fake quantization.\n \"use_calibration\",\n\n # If set to True, it will create a FunctionDef for each subgraph that is\n # converted to TRT op, and if TRT ops fail to execute at runtime, it'll\n # invoke that function as a fallback.\n \"use_function_backup\",\n\n # Max size for the input batch.\n # This option is deprecated in TF 2.0.\n \"max_batch_size\",\n ])\n\nDEFAULT_TRT_CONVERSION_PARAMS = TrtConversionParams(\n rewriter_config_template=None,\n max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES,\n precision_mode=TrtPrecisionMode.FP32,\n minimum_segment_size=3,\n is_dynamic_op=False,\n maximum_cached_engines=1,\n use_calibration=True,\n use_function_backup=True,\n max_batch_size=1)\n\n_TRT_ENGINE_CACHE_CONTAINER_NAME = \"TF-TRT-Engine-Cache\"\n_TRT_ENGINE_OP_NAME = \"TRTEngineOp\"\n\n\ndef _check_conversion_params(conversion_params):\n \"\"\"Validate the provided TrtConversionParams.\n\n Args:\n conversion_params: a TrtConversionParams instance.\n\n Raises:\n TypeError: if any of the parameters are of unexpected type.\n ValueError: if any of the parameters are of unexpected value.\n \"\"\"\n supported_precision_modes = TrtPrecisionMode.supported_precision_modes()\n if conversion_params.precision_mode not in supported_precision_modes:\n raise ValueError(\n (\"precision mode '{}' is not supported.\"\n \"It should be one of {}\").format(conversion_params.precision_mode,\n supported_precision_modes))\n\n\ndef _check_trt_version_compatibility():\n \"\"\"Check compatibility of TensorRT version.\n\n Raises:\n RuntimeError: if the TensorRT library version is incompatible.\n \"\"\"\n compiled_version = wrap_py_utils.get_linked_tensorrt_version()\n loaded_version = wrap_py_utils.get_loaded_tensorrt_version()\n tf_logging.info(\"Linked TensorRT version: %s\" % str(compiled_version))\n tf_logging.info(\"Loaded TensorRT version: %s\" % str(loaded_version))\n version_mismatch = False\n if loaded_version[0] < compiled_version[0]:\n tf_logging.error(\n \"TensorRT version mismatch. Tensorflow was compiled against \" +\n \"TensorRT %s but library loaded from environment is TensorRT %s\" %\n (\".\".join([str(x) for x in compiled_version]),\n \".\".join([str(x) for x in loaded_version])) +\n \". Please make sure that correct version of TensorRT \" +\n \"is available in the system and added to ldconfig or LD_LIBRARY_PATH\")\n raise RuntimeError(\"Incompatible TensorRT library version\")\n for i in zip(loaded_version, compiled_version):\n if i[0] != i[1]:\n tf_logging.warn(\"TensorRT mismatch. Compiled against version \" +\n \"%s, but loaded %s. Things may not work\" %\n (\".\".join([str(x) for x in compiled_version]),\n \".\".join([str(x) for x in loaded_version])))\n version_mismatch = True\n break\n if not version_mismatch:\n tf_logging.info(\"Running against TensorRT version %s\" %\n \".\".join([str(x) for x in loaded_version]))\n\n\ndef get_tensorrt_rewriter_config(\n conversion_params=DEFAULT_TRT_CONVERSION_PARAMS, is_v2=False):\n \"\"\"Returns a RewriterConfig proto for TRT transformation.\n\n Args:\n conversion_params: a TrtConversionParams instance.\n is_v2: whether we're getting a RewriterConfig for TF 2.0.\n\n Returns:\n A RewriterConfig proto which sets a TensorRTOptimizer to run Grappler.\n\n Raises:\n TypeError: if any of the parameters are of unexpected type.\n ValueError: if any of the parameters are of unexpected value.\n \"\"\"\n if conversion_params.rewriter_config_template is not None and not isinstance(\n conversion_params.rewriter_config_template,\n rewriter_config_pb2.RewriterConfig):\n raise TypeError(\n \"rewriter_config_template should be a RewriterConfig proto.\")\n _check_conversion_params(conversion_params)\n\n rewriter_config_with_trt = rewriter_config_pb2.RewriterConfig()\n if conversion_params.rewriter_config_template is None:\n # Layout optimizer may add Const nodes followed by Reshape nodes, thus we\n # need to run constant folding again.\n rewriter_config_with_trt.optimizers.extend(\n [\"constfold\", \"layout\", \"constfold\"])\n rewriter_config_with_trt.meta_optimizer_iterations = (\n rewriter_config_pb2.RewriterConfig.ONE)\n else:\n rewriter_config_with_trt.CopyFrom(\n conversion_params.rewriter_config_template)\n\n optimizer = rewriter_config_with_trt.custom_optimizers.add()\n # Add a constfold optimizer to cleanup the unused Const nodes.\n rewriter_config_with_trt.custom_optimizers.add().name = \"constfold\"\n\n optimizer.name = \"TensorRTOptimizer\"\n optimizer.parameter_map[\n \"minimum_segment_size\"].i = conversion_params.minimum_segment_size\n optimizer.parameter_map[\n \"max_workspace_size_bytes\"].i = conversion_params.max_workspace_size_bytes\n optimizer.parameter_map[\"precision_mode\"].s = _to_bytes(\n conversion_params.precision_mode)\n optimizer.parameter_map[\n \"maximum_cached_engines\"].i = conversion_params.maximum_cached_engines\n optimizer.parameter_map[\n \"use_calibration\"].b = conversion_params.use_calibration\n optimizer.parameter_map[\n \"use_function_backup\"].b = conversion_params.use_function_backup\n\n if is_v2:\n # Static mode (a.k.a pre-generating TRT engines and make them node\n # attributes) is deprecated in TF 2.0.\n optimizer.parameter_map[\"is_dynamic_op\"].b = True\n else:\n optimizer.parameter_map[\n \"max_batch_size\"].i = conversion_params.max_batch_size\n optimizer.parameter_map[\"is_dynamic_op\"].b = conversion_params.is_dynamic_op\n return rewriter_config_with_trt\n\n\nclass TrtGraphConverter(GraphConverter):\n \"\"\"A GraphConverter for TRT transformation.\"\"\"\n\n # TODO(laigd): use TrtConversionParams here.\n def __init__(self,\n input_saved_model_dir=None,\n input_saved_model_tags=None,\n input_saved_model_signature_key=None,\n input_graph_def=None,\n nodes_blacklist=None,\n session_config=None,\n max_batch_size=1,\n max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES,\n precision_mode=TrtPrecisionMode.FP32,\n minimum_segment_size=3,\n is_dynamic_op=False,\n maximum_cached_engines=1,\n use_calibration=True,\n use_function_backup=True):\n \"\"\"Initialize the converter.\n\n Args:\n input_saved_model_dir: the directory to load the SavedModel which contains\n the input graph to transforms. Used only when input_graph_def is None.\n input_saved_model_tags: list of tags to load the SavedModel.\n input_saved_model_signature_key: the key of the signature to optimize the\n graph for.\n input_graph_def: a GraphDef object containing a model to be transformed.\n If set to None, the graph will be read from the SavedModel loaded from\n input_saved_model_dir.\n nodes_blacklist: list of node names to prevent the converter from\n touching.\n session_config: the ConfigProto used to create a Session. It's also used\n as a template to create a TRT-enabled ConfigProto for conversion. If not\n specified, a default ConfigProto will be used.\n max_batch_size: max size for the input batch.\n max_workspace_size_bytes: the maximum GPU temporary memory which the TRT\n engine can use at execution time. This corresponds to the\n 'workspaceSize' parameter of nvinfer1::IBuilder::setMaxWorkspaceSize().\n precision_mode: one of TrtPrecisionMode.supported_precision_modes().\n minimum_segment_size: the minimum number of nodes required for a subgraph\n to be replaced by TRTEngineOp.\n is_dynamic_op: whether to generate dynamic TRT ops which will build the\n TRT network and engine at run time.\n maximum_cached_engines: max number of cached TRT engines in dynamic TRT\n ops. If the number of cached engines is already at max but none of them\n can serve the input, the TRTEngineOp will fall back to run the TF\n function based on which the TRTEngineOp is created.\n use_calibration: this argument is ignored if precision_mode is not INT8.\n If set to True, a calibration graph will be created to calibrate the\n missing ranges. The calibration graph must be converted to an inference\n graph by running calibration with calibrate(). If set to False,\n quantization nodes will be expected for every tensor in the graph\n (exlcuding those which will be fused). If a range is missing, an error\n will occur. Please note that accuracy may be negatively affected if\n there is a mismatch between which tensors TRT quantizes and which\n tensors were trained with fake quantization.\n use_function_backup: if set to True, it will create a FunctionDef for each\n subgraph that is converted to TRT op, and if TRT ops fail to execute at\n runtime, it'll invoke that function as a fallback.\n\n Raises:\n ValueError: if the combination of the parameters is invalid.\n \"\"\"\n super(TrtGraphConverter, self).__init__(\n input_saved_model_dir=input_saved_model_dir,\n input_saved_model_tags=input_saved_model_tags,\n input_saved_model_signature_key=input_saved_model_signature_key,\n input_graph_def=input_graph_def,\n nodes_blacklist=nodes_blacklist,\n session_config=session_config)\n _check_trt_version_compatibility()\n\n self._need_calibration = (\n precision_mode == TrtPrecisionMode.INT8 and use_calibration)\n if self._need_calibration and not is_dynamic_op:\n tf_logging.warn(\n \"INT8 precision mode with calibration is supported with \"\n \"dynamic TRT ops only. Disregarding is_dynamic_op parameter.\")\n is_dynamic_op = True\n\n # TODO(laigd): consider provide a mechanism to remove the fallback path\n # after calibration is done.\n if self._need_calibration and not use_function_backup:\n raise ValueError(\n \"Calibration requires enabling fallback to TF function execution.\")\n\n # TODO(laigd):\n # - Verify in int8 mode that maximum_cached_engines is set properly.\n # - If it fails to build the int8 engine it should return error.\n rewriter_config_template = None\n if (session_config and session_config.HasField(\"graph_options\") and\n session_config.graph_options.HasField(\"rewrite_options\")):\n rewriter_config_template = session_config.graph_options.rewrite_options\n\n self._conversion_params = TrtConversionParams(\n rewriter_config_template=rewriter_config_template,\n max_workspace_size_bytes=max_workspace_size_bytes,\n precision_mode=precision_mode,\n minimum_segment_size=minimum_segment_size,\n is_dynamic_op=is_dynamic_op,\n maximum_cached_engines=maximum_cached_engines,\n use_calibration=use_calibration,\n use_function_backup=use_function_backup,\n max_batch_size=max_batch_size)\n _check_conversion_params(self._conversion_params)\n\n def get_rewriter_config(self):\n return get_tensorrt_rewriter_config(\n conversion_params=self._conversion_params)\n\n def finalize_calibration(self):\n assert self._need_calibration\n assert self._converted\n assert not self._calibration_data_collected\n\n # TODO(laigd): a better way would be to use self._calibration_sess to list\n # all the devices, add one get_calibration_data for each device, and\n # fetch each such op for every resource until its found. This can work\n # even when the device of the TRTEngineOp is empty or not fully specified.\n\n # Maps device name to the corresponding get_calibration_data.\n device_to_get_resource_op_map = {}\n\n with self._calibration_graph.as_default():\n resource_name_input = array_ops.placeholder(dtypes.string)\n\n for node in self._converted_graph_def.node:\n if node.op == _TRT_ENGINE_OP_NAME:\n # Adds the get_calibration_data op for the device if not done before.\n # We only add one such op for each device.\n # TODO(laigd): What if the device is empty?????\n if node.device not in device_to_get_resource_op_map:\n with self._calibration_graph.device(node.device):\n serialized_resources_output = (\n gen_trt_ops.get_calibration_data_op(resource_name_input))\n device_to_get_resource_op_map[node.device] = (\n serialized_resources_output)\n\n # Get the calibration resource.\n calibration_result = self._calibration_sess.run(\n device_to_get_resource_op_map[node.device],\n feed_dict={resource_name_input: node.name})\n node.attr[\"calibration_data\"].s = calibration_result\n\n self._calibration_data_collected = True\n self._calibration_sess.close()\n\n def save(self, output_saved_model_dir):\n \"\"\"Save the converted graph as a SavedModel.\"\"\"\n if self._need_calibration:\n assert self._calibration_data_collected\n\n super(TrtGraphConverter, self).save(output_saved_model_dir)\n\n\ndef _get_resource_handle(name, device):\n with ops.device(device):\n return gen_trt_ops.create_trt_engine_cache_handle(\n container=_TRT_ENGINE_CACHE_CONTAINER_NAME, resource_name=name)\n\n\nclass TRTEngineResourceDeleter(tracking.CapturableResourceDeleter):\n \"\"\"Resource deleter for destroying TRT engine cache resource.\"\"\"\n\n def __init__(self, resource_name, device):\n super(TRTEngineResourceDeleter, self).__init__()\n self._resource_name = resource_name\n self._device = device\n\n def destroy_resource(self):\n handle = _get_resource_handle(self._resource_name, self._device)\n with ops.device(self._device):\n gen_resource_variable_ops.destroy_resource_op(\n handle, ignore_lookup_error=True)\n\n\nclass TRTEngineResource(tracking.TrackableResource):\n \"\"\"Class to track the serialized engines resource.\"\"\"\n\n def __init__(self,\n resource_name,\n filename,\n maximum_cached_engines,\n device=\"GPU\"):\n super(\n TRTEngineResource,\n self).__init__(deleter=TRTEngineResourceDeleter(resource_name, device))\n self._resource_name = resource_name\n # Track the serialized engine file in the SavedModel.\n self._filename = self._track_trackable(\n tracking.TrackableAsset(filename), \"_serialized_trt_engine_filename\")\n self._maximum_cached_engines = maximum_cached_engines\n self._device = device\n\n def _create_resource(self):\n return _get_resource_handle(self._resource_name, self._device)\n\n def _initialize(self):\n gen_trt_ops.populate_trt_engine_cache(\n self.resource_handle,\n self._filename,\n max_cached_engines_count=self._maximum_cached_engines)\n\n\nclass TrtGraphConverterV2(object):\n \"\"\"An offline converter for TF-TRT transformation for TF 2.0 SavedModels.\n\n To run the conversion without quantization calibration (e.g. for FP32/FP16\n precision modes):\n\n ```python\n params = DEFAULT_TRT_CONVERSION_PARAMS._replace(precision_mode='FP16')\n converter = TrtGraphConverterV2(\n input_saved_model_dir=\"my_dir\", conversion_params=params)\n converter.convert()\n converter.save(output_saved_model_dir)\n ```\n\n As a result, a TF-TRT converted SavedModel will be generated and saved to\n `output_saved_model_dir`. The SavedModel will have TRT compatible subgraph\n replaced by TRTEngineOps, but no TRT engines will be pre-built until execution\n time. We can also build the TRT engines offline by running the converted\n function with some input data:\n\n ```python\n params = DEFAULT_TRT_CONVERSION_PARAMS._replace(\n precision_mode='FP16',\n # Set this to a large enough number so it can cache all the TRT engines.\n maximum_cached_engines=16)\n converter = TrtGraphConverterV2(\n input_saved_model_dir=\"my_dir\", conversion_params=params)\n converted_func = converter.convert()\n for data in my_input_data:\n converted_func(my_input_data)\n converter.save(output_saved_model_dir)\n ```\n\n In this way, for each unique shapes of the inputs to the TRTEngineOp, if it\n cannot be handled by any previously generated TRT engine, a new engine will be\n generated and serialized to the output SavedModel in `output_saved_model_dir`.\n This is good for applications that cannot afford building TRT engines at\n runtime but have access to input data that is similar to the one used in\n production (for example, that will result in the same input shapes to the\n TRTEngineOps). Also, the generated TRT engines is platform dependent, so we\n need to run `converted_func` in an environment that is similar to production\n (at least with same type of GPU).\n\n TODO(laigd/hinsu): running conversion with calibration in INT8 mode should\n follow exactly the same steps.\n \"\"\"\n\n def __init__(self,\n input_saved_model_dir=None,\n input_saved_model_tags=None,\n input_saved_model_signature_key=None,\n conversion_params=DEFAULT_TRT_CONVERSION_PARAMS):\n \"\"\"Initialize the converter.\n\n Args:\n input_saved_model_dir: the directory to load the SavedModel which contains\n the input graph to transforms. Used only when input_graph_def is None.\n input_saved_model_tags: list of tags to load the SavedModel.\n input_saved_model_signature_key: the key of the signature to optimize the\n graph for.\n conversion_params: a TrtConversionParams instance.\n\n Raises:\n ValueError: if the combination of the parameters is invalid.\n \"\"\"\n assert context.executing_eagerly()\n _check_trt_version_compatibility()\n _check_conversion_params(conversion_params)\n\n self._conversion_params = conversion_params\n self._input_saved_model_dir = input_saved_model_dir\n self._input_saved_model_tags = (\n input_saved_model_tags or [tag_constants.SERVING])\n self._input_saved_model_signature_key = (\n input_saved_model_signature_key or\n signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY)\n\n self._need_calibration = (\n conversion_params.precision_mode == TrtPrecisionMode.INT8 and\n conversion_params.use_calibration)\n if (self._need_calibration and not conversion_params.is_dynamic_op):\n raise ValueError(\"INT8 precision mode with calibration is not supported \"\n \"with static TensorRT ops. Set is_dynamic_op to True.\")\n\n self._converted = False\n\n def _run_conversion(self, meta_graph_def):\n \"\"\"Run Grappler's OptimizeGraph() tool to convert the graph.\n\n Args:\n meta_graph_def: the MetaGraphDef instance to run the optimizations on.\n\n Returns:\n The optimized GraphDef.\n \"\"\"\n rewriter_config = get_tensorrt_rewriter_config(\n conversion_params=self._conversion_params, is_v2=True)\n grappler_session_config = config_pb2.ConfigProto()\n grappler_session_config.graph_options.rewrite_options.CopyFrom(\n rewriter_config)\n return tf_optimizer.OptimizeGraph(\n grappler_session_config, meta_graph_def, graph_id=b\"tf_graph\")\n\n # TODO(laigd): provide a utility function to optimize a ConcreteFunction and\n # use it here (b/124792963).\n def convert(self):\n \"\"\"Convert the input SavedModel in 2.0 format.\n\n Returns:\n The TF-TRT converted Function.\n \"\"\"\n assert not self._converted\n self._saved_model = load.load(self._input_saved_model_dir,\n self._input_saved_model_tags)\n func = self._saved_model.signatures[self._input_saved_model_signature_key]\n frozen_func = convert_to_constants.convert_variables_to_constants_v2(func)\n grappler_meta_graph_def = saver.export_meta_graph(\n graph_def=frozen_func.graph.as_graph_def(), graph=frozen_func.graph)\n\n # Add a collection 'train_op' so that Grappler knows the outputs.\n fetch_collection = meta_graph_pb2.CollectionDef()\n for array in frozen_func.inputs + frozen_func.outputs:\n fetch_collection.node_list.value.append(array.name)\n grappler_meta_graph_def.collection_def[\"train_op\"].CopyFrom(\n fetch_collection)\n\n # Run TRT optimizer in Grappler to convert the graph.\n self._converted_graph_def = self._run_conversion(grappler_meta_graph_def)\n self._converted_func = wrap_function.function_from_graph_def(\n self._converted_graph_def,\n [tensor.name for tensor in frozen_func.inputs],\n [tensor.name for tensor in frozen_func.outputs])\n\n self._converted = True\n\n # Wrap the converted ConcreteFunction in a Function so it can accept numpy\n # arrays as input.\n @def_function.function\n def wrapper_func(*args, **kwargs):\n return self._converted_func(*args, **kwargs)\n\n return wrapper_func\n\n def save(self, output_saved_model_dir):\n \"\"\"Save the converted SavedModel.\n\n Args:\n output_saved_model_dir: directory to saved the converted SavedModel.\n \"\"\"\n assert self._converted\n\n # Serialize the TRT engines in the cache if any, and create trackable\n # resource to track them.\n engine_asset_dir = tempfile.mkdtemp()\n resource_map = {}\n\n def _serialize_and_track_engine(canonical_engine_name):\n \"\"\"Serialize TRT engines in the cache and track them.\"\"\"\n # Don't dump the same cache twice.\n if canonical_engine_name in resource_map:\n return\n\n filename = os.path.join(engine_asset_dir,\n \"trt-serialized-engine.\" + canonical_engine_name)\n try:\n gen_trt_ops.dump_trt_engine_cache(\n container=_TRT_ENGINE_CACHE_CONTAINER_NAME,\n resource_name=canonical_engine_name,\n filename=filename,\n delete_cache_after_dump=True)\n except errors.NotFoundError:\n # If user haven't run the function to populate the engine, it's fine,\n # and we don't need to track any serialized TRT engines.\n return\n\n # TODO(laigd): add an option for the user to choose the device.\n resource_map[canonical_engine_name] = TRTEngineResource(\n canonical_engine_name, filename,\n self._conversion_params.maximum_cached_engines)\n\n # Remove all scope prefixes in the node name. In TF 2.0, the same concrete\n # function can be initialized multiple times with different prefixes, and\n # this will result in the same TRTEngineOp being initialized multiple times\n # with different cache and duplicate TRT engines.\n # TODO(laigd): this may be caused by the fact that TRTEngineOp is not\n # stataful, need to investigate.\n # TODO(laigd): we rely on the fact that all functions are fully inlined\n # before TF-TRT optimizer is called, as otherwise it may generate the same\n # name when optimizing a different function graph. Fix this.\n canonical_engine_name = lambda node: node.name.split(\"/\")[-1]\n for node in self._converted_graph_def.node:\n if node.op == _TRT_ENGINE_OP_NAME:\n _serialize_and_track_engine(canonical_engine_name(node))\n for func in self._converted_graph_def.library.function:\n for node in func.node_def:\n if node.op == _TRT_ENGINE_OP_NAME:\n _serialize_and_track_engine(canonical_engine_name(node))\n\n self._saved_model.trt_engine_resources = resource_map\n\n # Rewrite the signature map using the optimized ConcreteFunction.\n signatures = {\n key: value for key, value in self._saved_model.signatures.items()\n }\n signatures[self._input_saved_model_signature_key] = self._converted_func\n save.save(self._saved_model, output_saved_model_dir, signatures)\n\n\n# TODO(laigd): use TrtConversionParams here.\ndef create_inference_graph(\n input_graph_def,\n outputs,\n max_batch_size=1,\n max_workspace_size_bytes=DEFAULT_TRT_MAX_WORKSPACE_SIZE_BYTES,\n precision_mode=TrtPrecisionMode.FP32,\n minimum_segment_size=3,\n is_dynamic_op=False,\n maximum_cached_engines=1,\n input_saved_model_dir=None,\n input_saved_model_tags=None,\n input_saved_model_signature_key=None,\n output_saved_model_dir=None,\n session_config=None):\n \"\"\"Python wrapper for the TRT transformation.\n\n Args:\n input_graph_def: a GraphDef object containing a model to be transformed. If\n set to None, the graph will be read from the SavedModel loaded from\n input_saved_model_dir.\n outputs: list of tensors or node names for the model outputs. Only used when\n input_graph_def is not None.\n max_batch_size: max size for the input batch.\n max_workspace_size_bytes: the maximum GPU temporary memory which the TRT\n engine can use at execution time. This corresponds to the 'workspaceSize'\n parameter of nvinfer1::IBuilder::setMaxWorkspaceSize().\n precision_mode: one of TrtPrecisionMode.supported_precision_modes().\n minimum_segment_size: the minimum number of nodes required for a subgraph to\n be replaced by TRTEngineOp.\n is_dynamic_op: whether to generate dynamic TRT ops which will build the TRT\n network and engine at run time.\n maximum_cached_engines: max number of cached TRT engines in dynamic TRT ops.\n If the number of cached engines is already at max but none of them can\n serve the input, the TRTEngineOp will fall back to run the TF function\n based on which the TRTEngineOp is created.\n input_saved_model_dir: the directory to load the SavedModel which contains\n the input graph to transforms. Used only when input_graph_def is None.\n input_saved_model_tags: list of tags to load the SavedModel.\n input_saved_model_signature_key: the key of the signature to optimize the\n graph for.\n output_saved_model_dir: if not None, construct a SavedModel using the\n returned GraphDef and save it to the specified directory. This option only\n works when the input graph is loaded from a SavedModel, i.e. when\n input_saved_model_dir is specified and input_graph_def is None.\n session_config: the ConfigProto used to create a Session. It's also used as\n a template to create a TRT-enabled ConfigProto for conversion. If not\n specified, a default ConfigProto will be used.\n\n Returns:\n A GraphDef transformed from input_graph_def (or the SavedModel graph def\n loaded from input_saved_model_dir, if input_graph_def is not present), where\n all TRT compatible subgraphs are replaced with TRTEngineOps, and a TF\n function is added for each of the subgraphs.\n\n If is_dynamic_op is True, each TRTEngineOp will contain a serialized\n subgraph GraphDef, which will be converted to a TRT engine at execution time\n and the TRT engine will be cached for future usage. A new TRT engine will be\n created each time when none of the cached engines match the input shapes. If\n it fails to execute the TRT engine or the number of cached engines reaches\n maximum_cached_engines, the op will fall back to call the corresponding TF\n function.\n\n If is_dynamic_op is False, each TRTEngineOp will contain a serialized TRT\n engine created from the corresponding subgraph. No more engines will be\n created on the fly, and the op will fall back to call the corresponding TF\n function when it fails to execute the engine.\n\n Raises:\n ValueError: if the combination of the parameters is invalid.\n \"\"\"\n trt_converter = TrtGraphConverter(\n input_saved_model_dir=input_saved_model_dir,\n input_saved_model_tags=input_saved_model_tags,\n input_saved_model_signature_key=input_saved_model_signature_key,\n input_graph_def=input_graph_def,\n nodes_blacklist=outputs,\n session_config=session_config,\n max_batch_size=max_batch_size,\n max_workspace_size_bytes=max_workspace_size_bytes,\n precision_mode=precision_mode,\n minimum_segment_size=minimum_segment_size,\n is_dynamic_op=is_dynamic_op,\n maximum_cached_engines=maximum_cached_engines,\n use_calibration=False)\n converted_graph_def = trt_converter.convert()\n if output_saved_model_dir:\n trt_converter.save(output_saved_model_dir)\n return converted_graph_def\n"
]
| [
[
"tensorflow.core.protobuf.meta_graph_pb2.MetaGraphDef",
"tensorflow.python.grappler.tf_optimizer.OptimizeGraph",
"tensorflow.python.framework.convert_to_constants.convert_variables_to_constants_v2",
"tensorflow.python.platform.tf_logging.error",
"tensorflow.python.ops.array_ops.placeholder",
"tensorflow.python.framework.ops.get_from_proto_function",
"tensorflow.python.framework.ops.device",
"tensorflow.python.eager.context.executing_eagerly",
"tensorflow.python.training.tracking.tracking.TrackableAsset",
"tensorflow.compiler.tf2tensorrt.wrap_py_utils.get_linked_tensorrt_version",
"tensorflow.python.saved_model.loader.load",
"tensorflow.core.protobuf.meta_graph_pb2.CollectionDef",
"tensorflow.python.saved_model.builder.SavedModelBuilder",
"tensorflow.python.framework.importer.import_graph_def",
"tensorflow.compiler.tf2tensorrt.wrap_py_utils.is_tensorrt_enabled",
"tensorflow.python.saved_model.save.save",
"tensorflow.python.framework.ops.prepend_name_scope",
"tensorflow.python.client.session.Session",
"tensorflow.compiler.tf2tensorrt.wrap_py_utils.get_loaded_tensorrt_version",
"tensorflow.python.saved_model.load.load",
"tensorflow.core.protobuf.rewriter_config_pb2.RewriterConfig",
"tensorflow.python.platform.tf_logging.warn",
"tensorflow.python.framework.ops.Graph",
"tensorflow.python.eager.wrap_function.function_from_graph_def",
"tensorflow.python.framework.ops.get_default_graph",
"tensorflow.python.ops.gen_resource_variable_ops.destroy_resource_op",
"tensorflow.core.protobuf.config_pb2.ConfigProto",
"tensorflow.python.framework.ops.get_collection_proto_type"
]
]
|
jhfoxliu/iMVP | [
"741c355fbaae3a610cb31f0e34965734f0cd19a4"
]
| [
"iMVP_utils/iMVP_utils/interactive.py"
]
| [
"import os\nimport io\nfrom pydoc import classname\nfrom Bio import SeqIO\nimport time\nimport iMVP_utils\nfrom iMVP_utils import interactive_functions\n# import interactive_functions\nimport base64\nimport PIL.Image as Image\nimport pandas as pd\nimport numpy as np\nimport dash\nfrom dash import dcc\nfrom dash import html\nfrom dash.dependencies import Input, Output,State\nfrom dash import callback_context\nfrom flask import Flask\nimport plotly.express as px\nimport plotly.graph_objects as go\n\ndef launch_backend(output_path=\"./output/\"):\n \"\"\"The function to launch the backend for interactive\n\n Parameters\n ---------\n output_path: str\n The output directory of the files.\n \n Returns\n ---------\n A Dash App object.\n \"\"\"\n iMVP_finished = False\n input_validated = False\n first_time = True\n\n assets_path = os.path.dirname(iMVP_utils.__file__) + \"/assets/\"\n \n server= Flask(__name__)\n app = dash.Dash(name=\"app1\", server=server, assets_folder=assets_path)\n\n \"\"\"Run this app with 'python app.py -p port_number and visit http://127.0.0.1:prot_number/ in your web browser.\n (Press CTRL+C to quit)\n\n \"\"\"\n\n if os.path.exists (output_path) == False:\n os.mkdir(output_path)\n\n def run_iMVP(content, input_parameters):\n \"\"\"Clustering upload data in fasta format with UMAP and HDBSCAN. \n\n Parameters\n ---------\n content: string\n A comma separated string, including type and content of upload file. \n input_parameters: dict\n A list of reserved parameters for HDBSCAN.\n ---------\n\n Returns\n ---------\n A Div component: chilren\n A html div of 'processing' information.\n Html stlye: dict\n A style of 'submit-data' button. \n HDBSCAN_dict: dict\n The results of HDBSCAN.\n \"\"\"\n nonlocal output_path\n time_start = time.time()\n _, content_string = content.split(',')\n \n decoded = base64.b64decode(content_string)\n style_submit_button = {'width': '40%'}\n \n df = pd.read_csv(\n io.StringIO(decoded.decode('utf-8').replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\").replace(\">\", \"\")),sep = \"\\n\", header=None)\n fa_data = pd.concat([df[::2].reset_index(drop=True),df[1::2].reset_index(drop=True)],axis=1)\n fa_data.columns = ['sites','seq']\n # run HDBSACN\n df_HDBSCAN = interactive_functions.run_cluster(fa_data, output_path, input_parameters)\n \n png = interactive_functions.draw_logo(\"{path}/init.fa\".format(path=output_path), input_parameters)\n\n image = Image.open(io.BytesIO(png))\n img_file = '{path}/weblogo.png'.format(path=output_path)\n image.save(img_file) \n\n HDBSCAN_dict = df_HDBSCAN.to_dict()\n \n time_end = time.time()\n \n \n # used_time = round((time_end - time_start)/60,2)\n used_time = time_end - time_start\n if used_time >= 3600:\n used_time = time.strftime(\"%H hr %M min %S sec\", time.gmtime(used_time)) \n elif used_time >= 60:\n used_time = time.strftime(\"%M min %S sec\", time.gmtime(used_time)) \n else:\n used_time = time.strftime(\"%S sec\", time.gmtime(used_time)) \n \n # except Exception as e :\n # return html.Div([\n # 'There was an error processing this file.'\n # ]), {'display':'none'}\n\n df_groupby = df_HDBSCAN.groupby(\"Cluster\")[[\"Cluster\"]].count()\n df_groupby.columns = [\"Count\"]\n df_groupby[\"Cluster ID\"] = df_groupby.index\n df_groupby = df_groupby[[\"Cluster ID\", \"Count\"]]\n print(df_groupby)\n\n # html.Div([\n # dash.dash_table.DataTable(df_groupby.to_dict('records'), [{\"name\": i, \"id\": i} for i in df_groupby.columns])\n # ], style={\"width\": \"400px\", \"margin-left\":\"50px\"}\n # ),\n\n return html.Div([html.H3(\"{} inputs were analyzed. Finished in {}!\".format(df_HDBSCAN.shape[0], used_time)), html.H3('Done!'),]), \\\n style_submit_button , HDBSCAN_dict\n\n def check_fasta_input(content):\n basespace = {i:1 for i in \"ATCGUNRDEQHILKMFPSWYV\"}\n _, content_string = content.split(',')\n decoded = base64.b64decode(content_string)\n N = 0\n is_fasta = True\n try:\n for line in decoded.decode('utf-8').replace(\"\\r\\n\", \"\\n\").replace(\"\\r\", \"\\n\").split(\"\\n\"):\n try:\n # print(line)\n if not line:\n continue\n elif N % 2 == 0:\n if line.startswith(\">\") == False:\n is_fasta = False\n break\n elif N % 2 == 1:\n for b in line:\n if b.upper() not in basespace:\n is_fasta = False\n break\n N += 1\n except Exception as e:\n is_fasta = False\n break\n except Exception as e:\n is_fasta = False\n return is_fasta\n\n @app.callback(\n Output('upload_data','children'),\n Input('upload_data','filename'),\n State('upload_data', 'contents')\n )\n\n def upload_info(filenames, contents):\n nonlocal input_validated\n input_validated = False\n if filenames is None:\n return html.Div([\n 'Drag and Drop or ',html.A('Click to upload your FASTA file here')\n ], style={\"line-height\": \"300px\", \"width\": \"600px\"}) # style={\"padding\":\"50px\"}\n else:\n for file, c in zip(filenames, contents):\n fasta_status = check_fasta_input(c)\n if fasta_status == True:\n input_validated = True\n return html.Div([html.B('{filename}'.format(filename = file),style={'color':'#ff4777'}),' has been uploaded'], style={\"line-height\": \"300px\", \"width\": \"600px\"})\n else:\n return html.Div([html.B('Warining: {filename} is not a validated FASTA file!'.format(filename = file),style={'color':'#ff4777'}),], style={\"line-height\": \"300px\", \"width\": \"600px\"})\n @app.callback(\n Output('hdbscan-parameter-list','data'),\n Output('processing_1', 'children'),\n Output('processing_3','children'),\n Output('upload_data', 'style'),\n Output('para-list-div', 'style'),\n Output('upload-div', 'style'),\n Input('submit-button-state', 'n_clicks'),\n [\n State('upload_data', 'contents'), \n State('exp_len', 'value'), \n State('n_neighbors', 'value'), \n State('min_dist', 'value'), \n State('random_state', 'value'), \n State('umap_jobs', 'value'), \n State('umap_init', 'value'), \n State('densmap', 'value'), \n State('min_cluster_size', 'value'),\n State('min_samples', 'value'),\n State('cluster_selection_method', 'value'),\n State('cluster_selection_epsilon', 'value'),\n State('hdbscan_jobs', 'value'),\n State('softclustering', 'value'),\n State('weblogo_unit', 'value'),\n State('weblogo_first_index', 'value'),\n State('weblogo_base_type', 'value'),\n ],\n prevent_initial_call=True) \n\n def infomation_hide_div(n_clicks,list_of_contents, exp_len, n_neighbors, min_dist, random_state, umap_jobs, umap_init, densmap ,min_cluster_size, min_samples, cluster_selection_method, cluster_selection_epsilon, hdbscan_jobs, softclustering, weblogo_unit, weblogo_first_index, weblogo_base_type):\n \"\"\"\n Parameters\n ---------\n n_clicks: int\n The number of clicks to trigger the clustering.\n list_of_contents: list\n Contents of upload data.\n exp_len: int\n The expected lengths for the sequences.\n n_neighbors: int\n n_neighbors for UMAP.\n min_dist: int\n min_dist for UMAP.\n random_state: int\n random_state for UMAP.\n umap_jobs: int\n n_jobs for UMAP.\n umap_init: str\n init for UMAP.\n densmap: boolean\n densmap for UMAP.\n min_cluster_size: int\n The parameter of HBDSACN from user.\n min_samples: int\n The parameter of HBDSACN from user.\n cluster_selection_method: string\n The parameter of HBDSACN from user.\n core_dist_n_jobs: int\n The parameter of HBDSACN from user.\n softclustering: bool\n The parameter of HBDSACN from user.\n weblog_unit: str\n The parameter for Weblogo.\n weblog_first_index: str\n The parameter for Weblogo.\n ---------\n\n Return\n ---------\n hdbscan-parameter-list: dict\n The parameters of HDBSCAN from user.\n processing_1: div object\n The information about data processing.\n processing_3: div object\n The information about data processing.\n upload_data: dict\n A Div style of 'upload_data' to hide the div object.\n para-list-div: dict\n A Div style of 'para-list-div' to hide the div.\n upload-div: dict\n A Div style of 'upload-div' to hide the div.\n \"\"\"\n nonlocal input_validated\n\n dict_parameters = {\n \"exp_len\": exp_len,\n \"n_neighbors\": n_neighbors,\n \"min_dist\": min_dist,\n \"random_state\": random_state,\n \"umap_jobs\": umap_jobs,\n \"umap_init\": umap_init,\n \"densmap\": densmap,\n \"min_cluster_size\": min_cluster_size,\n \"min_samples\": min_samples,\n \"cluster_selection_method\": cluster_selection_method,\n \"cluster_selection_epsilon\": cluster_selection_epsilon,\n \"hdbscan_jobs\": hdbscan_jobs,\n \"softclustering\": softclustering,\n \"weblogo_unit\": weblogo_unit,\n \"weblogo_first_index\": weblogo_first_index,\n \"weblogo_base_type\": weblogo_base_type,\n }\n \n if input_validated == True:\n hide_div_style_1 = {'display': 'none'}\n hide_div_style_2 = {'display': 'none'}\n hide_div_style_3 = {'display': 'none'}\n if list_of_contents is not None:\n for c in list_of_contents:\n return dict_parameters, [html.H3(time.asctime( time.localtime(time.time())))],html.H3('Processing ......',id='process'),hide_div_style_1,hide_div_style_2,hide_div_style_3\n else:\n return dash.no_update\n\n @app.callback(\n Output('processing_2', 'children'),\n Output('submit-data', 'style'),\n Output('cluster-data', 'data'),\n Output('processing_3','style'),\n Output('horizontal_line','style'),\n Input('hdbscan-parameter-list','data'),\n [State('upload_data', 'contents')],\n prevent_initial_call=True)\n\n def upload_file(parameter_list, list_of_contents):\n\n \"\"\"\n Parameters\n ---------\n parameter_list: list\n The parameters of HDBSCAN from user.\n list_of_contents: list\n A content of upload file.\n\n ---------\n\n Returns\n ---------\n processing_2: div object\n The information about data processing.\n style: dict\n A style to hide 'submit-data' div object.\n parameters_dict: dict\n The results of clustering with HDBSCAN. \n hide_info_style: dict\n A style to hide 'processing_2' div object.\n display_hr: dict\n A style to display horizontal line.\n \"\"\" \n nonlocal iMVP_finished\n\n hide_info_style = {'display':'none'}\n display_hr = {'display':'inline-block'}\n\n if list_of_contents is not None:\n for c in list_of_contents:\n iMVP_out = run_iMVP(c, parameter_list)\n if len(iMVP_out) == 2:\n processing_2, style = iMVP_out\n parameters_dict = None\n else:\n processing_2, style, parameters_dict = iMVP_out\n iMVP_finished = True\n return processing_2, style, parameters_dict, hide_info_style, display_hr\n\n\n @app.callback(\n Output('cluster_figure', 'figure'),\n Output('my-checklist','options'),\n Output('type', 'data'),\n Output('hidden_data','style'),\n Output('submit-button','style'),\n [Input('submit-data','n_clicks'),\n State('cluster-data', 'data'),\n Input(\"scatter-slider\", \"value\"), \n ],prevent_initial_call=True\n )\n\n def cluster_figure(n_clicks, cluster_data, markersize):\n \"\"\"\n Parameters\n ---------\n n_clicks: int\n The number of clicks to trigger clustering.\n cluster_data: dict\n The results of clustering with HDBSCAN.\n markersize:\n The size of markers\n ---------\n\n Returns\n ---------\n cluster_figure: graph object in plotly\n A graph to display the clusters of HBDSCAN.\n my-checklist: list\n The types of cluster that user choosed.\n type: list\n Types of clusters.\n hidden_data: dict\n A style to hide the div object.\n submit-button: button object\n A style to show the div of button object. \n\n \"\"\"\n dff = pd.DataFrame(cluster_data)\n df = dff.sort_values(by=\"Cluster\", ascending=True)\n type = range(1,max(df['Cluster']) + 1)\n df['Cluster'] = df['Cluster'].astype(str)\n available_type = list(map(str, type)) \n df['customdata'] = df.index.values.tolist()\n options = [{'label': '{:>3}'.format(i), 'value':i } for i in available_type]\n fig = px.scatter(df, x=\"X\", y=\"Y\", color=\"Cluster\", custom_data=[\"customdata\"])\n fig.update_traces(marker_size=markersize) # , selector=dict(mode='markers')\n fig.update_layout(dragmode='lasso', hovermode=False, width=600, height=600)\n \n return fig, options,available_type,{'display':'inline-block', 'min-width': \"1200px\"},{'display':'none'} # \n\n @app.callback(\n Output(\"my-checklist\", \"value\"),\n Output(\"all-or-none\", \"value\"),\n Output(\"select-data\",\"data\"),\n [Input(\"type\", 'data'),\n Input(\"all-or-none\", \"value\"),\n Input(\"my-checklist\", 'value')],\n )\n\n def select_all_none(option,all_selected, my_selected):\n \"\"\"\n Parameters\n ---------\n option: list\n Types of all clusters.\n all_selected: list\n When user choose all clusters. \n my_selected: list \n Types of clusters that user choosed.\n\n ---------\n\n Returns\n ---------\n my-checklist: list\n Types of clusters that user choosed, which show as checklist object.\n all-or-none: list\n Types of all clusters, which show as checklist object.\n select-data: list\n Types of clusters that user choosed, which store as dcc object.\n\n \"\"\"\n ctx = callback_context\n input_id = ctx.triggered[0][\"prop_id\"].split(\".\")[0]\n \n if input_id == \"my-checklist\":\n all_selected = [\"Select All\"] if set(my_selected) == set(option) else []\n else:\n my_selected = option if all_selected else []\n if all_selected != []:\n select_data = option\n else:\n select_data = my_selected\n\n return my_selected, all_selected, select_data\n\n @app.callback(\n Output('weblogo','src'),\n Input('cluster_figure', 'selectedData'),\n Input('cluster-data', 'data'),\n Input('select-data','data'),\n Input('hdbscan-parameter-list','data'),\n prevent_initial_call=True\n )\n\n def draw_weblogo(selected_data,cluster_data, clusters_select, parameter_list):\n \"\"\"\n Parameters\n ---------\n selected_data: dict\n Data selected with lasso or checklist\n cluster_data: dict\n The results of clustering with HDBSCAN. \n clusters_select: list \n Types of clusters selected from users\n ---------\n\n Return\n ---------\n weblogo: png\n Weblogo picture in png format.\n ---------\n \"\"\"\n nonlocal output_path, iMVP_finished, first_time\n if iMVP_finished == True and first_time == True:\n # and os.path.isfile(\"{path}/selected_data.fa\".format(path=output_path)) == False\n img_file = '{path}/weblogo.png'.format(path=output_path)\n encode_img = base64.b64encode(open(img_file,'rb').read())\n iMVP_finished = True\n first_time = False\n return 'data:image/png;base64,{}'.format(encode_img.decode())\n elif clusters_select == [] and selected_data is None:\n return dash.no_update\n else:\n df = pd.DataFrame(cluster_data)\n df['Cluster'] = df['Cluster'].astype(str)\n fa_index = []\n if selected_data is None:\n custom = []\n selected_data = {}\n for i in df[df['Cluster'].isin(clusters_select) ].index.values.tolist():\n custom.append({'customdata':[i]})\n selected_data['points'] = custom\n \n for points in selected_data['points']: \n fa_index.extend(points.get('customdata'))\n \n fasta_name = \"{path}/selected_data.fa\".format(path=output_path)\n\n base_type = parameter_list[\"weblogo_base_type\"]\n\n with open(fasta_name, \"w\") as fasta_out:\n for idx, row in df.loc[fa_index].iterrows():\n if base_type == \"DNA\":\n seq_out = str(row[\"seq\"]).upper().replace(\"U\", \"T\")\n elif base_type == \"RNA\":\n seq_out = str(row[\"seq\"]).upper().replace(\"T\", \"U\")\n else:\n seq_out = str(row[\"seq\"])\n fasta_out.write(\">{}\\n{}\\n\".format(idx, seq_out))\n\n png = interactive_functions.draw_logo(fasta_name, parameter_list)\n image = Image.open(io.BytesIO(png))\n img_file = '{path}/weblogo.png'.format(path=output_path)\n image.save(img_file) \n encode_img = base64.b64encode(open(img_file,'rb').read())\n \n return 'data:image/png;base64,{}'.format(encode_img.decode())\n\n @app.callback(\n Output(\"download-text\", \"data\"),\n Input(\"btn-download-txt\", \"n_clicks\"),\n prevent_initial_call=True)\n def download_fasta(n_clicks):\n \"\"\"\n Parameters\n ---------\n n_clicks: int\n The number of clicks to trigger download file in fasta format.\n ---------\n\n Return\n ---------\n download-text: string \n A fasta format file.\n ---------\n \"\"\"\n nonlocal output_path\n with open('{path}/selected_data.fa'.format(path=output_path)) as f:\n contents = f.read()\n return dict(content=contents, filename=\"seleted_data.fa\")\n\n @app.callback(\n Output(\"download-csv\", \"data\"),\n Input(\"btn-download-csv\", \"n_clicks\"),\n prevent_initial_call=True)\n def download_csv(n_clicks):\n \"\"\"\n Parameters\n ---------\n n_clicks: int\n The number of clicks to trigger download CSV file.\n ---------\n\n Return\n ---------\n download-text: string \n A fasta format file.\n ---------\n \"\"\"\n nonlocal output_path\n with open('{path}/all_clusters.csv'.format(path=output_path)) as f:\n contents = f.read()\n return dict(content=contents, filename=\"all_clusters.csv\")\n\n @app.callback(\n Output(\"download-png\", \"data\"), \n Input(\"btn-download-png\", \"n_clicks\"),\n prevent_initial_call=True\n )\n def download_weblogo(n_clicks):\n nonlocal output_path\n \"\"\"\n Parameters\n ---------\n n_clicks: int \n The number of clicks to trigger download weblogo picture.\n ---------\n\n Return\n ---------\n download-png: png\n A file in png format of weblogo.\n ---------\n \"\"\"\n return dash.dcc.send_file(\"{path}/weblogo.png\".format(path=output_path))\n\n app.layout = html.Div([\n\n\n\n html.Div([\n html.Div([\n html.H1(\n \"iMVP Motif Viewer\",\n style = {'textAlign':'center'}), # , 'margin-left':'20%'\n\n html.H3(\n \"Version: 0.2.3; Contributed by Jing Yao, Jianheng Liu @ Zhang Lab (SYSU).\",\n style = {'textAlign':'center'}), # , 'margin-left': '10%'\n html.H3(\"Documents: https://readthedocs.org/iMVP/\", style = {'textAlign':'center'}),\n\n html.Div([\n # html.Br(),\n # html.Br(),\n html.Div(\"Tips #1: To go back to the parameters page, please refresh the page.\"),\n html.Div(\"Tips #2: Use Ctrl+C in command lines to terminate the backend.\"),\n ], style={\"horizonal-align\":\"center\", 'text-align':'center'}),\n ], style={\"width\":\"1000px\"}),\n\n html.Div([\n html.Div([\n html.Div([\n html.Div([\n html.Div([\n html.H4('I. Upload data'),\n dcc.Upload(\n id = 'upload_data',\n multiple=True,\n style={\"line-height\": \"300px\"} # , \"min-width\": \"100%\n ), \n\n ], className = \"upload\",id = 'upload-div', style={'display':'inline-block', \"width\": \"600px\"}, # \"line-height: 20%;\"\n ),\n\n html.Div([\n html.Br(),\n html.Br(),\n html.Div(\"If you have confirmed your input and parameters, click the button to run.\"),\n html.Br(),\n html.Button(id='submit-button-state', n_clicks=0, children='Submit'),\n ],\n className=\"input\", style={\"horizonal-align\":\"center\", 'text-align':'center'},\n ),\n\n ], className=\"two columns\", style={'display':'inline-block', \"width\": \"600px\", \"vertical-align\":\"top\", \"margin-right\":\"5%\", \"margin-left\":\"2.5%\"}\n ),\n\n # html.Div([\n\n # ], className=\"three columns\", style={'display':'inline-block'}\n # ),\n\n html.Div([\n html.Div([\n html.H4('II. Quality control'),\n html.Div([\n \"1. Expected lengths of the sequences =\",\n dcc.Input(id='exp_len', type='number', value='21', min='0'),\n ]),\n ], style={'display':'inline-block', \"vertical-align\":\"top\"}),\n\n html.H4('III. UMAP parameters'),\n html.Div([\n \"1. n_neighbors =\",\n dcc.Input(id='n_neighbors', type='number', value='20', min='0'),\n ]),\n html.Div([\n \"2. min_dist =\", \n dcc.Input(id='min_dist', type='number', value='0.01', step='any', min='0', max='1'), \n ]),\n html.Div([\n \"3. random_state =\", \n dcc.Input(id='random_state', type='number', value='42', min='-2147483648', max='2147483647'), \n ]),\n html.Div([\n \"4. jobs =\", \n dcc.Input(id='umap_jobs', type='number', value='6'), \n ]),\n html.Div([\n html.Div([\"5. init =\"], className=\"two columns\", style={\"display\": \"inline-block\"}), # style={\"display\": \"inline-block\"}\n html.Div([dcc.RadioItems(['random', 'spectral'], 'random', id='umap_init')], className=\"two columns\", style={\"display\": \"inline-block\"}), \n ], className=\"row\"# style={\"width\":\"30%\"}\n ),\n html.Div([\n html.Div([\"6. DensMAP =\"], className=\"two columns\", style={\"display\": \"inline-block\"}), # style={\"display\": \"inline-block\"}\n html.Div([dcc.RadioItems(['True', 'False'], 'False', id='densmap')], className=\"two columns\", style={\"display\": \"inline-block\"}), \n ], className=\"row\"# style={\"width\":\"30%\"}\n ),\n\n html.H4('IV. HBDSCAN parameters'),\n html.Div([\n \"1. min_cluster_size =\",\n dcc.Input(id='min_cluster_size', type='number', value='100'),\n ]),\n html.Div([\n \"2. min_samples =\", \n dcc.Input(id='min_samples', type='number', value='100'),\n ]),\n html.Div([\n \"3. cluster_selection_epsilon =\", \n dcc.Input(id='cluster_selection_epsilon', type='number', step=\"any\", value='0.0'),\n ]),\n\n html.Div([\n html.Div([\"4. cluster_selection_method =\"], className=\"two columns\", style={\"display\": \"inline-block\"}), # style={\"display\": \"inline-block\"}\n html.Div([dcc.RadioItems(['eom', 'leaf'], 'eom', id='cluster_selection_method')], className=\"two columns\", style={\"display\": \"inline-block\"}), \n ], className=\"row\"# style={\"width\":\"30%\"}\n ),\n\n html.Div([\n html.Div([\"5. soft clustering =\"], className=\"two columns\", style={\"display\": \"inline-block\"}), # style={\"display\": \"inline-block\"}\n html.Div([dcc.RadioItems(['True', 'False'], 'True', id='softclustering')], className=\"two columns\", style={\"display\": \"inline-block\"}), \n ], className=\"row\"# style={\"width\":\"30%\"}\n ),\n html.Div([\n \"6. jobs =\", \n dcc.Input(id='hdbscan_jobs', type='number', value='6'),\n ]),\n\n html.H4('V. Weblogo'),\n html.Div([\n html.Div([\"1. Unit =\"], className=\"two columns\", style={\"display\": \"inline-block\"}), # style={\"display\": \"inline-block\"}\n html.Div([dcc.RadioItems(['probability', 'bits'], 'probability', id='weblogo_unit')], className=\"two columns\", style={\"display\": \"inline-block\"}), \n ], className=\"row\"# style={\"width\":\"30%\"}\n ),\n html.Div([\n html.Div([\"2. Base type (LOGO and FASTA output) =\"], className=\"two columns\", style={\"display\": \"inline-block\"}), # style={\"display\": \"inline-block\"}\n html.Div([dcc.RadioItems(['As input', 'DNA', \"RNA\"], 'As input', id='weblogo_base_type')], className=\"two columns\", style={\"display\": \"block\"}), # inline- \n ], className=\"row\"# style={\"width\":\"30%\"}\n ),\n\n html.Div([\"3. First index =\",\n dcc.Input(id='weblogo_first_index', type='number', value='-10'),\n ]), \n \n ], className=\"two columns\", style={'display':'inline-block'} \n ),\n\n ], style={'display':'inline-block', \"margin-left\":\"0%\", \"width\":\"100%\"}, # , \"width\":\"40%\"\n ),\n ], className=\"row\", style={'display':'inline-block', \"width\":\"100%\"}\n ),\n\n \n ], id=\"para-list-div\", style={\"width\":\"auto\"})\n\n ], className=\"section1\",id = 'section1', style={\"width\":\"1600px\"}),\n\n html.Hr(id = \"horizontal_line\",style={'display':'none'}),\n\n html.Div([\n html.Div([\n html.Div([\n html.Div(\n dcc.Graph(id = 'cluster_figure'),\n style={'display': 'inline-block'} # 'width': '40%',\n ),\n html.Div(\n html.H4(\"Marker size:\"),\n style={\"margin-left\": \"10%\"}\n ),\n html.Div(\n dcc.Slider(id='scatter-slider', value=10, min=1, max=30,),\n style={\"margin-left\": \"10%\", \"margin-right\": \"10%\"}\n ), \n\n ], className=\"two columns\", style={\"min-width\":\"600px\", \"display\": \"inline-block\", \"max-width\": \"40%\", \"margin-right\": \"5%\"} # , \"margin-right\": \"%\"\n ),\n\n html.Div([\n html.Div([\n html.Div(\n html.Img(id = \"weblogo\", style={'max-width':\"600px\",'display': 'inline-block'}), \n style={'display': 'inline-block'} # , 'verticalAlign':'top'\n ), \n # style={'width':\"200px\"}), # 'width': '50%','display': 'inline-block', 'position':'relative','bottom':'150px'\n\n html.Div([\n html.Div([\n html.Div(html.Button(\"Download FASTA\", id = \"btn-download-txt\"), # , style = {'width': '99%'}\n ),\n dcc.Download(id = \"download-text\")\n ],\n style={'display':'inline-block', \"margin-left\": \"10%\", \"margin-right\":\"5%\"}, \n className='three columns'), \n\n html.Div([\n html.Div(html.Button(\"Download CSV\", id=\"btn-download-csv\"), # , style={'width': '99%'}\n ),\n dcc.Download(id = \"download-csv\"),\n ],\n style={'display':'inline-block', \"margin-left\":\"5%\", \"margin-right\":\"5%\"}, \n className='three columns'),\n\n html.Div([\n html.Div(html.Button(\"Download LOGO\", id=\"btn-download-png\"), # , style={'width': '99%'}\n ),\n dcc.Download(id = \"download-png\"),\n ],\n style={'display':'inline-block', \"margin-left\":\"5%\", \"margin-right\": \"10%\"}, \n className='three columns'),\n\n ], className=\"row\", style={\"horizonal-align\": \"middle\", \"margin-left\": \"5%\", \"margin-top\": \"5%\", \"margin-right\": \"5%\", \"margin-bottom\": \"5%\"} # 'display': 'inline-block', \n ),\n\n html.Br(),\n html.Br(),\n\n html.Div([\n html.Div(\n html.H4(\"Select clusters:\", style={'display': 'inline-block'}),\n ),\n \n html.Div([\n dcc.Checklist(\n id=\"all-or-none\",\n options=[{\"label\": \"Select All\", \"value\": \"Select All\"}],\n value=[],\n # labelStyle={\"display\": \"inline-block\", \"position\": \"relative\", \"vertical-align\":\"middle\"},\n ),\n ], # style={'display': 'inline-block'}\n ),\n\n html.Div([\n dcc.Checklist(\n id=\"my-checklist\",\n #options=[{\"label\": x, \"value\": x} for x in option],\n value=[\"1\"],\n # labelStyle={\"display\": \"inline-block\", \"position\": \"relative\", \"vertical-align\":\"middle\"}, # \"text-\": \"relative\"\n ),\n ], # style={'display': 'inline-block'}\n ),\n ], style={'display': 'inline-block'}),\n\n ], style={'display': 'inline-block'}\n ),\n\n ], className=\"two columns\", style={\"margin-top\":\"5%\", \"max-width\": \"40%\", \"display\": \"inline-block\",'vertical-align': 'top'} \n ),\n ], className=\"row\", style={\"display\": \"inline-block\", \"min-width\":\"1000px\"} \n ),\n html.Br(),\n html.Br(),\n html.Br(),\n\n ], id = \"hidden_data\", style={'display':'none', 'min-width': '1000px'},\n ),\n\n \n\n # html.Div(\n # dcc.Markdown('''\n # *Usage:*\n # The software encodes the data using one-hot encoding and the dimensionality reduction using **UMAP**. Then, the matrix is clustered using **HDBSCAN** to get all the clusters from the fasta file.Firstly, upload the fasta data of the same length. Then, input the parameters for the clustering with HDBSCAN. After submitting the data, it will take a few minutes for the background to process the data.Finally, you can select clusters by tick checklist, or use a lasso to circle the parts of interest on the cluster plot. That part of data would display by weblogo of base enrichment.\n # ''')\n # )\n\n html.Div(id = \"processing_1\"),\n html.Div(id = \"processing_2\"),\n html.Div(id = \"processing_3\"),\n html.Div(\n html.Button(\n id = 'submit-data',\n n_clicks=0,\n children='Draw the Figures',\n style = {'display':'none'}),\n id = 'submit-button'),\n\n dcc.Store(id = \"cluster-data\"),\n dcc.Store(id = \"hdbscan-parameter-list\"),\n dcc.Store(id = \"select-data\"),\n dcc.Store(id = \"type\")\n \n ], style={\"margin-left\":\"0%\", \"width\":\"1000px\"})\n\n return app\n\nif __name__ == \"__main__\":\n pass"
]
| [
[
"pandas.DataFrame"
]
]
|
JonathanLehner/korali | [
"90f97d8e2fed2311f988f39cfe014f23ba7dd6cf",
"90f97d8e2fed2311f988f39cfe014f23ba7dd6cf"
]
| [
"tests/statistical/optimizers/correctness/helpers/helpers.py",
"examples/hierarchical.bayesian/extended/_setup/model/model.py"
]
| [
"#!/usr/bin/env python3\nimport numpy as np\n\n\ndef checkMin(k, expectedMinimum, tol):\n minimum = k[\"Solver\"][\"Best Ever Value\"]\n assert np.isclose(expectedMinimum, minimum, atol = tol), \"Minimum {0} \"\\\n \"deviates from true min {1} by more than {2}\".format(minimum, expectedMinimum, tol)\n\ndef checkInfeasible(k, expectedMinimum):\n minimum = k[\"Solver\"][\"Infeasible Sample Count\"]\n assert np.less(expectedMinimum, minimum, ), \"Minimum {0} \"\\\n \"is not less than {1}\".format(minimum, expectedMinimum)\n \ndef checkEvals(k, expected):\n val = k[\"Solver\"][\"Model Evaluation Count\"]\n assert np.equal(expected, val, ), \"Value {0} \"\\\n \"is not equal to {1}\".format(expected, val)\n",
"#!/usr/bin/env python3\nimport sys\nimport os\nimport numpy as np\n\n\ndef logistic(X, s):\n th1 = s[\"Parameters\"][0]\n th2 = s[\"Parameters\"][1]\n th3 = s[\"Parameters\"][2]\n sig = s[\"Parameters\"][3]\n\n result = []\n sdev = []\n\n for x in X:\n f = np.exp(th3 * x)\n y = (th1 * th2 * f) / (th1 + th2 * (f - 1))\n result.append(y)\n sdev.append(sig)\n\n s[\"Reference Evaluations\"] = result\n s[\"Standard Deviation\"] = sdev\n\n\ndef logistic_reference(s):\n th = np.zeros(4)\n for i in range(4):\n th[i] = s[\"Parameters\"][i]\n\n X = np.linspace(0.0, 10.0, num=21)\n Y = np.zeros(X.size)\n for i in range(X.size):\n f = np.exp(th[2] * X[i])\n if (th[0] * th[1] * f == 0):\n Y[i] = 0.0\n else:\n Y[i] = (th[0] * th[1] * f) / (th[0] + th[1] * (f - 1))\n\n Y = Y + np.random.normal(0, th[3], X.size)\n k = s[\"Sample Id\"]\n\n dataFolder = \"_setup/data/\"\n if not os.path.exists(dataFolder):\n os.makedirs(dataFolder)\n dataFile = dataFolder + \"/data_set_\" + str(k).zfill(3) + \".dat\"\n np.savetxt(dataFile, np.transpose([X, Y]))\n\n\ndef getReferenceData(path, i):\n fileName = path + \"/data_set_\" + str(i).zfill(3) + \".dat\"\n y = readColumnFromFile(fileName, 1)\n return y\n\n\ndef getReferencePoints(path, i):\n fileName = path + \"/data_set_\" + str(i).zfill(3) + \".dat\"\n y = readColumnFromFile(fileName, 0)\n return y\n\n\ndef readColumnFromFile(FileName, Column):\n try:\n f = open(FileName, \"r\")\n lines = f.readlines()\n y = []\n for l in lines:\n y.append(float(l.split()[Column]))\n f.close()\n except IOError as e:\n print(\"I/O error(\" + str(e.errno) + \"): \" + e.strerror)\n print(\"The file \" + FileName + \" is missing\")\n sys.exit(1)\n except ValueError:\n print(\"Could not convert data to a float. Check the results in \" + FileName)\n sys.exit(1)\n except:\n print(\"Unexpected error: \" + sys.exc_info()[0])\n raise\n\n return y\n"
]
| [
[
"numpy.less",
"numpy.equal",
"numpy.isclose"
],
[
"numpy.linspace",
"numpy.random.normal",
"numpy.transpose",
"numpy.exp",
"numpy.zeros"
]
]
|
Aryan-Rajoria/NASWOT-attacks | [
"5045de462afcd38314d760a41e7da7dfaea24092"
]
| [
"nasbench/lib/graph_util.py"
]
| [
"# Copyright 2019 The Google Research 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\n\"\"\"Utility functions used by generate_graph.py.\"\"\"\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport hashlib\nimport itertools\n\nimport numpy as np\n\n\ndef gen_is_edge_fn(bits):\n \"\"\"Generate a boolean function for the edge connectivity.\n\n Given a bitstring FEDCBA and a 4x4 matrix, the generated matrix is\n [[0, A, B, D],\n [0, 0, C, E],\n [0, 0, 0, F],\n [0, 0, 0, 0]]\n\n Note that this function is agnostic to the actual matrix dimension due to\n order in which elements are filled out (column-major, starting from least\n significant bit). For example, the same FEDCBA bitstring (0-padded) on a 5x5\n matrix is\n [[0, A, B, D, 0],\n [0, 0, C, E, 0],\n [0, 0, 0, F, 0],\n [0, 0, 0, 0, 0],\n [0, 0, 0, 0, 0]]\n\n Args:\n bits: integer which will be interpreted as a bit mask.\n\n Returns:\n vectorized function that returns True when an edge is present.\n \"\"\"\n\n def is_edge(x, y):\n \"\"\"Is there an edge from x to y (0-indexed)?\"\"\"\n if x >= y:\n return 0\n # Map x, y to index into bit string\n index = x + (y * (y - 1) // 2)\n return (bits >> index) % 2 == 1\n\n return np.vectorize(is_edge)\n\n\ndef is_full_dag(matrix):\n \"\"\"Full DAG == all vertices on a path from vert 0 to (V-1).\n\n i.e. no disconnected or \"hanging\" vertices.\n\n It is sufficient to check for:\n 1) no rows of 0 except for row V-1 (only output vertex has no out-edges)\n 2) no cols of 0 except for col 0 (only input vertex has no in-edges)\n\n Args:\n matrix: V x V upper-triangular adjacency matrix\n\n Returns:\n True if the there are no dangling vertices.\n \"\"\"\n shape = np.shape(matrix)\n\n rows = matrix[:shape[0] - 1, :] == 0\n rows = np.all(rows, axis=1) # Any row with all 0 will be True\n rows_bad = np.any(rows)\n\n cols = matrix[:, 1:] == 0\n cols = np.all(cols, axis=0) # Any col with all 0 will be True\n cols_bad = np.any(cols)\n\n return (not rows_bad) and (not cols_bad)\n\n\ndef num_edges(matrix):\n \"\"\"Computes number of edges in adjacency matrix.\"\"\"\n return np.sum(matrix)\n\n\ndef hash_module(matrix, labeling):\n \"\"\"Computes a graph-invariance MD5 hash of the matrix and label pair.\n\n Args:\n matrix: np.ndarray square upper-triangular adjacency matrix.\n labeling: list of int labels of length equal to both dimensions of\n matrix.\n\n Returns:\n MD5 hash of the matrix and labeling.\n \"\"\"\n vertices = np.shape(matrix)[0]\n in_edges = np.sum(matrix, axis=0).tolist()\n out_edges = np.sum(matrix, axis=1).tolist()\n\n assert len(in_edges) == len(out_edges) == len(labeling)\n hashes = list(zip(out_edges, in_edges, labeling))\n hashes = [hashlib.md5(str(h).encode('utf-8')).hexdigest() for h in hashes]\n # Computing this up to the diameter is probably sufficient but since the\n # operation is fast, it is okay to repeat more times.\n for _ in range(vertices):\n new_hashes = []\n for v in range(vertices):\n in_neighbors = [hashes[w] for w in range(vertices) if matrix[w, v]]\n out_neighbors = [hashes[w] for w in range(vertices) if matrix[v, w]]\n new_hashes.append(hashlib.md5(\n (''.join(sorted(in_neighbors)) + '|' +\n ''.join(sorted(out_neighbors)) + '|' +\n hashes[v]).encode('utf-8')).hexdigest())\n hashes = new_hashes\n fingerprint = hashlib.md5(str(sorted(hashes)).encode('utf-8')).hexdigest()\n\n return fingerprint\n\n\ndef permute_graph(graph, label, permutation):\n \"\"\"Permutes the graph and labels based on permutation.\n\n Args:\n graph: np.ndarray adjacency matrix.\n label: list of labels of same length as graph dimensions.\n permutation: a permutation list of ints of same length as graph dimensions.\n\n Returns:\n np.ndarray where vertex permutation[v] is vertex v from the original graph\n \"\"\"\n # vertex permutation[v] in new graph is vertex v in the old graph\n forward_perm = zip(permutation, list(range(len(permutation))))\n inverse_perm = [x[1] for x in sorted(forward_perm)]\n edge_fn = lambda x, y: graph[inverse_perm[x], inverse_perm[y]] == 1\n new_matrix = np.fromfunction(np.vectorize(edge_fn),\n (len(label), len(label)),\n dtype=np.int8)\n new_label = [label[inverse_perm[i]] for i in range(len(label))]\n return new_matrix, new_label\n\n\ndef is_isomorphic(graph1, graph2):\n \"\"\"Exhaustively checks if 2 graphs are isomorphic.\"\"\"\n matrix1, label1 = np.array(graph1[0]), graph1[1]\n matrix2, label2 = np.array(graph2[0]), graph2[1]\n assert np.shape(matrix1) == np.shape(matrix2)\n assert len(label1) == len(label2)\n\n vertices = np.shape(matrix1)[0]\n # Note: input and output in our constrained graphs always map to themselves\n # but this script does not enforce that.\n for perm in itertools.permutations(range(0, vertices)):\n pmatrix1, plabel1 = permute_graph(matrix1, label1, perm)\n if np.array_equal(pmatrix1, matrix2) and plabel1 == label2:\n return True\n\n return False\n"
]
| [
[
"numpy.array_equal",
"numpy.all",
"numpy.vectorize",
"numpy.shape",
"numpy.any",
"numpy.array",
"numpy.sum"
]
]
|
JakeTheWise/model-analysis | [
"4e1b3eed50ce8d9cc945d5a79eb547c558663695"
]
| [
"tensorflow_model_analysis/extractors/tflite_predict_extractor.py"
]
| [
"# Lint as: python3\n# Copyright 2019 Google LLC\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# https://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\"\"\"Predict extractor for TFLite models.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\n# Standard __future__ imports\nfrom __future__ import print_function\n\nimport collections\nimport copy\nfrom typing import Dict, List, Optional, Union, Sequence, Text\n\nimport apache_beam as beam\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow_model_analysis import config\nfrom tensorflow_model_analysis import constants\nfrom tensorflow_model_analysis import model_util\nfrom tensorflow_model_analysis import types\nfrom tensorflow_model_analysis.extractors import extractor\n\nTFLITE_PREDICT_EXTRACTOR_STAGE_NAME = 'ExtractTFLitePredictions'\n\n\n# TODO(b/149981535) Determine if we should merge with RunInference.\[email protected]_input_types(beam.typehints.List[types.Extracts])\[email protected]_output_types(types.Extracts)\nclass _TFLitePredictionDoFn(model_util.BatchReducibleDoFnWithModels):\n \"\"\"A DoFn that loads tflite models and predicts.\"\"\"\n\n def __init__(self, eval_config: config.EvalConfig,\n eval_shared_models: Dict[Text, types.EvalSharedModel]) -> None:\n super(_TFLitePredictionDoFn, self).__init__(\n {k: v.model_loader for k, v in eval_shared_models.items()})\n self._eval_config = eval_config\n\n def setup(self):\n super(_TFLitePredictionDoFn, self).setup()\n self._interpreters = {}\n for model_name, model_contents in self._loaded_models.items():\n self._interpreters[model_name] = tf.lite.Interpreter(\n model_content=model_contents.contents)\n\n def _batch_reducible_process(\n self, elements: List[types.Extracts]) -> Sequence[types.Extracts]:\n \"\"\"Invokes the tflite model on the provided inputs and stores the result.\"\"\"\n # This will be same size as elements, but we rebuild results dynamically\n # to avoid a deepcopy.\n result = []\n\n batched_features = collections.defaultdict(list)\n for e in elements:\n features = e[constants.FEATURES_KEY]\n for key, value in features.items():\n batched_features[key].append(value)\n\n for spec in self._eval_config.model_specs:\n model_name = spec.name if len(self._eval_config.model_specs) > 1 else ''\n if model_name not in self._loaded_models:\n raise ValueError('model for \"{}\" not found: eval_config={}'.format(\n spec.name, self._eval_config))\n\n interpreter = self._interpreters[model_name]\n\n input_details = interpreter.get_input_details()\n output_details = interpreter.get_output_details()\n\n input_features = {}\n for i in input_details:\n input_name = i['name']\n if input_name not in batched_features:\n raise ValueError(\n 'feature \"{}\" not found in input data'.format(input_name))\n input_shape = i['shape']\n feature_shape = np.shape(batched_features[input_name][0])\n if len(feature_shape) == len(input_shape):\n input_features[input_name] = batched_features[input_name]\n elif len(feature_shape) == len(input_shape) - 1:\n input_features[input_name] = [\n np.expand_dims(b, axis=0) for b in batched_features[input_name]\n ]\n else:\n raise ValueError(\n 'incompatible shape and data for feature: {}'.format(input_name))\n input_features[input_name] = tf.concat(\n input_features[input_name], axis=0)\n if np.shape(input_features[input_name]) != tuple(i['shape']):\n interpreter.resize_tensor_input(i['index'],\n np.shape(input_features[input_name]))\n interpreter.allocate_tensors()\n\n for i in input_details:\n interpreter.set_tensor(i['index'], input_features[i['name']])\n interpreter.invoke()\n\n outputs = {\n o['name']: interpreter.get_tensor(o['index']) for o in output_details\n }\n\n for v in outputs.values():\n if len(v) != len(elements):\n raise ValueError('Did not get the expected number of results.')\n\n for i in range(len(elements)):\n output = {k: v[i] for k, v in outputs.items()}\n\n if len(output) == 1:\n output = list(output.values())[0]\n\n if i >= len(result):\n result.append(copy.copy(elements[i]))\n\n if len(self._eval_config.model_specs) == 1:\n result[i][constants.PREDICTIONS_KEY] = output\n else:\n result[i].setdefault(constants.PREDICTIONS_KEY, {})[spec.name] = (\n output)\n return result\n\n\[email protected]_fn\[email protected]_input_types(types.Extracts)\[email protected]_output_types(types.Extracts)\ndef _ExtractTFLitePredictions( # pylint: disable=invalid-name\n extracts: beam.pvalue.PCollection, eval_config: config.EvalConfig,\n eval_shared_models: Dict[Text, types.EvalSharedModel],\n desired_batch_size: Optional[int]) -> beam.pvalue.PCollection:\n \"\"\"A PTransform that adds predictions and possibly other tensors to extracts.\n\n Args:\n extracts: PCollection of extracts containing model inputs keyed by\n tfma.FEATURES_KEY.\n eval_config: Eval config.\n eval_shared_models: Shared model parameters keyed by model name.\n desired_batch_size: Optional batch size.\n\n Returns:\n PCollection of Extracts updated with the predictions.\n \"\"\"\n batch_args = {}\n # TODO(b/143484017): Consider removing this option if autotuning is better\n # able to handle batch size selection.\n if desired_batch_size is not None:\n batch_args = dict(\n min_batch_size=desired_batch_size, max_batch_size=desired_batch_size)\n else:\n # TODO(b/155887292): Remove the following and allow dynamic batch sizing\n # once the bug is addressed. Also add unit tests to exercise.\n batch_args = dict(min_batch_size=1, max_batch_size=1)\n\n return (\n extracts\n | 'Batch' >> beam.BatchElements(**batch_args)\n | 'Predict' >> beam.ParDo(\n _TFLitePredictionDoFn(\n eval_config=eval_config, eval_shared_models=eval_shared_models)))\n\n\ndef TFLitePredictExtractor(\n eval_config: config.EvalConfig,\n eval_shared_model: Union[types.EvalSharedModel,\n Dict[Text, types.EvalSharedModel]],\n desired_batch_size: Optional[int] = None) -> extractor.Extractor:\n \"\"\"Creates an extractor for performing predictions on tflite models.\n\n The extractor's PTransform loads and interprets the tflite flatbuffer against\n every extract yielding a copy of the incoming extracts with an additional\n extract added for the predictions keyed by tfma.PREDICTIONS_KEY. The model\n inputs are searched for under tfma.FEATURES_KEY. If multiple\n models are used the predictions will be stored in a dict keyed by model name.\n\n Args:\n eval_config: Eval config.\n eval_shared_model: Shared model (single-model evaluation) or dict of shared\n models keyed by model name (multi-model evaluation).\n desired_batch_size: Optional batch size.\n\n Returns:\n Extractor for extracting predictions.\n \"\"\"\n eval_shared_models = model_util.verify_and_update_eval_shared_models(\n eval_shared_model)\n\n # pylint: disable=no-value-for-parameter\n return extractor.Extractor(\n stage_name=TFLITE_PREDICT_EXTRACTOR_STAGE_NAME,\n ptransform=_ExtractTFLitePredictions(\n eval_config=eval_config,\n eval_shared_models={m.model_name: m for m in eval_shared_models},\n desired_batch_size=desired_batch_size))\n"
]
| [
[
"tensorflow.concat",
"tensorflow.lite.Interpreter",
"numpy.expand_dims",
"numpy.shape"
]
]
|
mscipio/occiput-suite | [
"9b7dc59ad615d46d811eab965a86ec9efe292a7d"
]
| [
"occiput_suite/occiput/DataSources/FileSources/vNAV.py"
]
| [
"# occiput \n# Stefano Pedemonte \n# April 2014 \n# Harvard University, Martinos Center for Biomedical Imaging \n# Boston, MA, USA \n# Nov. 2015 \n\nfrom __future__ import absolute_import, print_function\n\n__all__ = ['vNAV_MPRage', 'load_vnav_mprage']\n\nimport copy\nimport os\n\nimport dicom\nimport matplotlib.pyplot as plt\nimport numpy\n\nfrom ...Core import Transform_Affine\nfrom ...Core import transformations as tr\n\nBOX_MIN = [-50.0, -50.0, -50.0]\nBOX_MAX = [50.0, 50.0, 50.0]\nTHRESHOLD_MM = 1.1\nLINE_COLOR = \"#2f8dff\"\n\n\ndef quaternion_to_rotation(q, axes='sxyz'):\n return tr.euler_from_quaternion(q, axes)\n\n\ndef angle_axis_to_quaternion(angle_rad, axis):\n f = numpy.sin(0.5 * angle_rad)\n quaternion = numpy.asarray([numpy.cos(0.5 * angle_rad), f * axis[0], f * axis[1], f * axis[2]])\n return quaternion\n\n\ndef angle_axis_to_rotation(angle_rad, axis):\n quaternion = angle_axis_to_quaternion(angle_rad, axis)\n rotation = quaternion_to_rotation(quaternion)\n return rotation\n\n\ndef affine_from_quaternion(q, axes='sxyz'):\n pass\n\n\ndef quaternion_from_matrix(affine):\n return tr.quaternion_from_matrix(affine)\n\n\ndef rad_to_deg(rad):\n return numpy.asarray(rad) * 180.0 / numpy.pi\n\n\ndef deg_to_rad(deg):\n return numpy.asarray(deg) / 180.0 * numpy.pi\n\n\nclass vNAV_MPRage():\n def __init__(self, path=None, from_dicom_comments=True, files_start_with=None, files_end_with='.dcm'):\n self._n_time_points = 0\n self._duration = []\n self._motion = []\n if path is not None:\n self.load_data_files(path, from_dicom_comments, files_start_with, files_end_with)\n\n def get_volume_dicom(self, index):\n dcm_file = self._paths[index]\n f = dicom.read_file(dcm_file)\n return f\n\n def get_motion_quaternion(self, index):\n motion_affine = self.get_motion_affine(index)\n return quaternion_from_matrix(motion_affine)\n\n def get_motion_affine(self, index):\n return self._motion[index]\n\n def get_n_time_points(self):\n return self._n_time_points\n\n def get_duration(self, index):\n return self._duration[index]\n\n def load_data_files(self, path, from_dicom_comments=True, files_start_with=None, files_end_with=None,\n exclude_files_end_with=('.dat', '.txt', '.py', '.pyc', '.nii', '.gz', '.png', '.jpg', '.jpeg',\n '.eps', '.hdr', '.l')):\n \"\"\"Load vNAV dicom files from given path and extract motion information. \n If from_dicom_comments==True, use the information stored in the dicom comments. \n If from_dicom_comments==False, use the information stored in the dicom MOCO field. \n As of April 2014, these two express motion in different coordinate systems. \n The dicom comments report absolute motion in scanner coordinates (origin is the magnetic iso-center of the scanner).\n The dicom MOCO field is currently for proprietary use (??). \"\"\"\n\n self._n_time_points = 0\n self._duration = []\n self._motion = []\n\n self._paths = []\n self._tx = []\n self._ty = []\n self._tz = []\n self._rx = []\n self._ry = []\n self._rz = []\n self._tx_comm = []\n self._ty_comm = []\n self._tz_comm = []\n self._rx_comm = []\n self._ry_comm = []\n self._rz_comm = []\n self._q0_comm = []\n self._q1_comm = []\n self._q2_comm = []\n self._q3_comm = []\n self._a0_comm = []\n self._a1_comm = []\n self._a2_comm = []\n self._a3_comm = []\n N = 0\n\n # pick the first dicom file found in path \n files = os.listdir(path)\n files.sort()\n\n # CASE 1: there exist files named with .dcm extension\n for file_name in files:\n file_valid = True\n if files_start_with is not None:\n if not file_name.startswith(files_start_with):\n file_valid = False\n if files_end_with is not None:\n if not file_name.endswith(files_end_with):\n file_valid = False\n for s in exclude_files_end_with:\n if file_name.endswith(s):\n file_valid = False\n if file_valid:\n full_path = path + os.sep + file_name\n # read moco information from files \n self._paths.append(full_path)\n try:\n f = dicom.read_file(full_path)\n except:\n print(\"Could not read file \", full_path)\n return\n t = f.get(0x00191025).value\n r = f.get(0x00191026).value\n self._tx.append(t[0])\n self._ty.append(t[1])\n self._tz.append(t[2])\n self._rx.append(r[0])\n self._ry.append(r[1])\n self._rz.append(r[2])\n motion_dicom_moco = []\n\n # extract moco information stored in the dicom comment field\n if from_dicom_comments:\n s = f.get(0x00204000).value\n if N:\n a = numpy.float32(s.split(' ')[1:5])\n t = numpy.float32(s.split(' ')[6:9])\n freq = numpy.float32(s.split(' ')[10])\n r = angle_axis_to_rotation(a[0], a[1:4])\n else:\n t = numpy.float32([0, 0, 0])\n r = numpy.float32([0, 0, 0])\n a = numpy.float32([0, 1, 0, 0]) # FIXME: is this right?\n\n q = angle_axis_to_quaternion(a.copy()[0], a.copy()[1:4])\n self._a0_comm.append(a[0])\n self._a1_comm.append(a[1])\n self._a2_comm.append(a[2])\n self._a3_comm.append(a[3])\n self._tx_comm.append(t[0])\n self._ty_comm.append(t[1])\n self._tz_comm.append(t[2])\n self._q0_comm.append(q[0])\n self._q1_comm.append(q[1])\n self._q2_comm.append(q[2])\n self._q3_comm.append(q[3])\n self._rx_comm.append(r[0])\n self._ry_comm.append(r[1])\n self._rz_comm.append(r[2])\n\n tra_mat = tr.translation_matrix(t)\n rot_mat = tr.quaternion_matrix(q)\n motion_dicom_comments = numpy.dot(tra_mat, rot_mat)\n\n # xaxis, yaxis, zaxis = [1, 0, 0], [0, 1, 0], [0, 0, 1]\n # Rx = tr.rotation_matrix(r[0], xaxis)\n # Ry = tr.rotation_matrix(r[1], yaxis)\n # Rz = tr.rotation_matrix(r[2], zaxis)\n # rot_mat = tr.concatenate_matrices(Rx, Ry, Rz)\n # rot_mat = Ry.copy()\n # motion_dicom_comments = numpy.dot(tra_mat,rot_mat) \n # motion_dicom_comments = rot_mat.copy()\n\n N += 1\n if from_dicom_comments:\n self._motion.append(motion_dicom_comments)\n else:\n self._motion.append(motion_dicom_moco)\n acquisition_number = f.get(0x00200012).value\n creation_time = f.get(0x00080013).value\n # print \"Acquisition number: \", acquisition_number\n # print \"Creation time: \",creation_time\n self._n_time_points = N\n\n def _draw_rectangle(self, axis, x, y, alpha=0.2, ec=\"gray\", fc=\"gray\"): # \"CornflowerBlue\"\n axis.add_patch(plt.Rectangle((x[0], y[0]), x[1] - x[0], y[1] - y[0], alpha=alpha, ec=ec, fc=fc, visible=True))\n # plt.draw() \n\n def _draw_rectangles(self, axis, windows, range_y):\n for ii in range(len(windows)):\n tt = windows[ii]\n yy = (range_y[0], range_y[1])\n self._draw_rectangle(axis, tt, yy)\n\n def _draw_line(self, axis, x, range_y, color=\"#ff8d8d\", linestyle=\"dashed\", label=\"\"):\n axis.vlines(x, range_y[0], range_y[1], colors=color, linestyles=linestyle, label=label, visible=True)\n\n def _draw_events(self, axis, time, range_y, events, color=\"#ff8d8d\", linestyle=\"dashed\", label=\"\"):\n for t_index in time:\n if t_index:\n if events[t_index - 1]:\n # print \"Drawing line: \", t_index, range_y, color, linestyle\n self._draw_line(axis, t_index, range_y, color, linestyle, label)\n\n def plot_motion(self, save_to_file=None, display_dicom_comments=True, display_dicom_moco=False, range_mm=(-8, 8),\n range_deg=(-7, 7), extract_events_threshold=THRESHOLD_MM, method='box', box_min=BOX_MIN,\n box_max=BOX_MAX, min_duration=1, line_color=LINE_COLOR, figsize=(10, 5)):\n t = range(len(self._tx))\n\n # make windows:\n if extract_events_threshold is not None:\n windows = []\n events = self.extract_motion_events(method, extract_events_threshold, box_min, box_max)\n t_index_start = 0\n for t_index in t:\n if t_index: # this excludes the possibility of a motion event at time 0 \n if events[t_index - 1]:\n t_index_end = t_index - 1\n if t_index_end - t_index_start > min_duration:\n windows.append((t_index_start, t_index_end)) # end window with frame before a motion event \n t_index_start = t_index + 1 # start window with frame after a motion event \n windows.append((t_index_start, t[-1]))\n\n if display_dicom_moco:\n fig1 = plt.figure(1, figsize=figsize)\n\n ax1 = fig1.add_subplot(311)\n ax1.plot(t, self._tx, line_color)\n ax1.grid(True)\n ax1.set_ylim(range_mm)\n ax1.set_ylabel('TX [mm]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_mm)\n self._draw_events(ax1, t, range_mm, events)\n\n ax1 = fig1.add_subplot(312)\n ax1.plot(t, self._ty, line_color)\n ax1.grid(True)\n ax1.set_ylim(range_mm)\n ax1.set_ylabel('TY [mm]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_mm)\n self._draw_events(ax1, t, range_mm, events)\n\n ax1 = fig1.add_subplot(313)\n ax1.plot(t, self._tz, line_color)\n ax1.grid(True)\n ax1.set_ylim(range_mm)\n ax1.set_ylabel('TZ [mm]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_mm)\n self._draw_events(ax1, t, range_mm, events)\n\n # if save_to_file is not None:\n # plt.savefig(save_to_file)\n\n fig2 = plt.figure(2, figsize=figsize)\n\n ax1 = fig2.add_subplot(311)\n ax1.plot(t, rad_to_deg(self._rx), line_color)\n ax1.grid(True)\n ax1.set_ylim(range_deg)\n ax1.set_ylabel('RX [deg]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_deg)\n self._draw_events(ax1, t, range_deg, events)\n\n ax1 = fig2.add_subplot(312)\n ax1.plot(t, rad_to_deg(self._ry), line_color)\n ax1.grid(True)\n ax1.set_ylim(range_deg)\n ax1.set_ylabel('RY [deg]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_deg)\n self._draw_events(ax1, t, range_deg, events)\n\n ax1 = fig2.add_subplot(313)\n ax1.plot(t, rad_to_deg(self._rz), line_color)\n ax1.grid(True)\n ax1.set_ylim(range_deg)\n ax1.set_ylabel('RZ [deg]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_deg)\n self._draw_events(ax1, t, range_deg, events)\n\n # if save_to_file is not None:\n # plt.savefig(save_to_file)\n else:\n fig1 = None\n fig2 = None\n\n if display_dicom_comments:\n fig3 = plt.figure(3, figsize=figsize)\n\n # mr = numpy.min([self._rx_comm,self._ry_comm,self._rz_comm])\n # Mr = numpy.max([self._rx_comm,self._ry_comm,self._rz_comm])\n # mt = numpy.min([self._tx_comm,self._ty_comm,self._tz_comm])\n # Mt = numpy.max([self._tx_comm,self._ty_comm,self._tz_comm])\n mr = range_deg[0]\n Mr = range_deg[1]\n mt = range_mm[0]\n Mt = range_mm[1]\n\n ax1 = fig3.add_subplot(311)\n ax1.set_title(\"Rotation vs. vNAV frame number\")\n ax1.plot(t, rad_to_deg(self._rx_comm), line_color)\n ax1.grid(True)\n ax1.set_ylim((mr, Mr))\n ax1.set_ylabel('RX [deg]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n # print windows\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_deg)\n self._draw_events(ax1, t, range_deg, events)\n\n ax1 = fig3.add_subplot(312)\n # ax1.set_title(\"Rotation comments Y\")\n ax1.plot(t, rad_to_deg(self._ry_comm), line_color)\n ax1.grid(True)\n ax1.set_ylim((mr, Mr))\n ax1.set_ylabel('RY [deg]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_deg)\n self._draw_events(ax1, t, range_deg, events)\n\n ax1 = fig3.add_subplot(313)\n # ax1.set_title(\"Rotation comments Z\")\n ax1.plot(t, rad_to_deg(self._rz_comm), line_color)\n ax1.grid(True)\n ax1.set_ylim((mr, Mr))\n ax1.set_ylabel('RZ [deg]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_deg)\n self._draw_events(ax1, t, range_deg, events)\n\n # if save_to_file is not None:\n # plt.savefig(save_to_file)\n\n fig4 = plt.figure(4, figsize=figsize)\n\n ax1 = fig4.add_subplot(311)\n ax1.set_title(\"Translation vs. vNAV frame number\")\n ax1.plot(t, self._tx_comm, line_color)\n ax1.grid(True)\n ax1.set_ylim((mt, Mt))\n ax1.set_ylabel('TX [mm]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_mm)\n self._draw_events(ax1, t, range_mm, events)\n\n ax1 = fig4.add_subplot(312)\n # ax1.set_title(\"Translation comments Y\")\n ax1.plot(t, self._ty_comm, line_color)\n ax1.grid(True)\n ax1.set_ylim((mt, Mt))\n ax1.set_ylabel('TY [mm]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_mm)\n self._draw_events(ax1, t, range_mm, events)\n\n ax1 = fig4.add_subplot(313)\n # ax1.set_title(\"Translation comments Z\")\n ax1.plot(t, self._tz_comm, line_color)\n ax1.grid(True)\n ax1.set_ylim((mt, Mt))\n ax1.set_ylabel('TZ [mm]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n if extract_events_threshold is not None:\n self._draw_rectangles(ax1, windows, range_mm)\n self._draw_events(ax1, t, range_mm, events)\n\n # if save_to_file is not None:\n # plt.savefig(save_to_file)\n else:\n fig3 = None\n fig4 = None\n\n plt.show()\n return fig1, fig2, fig3, fig4\n\n def get_mean_displacement(self, index, method='box', box_min=BOX_MIN, box_max=BOX_MAX):\n mat = self.get_motion_affine(index)\n mat = Transform_Affine(mat)\n if method == 'box':\n b = box_min\n B = box_max\n corners = numpy.asarray(\n [[b[0], b[1], b[2], 1], [B[0], b[1], b[2], 1], [b[0], B[1], b[2], 1], [B[0], B[1], b[2], 1],\n [b[0], b[1], B[2], 1], [B[0], b[1], B[2], 1], [b[0], B[1], B[2], 1],\n [B[0], B[1], B[2], 1]]).transpose()\n corners_t = mat.left_multiply(corners)\n corners_t[3, :] = 0\n corners[3, :] = 0\n # print \"CORNERS: \", corners_t\n # dist = numpy.sqrt(((corners-corners_t)**2).sum(0))\n dist = (corners - corners_t).sum(0)\n mean_displ = numpy.mean(dist)\n else:\n raise (\"Method to compute mean displacement is unknown. \")\n return mean_displ\n\n def get_mean_displacement_variation(self, index, method='box', box_min=BOX_MIN, box_max=BOX_MAX):\n mat = self.get_motion_affine(index)\n if index > 0:\n mat0 = self.get_motion_affine(index - 1)\n else:\n mat0 = tr.identity_matrix()\n mat = Transform_Affine(mat)\n mat0 = Transform_Affine(mat0)\n if method == 'box':\n b = box_min\n B = box_max\n corners = numpy.asarray(\n [[b[0], b[1], b[2], 1], [B[0], b[1], b[2], 1], [b[0], B[1], b[2], 1], [B[0], B[1], b[2], 1],\n [b[0], b[1], B[2], 1], [B[0], b[1], B[2], 1], [b[0], B[1], B[2], 1],\n [B[0], B[1], B[2], 1]]).transpose()\n corners_t = mat.left_multiply(corners)\n corners_t[3, :] = 0\n corners_t0 = mat0.left_multiply(corners)\n corners_t0[3, :] = 0\n dist = numpy.sqrt(((corners_t - corners_t0) ** 2).sum(0))\n # dist = (corners-corners_t).sum(0)\n mean_displ = numpy.mean(dist)\n else:\n raise (\"Method to compute mean displacement is unknown. \")\n return mean_displ\n\n def get_mean_displacement_variation_since_time(self, index_new, index_old, method='box', box_min=BOX_MIN,\n box_max=BOX_MAX):\n mat = self.get_motion_affine(index_new)\n mat0 = self.get_motion_affine(index_old)\n mat = Transform_Affine(mat)\n mat0 = Transform_Affine(mat0)\n if method == 'box':\n b = box_min\n B = box_max\n corners = numpy.asarray(\n [[b[0], b[1], b[2], 1], [B[0], b[1], b[2], 1], [b[0], B[1], b[2], 1], [B[0], B[1], b[2], 1],\n [b[0], b[1], B[2], 1], [B[0], b[1], B[2], 1], [b[0], B[1], B[2], 1],\n [B[0], B[1], B[2], 1]]).transpose()\n corners_t = mat.left_multiply(corners)\n corners_t[3, :] = 0\n corners_t0 = mat0.left_multiply(corners)\n corners_t0[3, :] = 0\n dist = numpy.sqrt(((corners_t - corners_t0) ** 2).sum(0))\n # dist = (corners-corners_t).sum(0)\n mean_displ = numpy.mean(dist)\n else:\n raise (\"Method to compute mean displacement is unknown. \")\n return mean_displ\n\n def extract_motion_events(self, method='box', threshold=THRESHOLD_MM, box_min=BOX_MIN, box_max=BOX_MAX):\n t = range(self.get_n_time_points())\n is_event = numpy.zeros(len(t) - 1)\n t_index_old = 0\n for t_index in t[1:]:\n # mean_displ = self.get_mean_displacement_variation(t_index, method, box_min, box_max ) \n # if numpy.sqrt((mean_displ)**2) >= threshold: \n\n mean_displ = self.get_mean_displacement_variation_since_time(t_index, t_index_old, method, box_min, box_max)\n if numpy.sqrt((mean_displ) ** 2) >= threshold:\n t_index_old = numpy.copy(t_index)\n is_event[t_index - 1] = 1\n else:\n is_event[t_index - 1] = 0\n return is_event\n\n def plot_mean_displacement(self, method='box', box_min=BOX_MIN, box_max=BOX_MAX, save_to_file=None, plot_zero=False,\n extract_events_threshold=THRESHOLD_MM, plot_range=(None, None), line_color=LINE_COLOR,\n min_duration=1, figsize=(10, 5)):\n t = range(self.get_n_time_points())\n mean_displ = numpy.zeros(len(t))\n mean_displ_var = numpy.zeros(len(t))\n mean_displ_var_since_event = numpy.zeros(len(t))\n\n if extract_events_threshold is not None:\n events = self.extract_motion_events(method, extract_events_threshold, box_min, box_max)\n\n t_index_old = 0\n for t_index in t:\n mean_displ[t_index] = self.get_mean_displacement(t_index, method, box_min, box_max)\n mean_displ_var[t_index] = self.get_mean_displacement_variation(t_index, method, box_min, box_max)\n mean_displ_var_since_event[t_index] = self.get_mean_displacement_variation_since_time(t_index, t_index_old,\n method, box_min,\n box_max)\n if t_index:\n if events[t_index - 1] == 1:\n t_index_old = t_index - 1\n if not plot_zero:\n t = t[1:]\n mean_displ = mean_displ[1:]\n mean_displ_var = mean_displ_var[1:]\n mean_displ_var_since_event = mean_displ_var_since_event[1:]\n\n # make windows:\n if extract_events_threshold is not None:\n windows = []\n events = self.extract_motion_events(method, extract_events_threshold, box_min, box_max)\n t_index_start = 0\n for t_index in t:\n if t_index: # this excludes the possibility of a motion event at time 0 \n if events[t_index - 1]:\n t_index_end = t_index - 1\n if t_index_end - t_index_start > min_duration:\n windows.append((t_index_start, t_index_end)) # end window with frame before a motion event \n t_index_start = t_index + 1 # start window with frame after a motion event \n windows.append((t_index_start, t[-1]))\n\n # mean_displ[numpy.where(mean_displ==0)]=-1000\n # mean_displ_var[numpy.where(mean_displ_var==0)]=-1000\n # mean_displ_var_since_event[numpy.where(mean_displ_var_since_event==0)]=-1000\n\n fig = plt.figure(5, figsize=figsize)\n\n ax1 = fig.add_subplot(311)\n ax1.set_title(\"Times frames - vNAV\")\n ax1.plot(t, mean_displ, line_color)\n ax1.grid(True)\n if plot_range[0] is None:\n pr0 = copy.copy(mean_displ.min())\n else:\n pr0 = copy.copy(plot_range[0])\n if plot_range[1] is None:\n pr1 = copy.copy(mean_displ.max())\n else:\n pr1 = copy.copy(plot_range[1])\n ax1.set_ylim([pr0, pr1])\n ax1.set_ylabel('disp [mm]')\n if extract_events_threshold is not None:\n ax1.hold(1)\n E = events * mean_displ\n E[numpy.where(E < 0.1)] = -1000\n ax1.plot(t, E, 'r.')\n # ax1.plot(t,0.5*(events*(mean_displ.max()-mean_displ.min())+mean_displ.min()),'r.')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n self._draw_rectangles(ax1, windows, [pr0, pr1])\n self._draw_events(ax1, t, [pr0, pr1], events)\n\n ax1 = fig.add_subplot(312)\n # ax1.set_title(\"Mean displacement delta \")\n ax1.plot(t, mean_displ_var, line_color)\n ax1.grid(True)\n if plot_range[0] is None:\n pr0 = copy.copy(mean_displ_var.min())\n else:\n pr0 = copy.copy(plot_range[0])\n if plot_range[1] is None:\n pr1 = copy.copy(mean_displ_var.max())\n else:\n pr1 = copy.copy(plot_range[1])\n ax1.set_ylim([pr0, pr1])\n ax1.set_ylabel('delta [mm]')\n if extract_events_threshold is not None:\n ax1.hold(1)\n E = events * mean_displ_var\n E[numpy.where(E < 0.1)] = -1000\n ax1.plot(t, E, 'r.')\n # ax1.plot(t,0.5*(events*(mean_displ.max()-mean_displ.min())+mean_displ.min()),'r.')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n self._draw_rectangles(ax1, windows, [pr0, pr1])\n self._draw_events(ax1, t, [pr0, pr1], events)\n\n ax1 = fig.add_subplot(313)\n # ax1.set_title(\"Mean displacement event\")\n ax1.plot(t, mean_displ_var_since_event, line_color)\n ax1.grid(True)\n if plot_range[0] is None:\n pr0 = copy.copy(mean_displ_var_since_event.min())\n else:\n pr0 = copy.copy(plot_range[0])\n if plot_range[1] is None:\n pr1 = copy.copy(mean_displ_var_since_event.max())\n else:\n pr1 = copy.copy(plot_range[1])\n ax1.set_ylim([pr0, pr1])\n ax1.set_ylabel('event [mm]')\n if extract_events_threshold is not None:\n ax1.hold(1)\n E = events * mean_displ_var_since_event\n E[numpy.where(E < 0.1)] = -1000\n ax1.plot(t, E, 'r.')\n # ax1.plot(t,0.5*(events*(mean_displ.max()-mean_displ.min())+mean_displ.min()),'r.')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n self._draw_rectangles(ax1, windows, [pr0, pr1])\n self._draw_events(ax1, t, [pr0, pr1], events)\n\n if save_to_file is not None:\n plt.savefig(save_to_file)\n plt.show()\n return fig\n\n def plot_quaternion(self, save_to_file=None, plot_range=(None, None), line_color=LINE_COLOR, figsize=(10, 5)):\n t = range(self.get_n_time_points())[1:]\n s = rad_to_deg(numpy.asarray(self._a0_comm))[1:]\n\n fig = plt.figure(6, figsize=figsize)\n ax1 = fig.add_subplot(211)\n ax1.set_title(\"Rotation agnle [deg] vs. vNAV frame number\")\n ax1.plot(t, s, line_color)\n ax1.grid(True)\n if plot_range[0] is None:\n plot_range[0] = s.min()\n if plot_range[1] is None:\n plot_range[1] = s.max()\n ax1.set_ylim(plot_range)\n ax1.set_ylabel('Rotation angle [deg]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n\n arc = numpy.zeros(self.get_n_time_points())\n v0 = numpy.asarray(self._a1_comm[0], self._a2_comm[0], self._a3_comm[0])\n for t in range(self.get_n_time_points()):\n vt = numpy.asarray(self._a1_comm[t], self._a2_comm[t], self._a3_comm[t])\n arc[t] = numpy.dot(numpy.transpose(v0), vt)\n ax1 = fig.add_subplot(212)\n ax1.set_title(\"Arc vs. vNAV frame number\")\n t = range(self.get_n_time_points())\n ax1.plot(t, arc, line_color)\n ax1.grid(True)\n plot_range[0] = arc.min() - 0.0001\n plot_range[1] = arc.max() + 0.0001\n ax1.set_ylim(plot_range)\n ax1.set_ylabel('Arc [steradians]')\n # for label in ax1.get_xticklabels():\n # label.set_color('r')\n\n if save_to_file is not None:\n plt.savefig(save_to_file)\n plt.show()\n return fig\n\n def _repr_html_(self):\n self.plot_mean_displacement()\n\n\ndef load_vnav_mprage(path, from_dicom_comments=True, files_start_with=None, files_end_with=None):\n return vNAV_MPRage(path, from_dicom_comments, files_start_with, files_end_with)\n"
]
| [
[
"matplotlib.pyplot.Rectangle",
"numpy.dot",
"numpy.sqrt",
"numpy.asarray",
"numpy.cos",
"matplotlib.pyplot.savefig",
"numpy.sin",
"numpy.copy",
"numpy.mean",
"numpy.float32",
"numpy.transpose",
"matplotlib.pyplot.show",
"numpy.where",
"matplotlib.pyplot.figure"
]
]
|
vishalbelsare/pymcmcstat | [
"b4b10547ce00fe5e095871ae8ee48b381d9a2a2b"
]
| [
"test/plotting/test_utilities.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed May 30 05:57:34 2018\n\n@author: prmiles\n\"\"\"\n\nfrom pymcmcstat.plotting import utilities\nimport unittest\nfrom mock import patch\nimport numpy as np\nimport math\n\n# --------------------------\nclass GenerateSubplotGrid(unittest.TestCase):\n def test_generate_subplot_grid(self):\n nparam = 5\n ns1, ns2 = utilities.generate_subplot_grid(nparam = nparam)\n self.assertEqual(ns1, math.ceil(math.sqrt(nparam)), msg = 'Expect 3')\n self.assertEqual(ns2, round(math.sqrt(nparam)), msg = 'Expect 2')\n\n def test_generate_subplot_grid_1(self):\n nparam = 1\n ns1, ns2 = utilities.generate_subplot_grid(nparam = nparam)\n self.assertEqual(ns1, math.ceil(math.sqrt(nparam)), msg = 'Expect 1')\n self.assertEqual(ns2, round(math.sqrt(nparam)), msg = 'Expect 1')\n\n# --------------------------\nclass GenerateNames(unittest.TestCase):\n \n def test_default_names(self):\n nparam = 8\n names = utilities.generate_names(nparam = nparam, names = None)\n self.assertEqual(len(names), nparam, msg = 'Length of names should match number of parameters')\n for ii in range(nparam):\n self.assertEqual(names[ii], str('$p_{{{}}}$'.format(ii)))\n\n def test_names_partial(self):\n nparam = 8\n names = ['hi']\n names = utilities.generate_names(nparam = nparam, names = names)\n self.assertEqual(names[0], 'hi', msg = 'First name is hi')\n for ii in range(1, nparam):\n self.assertEqual(names[ii], str('$p_{{{}}}$'.format(ii)))\n \n# --------------------------\nclass SetupPlotFeatures(unittest.TestCase):\n def test_default_features(self):\n nparam = 2\n ns1, ns2, names, figsizeinches = utilities.setup_plot_features(nparam = nparam, names = None, figsizeinches = None)\n self.assertEqual(ns1, math.ceil(math.sqrt(nparam)), msg = 'Expect 3')\n self.assertEqual(ns2, round(math.sqrt(nparam)), msg = 'Expect 2')\n for ii in range(nparam):\n self.assertEqual(names[ii], str('$p_{{{}}}$'.format(ii)))\n self.assertEqual(figsizeinches, [5,4], msg = 'Default figure size is [5,4]')\n \n def test_nondefault_features(self):\n nparam = 2\n ns1, ns2, names, figsizeinches = utilities.setup_plot_features(nparam = nparam, names = ['hi'], figsizeinches = [7,2])\n self.assertEqual(ns1, math.ceil(math.sqrt(nparam)), msg = 'Expect 3')\n self.assertEqual(ns2, round(math.sqrt(nparam)), msg = 'Expect 2')\n self.assertEqual(names[0], 'hi', msg = 'First name is hi')\n for ii in range(1, nparam):\n self.assertEqual(names[ii], str('$p_{{{}}}$'.format(ii)))\n self.assertEqual(figsizeinches, [7,2], msg = 'Default figure size is [7,2]')\n \n# --------------------------\nclass GenerateDefaultNames(unittest.TestCase):\n \n def test_size_of_default_names(self):\n nparam = 8\n names = utilities.generate_default_names(nparam = nparam)\n self.assertEqual(len(names), nparam, msg = 'Length of names should match number of parameters')\n \n def test_value_of_default_names(self):\n names = utilities.generate_default_names(nparam = 3)\n expected_names = ['$p_{0}$','$p_{1}$','$p_{2}$']\n self.assertEqual(names, expected_names,\n msg = str('Names do not match: Expected - {}, Received - {}'.format(expected_names, names)))\n\n# --------------------------\nclass ExtendNamesToMatchNparam(unittest.TestCase):\n \n def test_initially_empty_name_set(self):\n nparam = 3\n names = utilities.extend_names_to_match_nparam(names = None, nparam = nparam)\n expected_names = ['$p_{0}$','$p_{1}$','$p_{2}$']\n self.assertEqual(names, expected_names,\n msg = str('Names do not match: Expected - {}, Received - {}'.format(expected_names, names)))\n \n def test_single_entry_name_set(self):\n nparam = 3\n names = ['aa']\n names = utilities.extend_names_to_match_nparam(names = names, nparam = nparam)\n expected_names = ['aa','$p_{1}$','$p_{2}$']\n self.assertEqual(names, expected_names,\n msg = str('Names do not match: Expected - {}, Received - {}'.format(expected_names, names)))\n\n def test_double_entry_name_set(self):\n nparam = 3\n names = ['aa', 'zz']\n names = utilities.extend_names_to_match_nparam(names = names, nparam = nparam)\n expected_names = ['aa','zz','$p_{2}$']\n self.assertEqual(names, expected_names, \n msg = str('Names do not match: Expected - {}, Received - {}'.format(expected_names, names)))\n \n# --------------------------\nclass MakeXGrid(unittest.TestCase):\n \n def test_shape_of_output(self):\n x = np.linspace(0, 10, num = 50)\n npts = 20\n xgrid = utilities.make_x_grid(x = x, npts = 20)\n self.assertEqual(xgrid.shape, (npts, 1), msg = str('Expected return dimension of ({}, 1)'.format(npts)))\n \n def test_default_shape_of_output(self):\n x = np.linspace(0, 10, num = 50)\n xgrid = utilities.make_x_grid(x = x)\n self.assertEqual(xgrid.shape, (100, 1), msg = 'Expected return dimension of (100, 1)')\n \n def test_shape_of_output_for_dense_x(self):\n x = np.linspace(0, 10, num = 500)\n npts = 20\n xgrid = utilities.make_x_grid(x = x, npts = 20)\n self.assertEqual(xgrid.shape, (npts, 1), msg = 'Expected return dimension of (npts, 1)')\n \n def test_default_shape_of_output_for_dense_x(self):\n x = np.linspace(0, 10, num = 500)\n xgrid = utilities.make_x_grid(x = x)\n self.assertEqual(xgrid.shape, (100, 1), msg = 'Expected return dimension of (100, 1)')\n \n# --------------------------\nclass GenerateEllipse(unittest.TestCase):\n\n def test_does_non_square_matrix_return_error(self):\n cmat = np.zeros([3,2])\n mu = np.zeros([2,1])\n with self.assertRaises(SystemExit):\n utilities.generate_ellipse(mu, cmat)\n \n def test_does_non_symmetric_matrix_return_error(self):\n cmat = np.array([[3,2],[1,3]])\n mu = np.zeros([2,1])\n with self.assertRaises(SystemExit):\n utilities.generate_ellipse(mu, cmat)\n \n def test_does_non_positive_definite_matrix_return_error(self):\n cmat = np.zeros([2,2])\n mu = np.zeros([2,1])\n with self.assertRaises(SystemExit):\n utilities.generate_ellipse(mu, cmat)\n \n def test_does_good_matrix_return_equal_sized_xy_arrays(self):\n cmat = np.eye(2)\n mu = np.zeros([2,1])\n x,y = utilities.generate_ellipse(mu, cmat)\n self.assertEqual(x.shape,y.shape)\n \n def test_does_good_matrix_return_correct_size_array(self):\n cmat = np.eye(2)\n mu = np.zeros([2,1])\n ndp = 50 # number of points to generate ellipse shape\n x,y = utilities.generate_ellipse(mu, cmat, ndp)\n self.assertEqual(x.size, ndp)\n self.assertEqual(y.size, ndp)\n \n# --------------------------\nclass GaussianDensityFunction(unittest.TestCase):\n \n def test_float_return_with_float_input(self):\n self.assertTrue(isinstance(utilities.gaussian_density_function(x = 0.), float),\n msg = 'Expected float return')\n \n def test_float_return_with_int_input(self):\n self.assertTrue(isinstance(utilities.gaussian_density_function(x = 0), float),\n msg = 'Expected float return')\n \n def test_float_return_with_float_input_at_nondefault_mean(self):\n self.assertTrue(isinstance(utilities.gaussian_density_function(x = 0., mu = 100), float),\n msg = 'Expected float return')\n \n# --------------------------\nclass IQrange(unittest.TestCase):\n \n def test_array_return_with_column_vector_input(self):\n x = np.random.random_sample(size = (100,1))\n q = utilities.iqrange(x = x)\n self.assertTrue(isinstance(q, np.ndarray), msg = 'Expected array return - received {}'.format(type(q)))\n self.assertEqual(q.size, 1, msg = 'Expect single element array')\n \n def test_array_return_with_row_vector_input(self):\n x = np.random.random_sample(size = (1,100))\n q = utilities.iqrange(x = x)\n self.assertTrue(isinstance(q, np.ndarray), msg = 'Expected array return - received {}'.format(type(q)))\n self.assertEqual(q.size, 1, msg = 'Expect single element array')\n \n# --------------------------\nclass ScaleBandWidth(unittest.TestCase):\n \n def test_array_return_with_column_vector_input(self):\n x = np.random.random_sample(size = (100,1))\n s = utilities.scale_bandwidth(x = x)\n self.assertTrue(isinstance(s, np.ndarray), msg = 'Expected array return - received {}'.format(type(s)))\n self.assertEqual(s.size, 1, msg = 'Expect single element array')\n \n def test_array_return_with_row_vector_input(self):\n x = np.random.random_sample(size = (1,100))\n s = utilities.scale_bandwidth(x = x)\n self.assertTrue(isinstance(s, np.ndarray), msg = 'Expected array return - received {}'.format(type(s)))\n self.assertEqual(s.size, 1, msg = 'Expect single element array')\n \n @patch('pymcmcstat.plotting.utilities.iqrange', return_value = -1.0)\n def test_array_return_with_iqrange_lt_0(self, mock_iqrange):\n x = np.random.random_sample(size = (1,100))\n s = utilities.scale_bandwidth(x = x)\n self.assertTrue(isinstance(s, np.ndarray), msg = 'Expected array return - received {}'.format(type(s)))\n self.assertEqual(s.size, 1, msg = 'Expect single element array')\n \n @patch('pymcmcstat.plotting.utilities.iqrange', return_value = 1.0)\n def test_array_return_with_iqrange_gt_0(self, mock_iqrange):\n x = np.random.random_sample(size = (1,100))\n s = utilities.scale_bandwidth(x = x)\n self.assertTrue(isinstance(s, np.ndarray), msg = 'Expected array return - received {}'.format(type(s)))\n self.assertEqual(s.size, 1, msg = 'Expect single element array')\n \n# --------------------------\nclass AppendToNrowNcolBasedOnShape(unittest.TestCase):\n def test_shape_is_2d(self):\n nrow = []\n ncol = []\n sh = (2,1)\n nrow, ncol = utilities.append_to_nrow_ncol_based_on_shape(sh = sh, nrow = nrow, ncol = ncol)\n self.assertEqual(nrow, [2], msg = 'Expect [2]')\n self.assertEqual(ncol, [1], msg = 'Expect [1]')\n \n def test_shape_is_1d(self):\n nrow = []\n ncol = []\n sh = (2,)\n nrow, ncol = utilities.append_to_nrow_ncol_based_on_shape(sh = sh, nrow = nrow, ncol = ncol)\n self.assertEqual(nrow, [2], msg = 'Expect [2]')\n self.assertEqual(ncol, [1], msg = 'Expect [1]')\n \n# --------------------------\nclass ConvertFlagToBoolean(unittest.TestCase):\n def test_boolean_conversion(self):\n self.assertTrue(utilities.convert_flag_to_boolean(flag = 'on'), msg = 'on -> True')\n self.assertFalse(utilities.convert_flag_to_boolean(flag = 'off'), msg = 'off -> False')\n \n# --------------------------\nclass SetLocalParameters(unittest.TestCase):\n def test_set_local_parameters(self):\n slp = utilities.set_local_parameters\n self.assertTrue(np.array_equal(slp(ii = 0, local = np.array([0, 0])), np.array([True, True])), msg = 'Expect Array [True, True]')\n self.assertTrue(np.array_equal(slp(ii = 0, local = np.array([0, 1])), np.array([True, False])), msg = 'Expect Array [True, False]')\n self.assertTrue(np.array_equal(slp(ii = 0, local = np.array([1, 0])), np.array([False, True])), msg = 'Expect Array [False, True]')\n\n self.assertTrue(np.array_equal(slp(ii = 1, local = np.array([0, 1])), np.array([True, True])), msg = 'Expect Array [True, True]')\n self.assertTrue(np.array_equal(slp(ii = 1, local = np.array([1, 0])), np.array([True, True])), msg = 'Expect Array [True, True]')\n \n self.assertTrue(np.array_equal(slp(ii = 1, local = np.array([2, 2])), np.array([False, False])), msg = 'Expect Array [False, False]')\n self.assertTrue(np.array_equal(slp(ii = 2, local = np.array([1, 2])), np.array([False, True])), msg = 'Expect Array [False, True]')\n \n# --------------------------------------------\nclass Empirical_Quantiles_Test(unittest.TestCase):\n\n def test_does_default_empirical_quantiles_return_3_element_array(self):\n test_out = utilities.empirical_quantiles(np.random.rand(10,1))\n self.assertEqual(test_out.shape, (3,1), msg = 'Default output shape is (3,1)')\n \n def test_does_non_default_empirical_quantiles_return_2_element_array(self):\n test_out = utilities.empirical_quantiles(np.random.rand(10,1), p = np.array([0.2, 0.5]))\n self.assertEqual(test_out.shape, (2,1), msg = 'Non-default output shape should be (2,1)')\n \n def test_empirical_quantiles_should_not_support_list_input(self):\n with self.assertRaises(AttributeError):\n utilities.empirical_quantiles([-1,0,1])\n \n def test_empirical_quantiles_vector(self):\n out = utilities.empirical_quantiles(np.linspace(10,20, num = 10).reshape(10,1), p = np.array([0.22, 0.57345]))\n exact = np.array([[12.2], [15.7345]])\n comp = np.linalg.norm(out - exact)\n self.assertAlmostEqual(comp, 0)\n \n# --------------------------\nclass CheckSettings(unittest.TestCase):\n\n def test_settings_with_user_none(self):\n user_settings = None\n default_settings = dict(a = False, linewidth = 3, marker = dict(markersize = 5, color = 'g'))\n settings = utilities.check_settings(default_settings = default_settings, user_settings = user_settings)\n self.assertEqual(settings, default_settings, msg = str('Expect dictionaries to match: {} neq {}'.format(settings, default_settings)))\n \n def test_settings_with_subdict(self):\n user_settings = dict(a = True, fontsize = 12)\n default_settings = dict(a = False, linewidth = 3, marker = dict(markersize = 5, color = 'g'))\n settings = utilities.check_settings(default_settings = default_settings, user_settings = user_settings)\n self.assertEqual(settings['a'], user_settings['a'], msg = 'Expect user setting to overwrite')\n self.assertEqual(settings['marker'], default_settings['marker'], msg = 'Expect default to persist')\n \n def test_settings_with_subdict_user_ow(self):\n user_settings = dict(a = True, fontsize = 12, marker = dict(color = 'b'))\n default_settings = dict(a = False, linewidth = 3, marker = dict(markersize = 5, color = 'g'))\n settings = utilities.check_settings(default_settings = default_settings, user_settings = user_settings)\n self.assertEqual(settings['a'], user_settings['a'], msg = 'Expect user setting to overwrite')\n self.assertEqual(settings['marker']['color'], user_settings['marker']['color'], msg = 'Expect user to overwrite')\n self.assertEqual(settings['marker']['markersize'], default_settings['marker']['markersize'], msg = 'Expect default to persist')\n \n def test_settings_with_subdict_user_has_new_setting(self):\n user_settings = dict(a = True, fontsize = 12, marker = dict(color = 'b'), linestyle = '--')\n default_settings = dict(a = False, linewidth = 3, marker = dict(markersize = 5, color = 'g'))\n settings = utilities.check_settings(default_settings = default_settings, user_settings = user_settings)\n self.assertEqual(settings['a'], user_settings['a'], msg = 'Expect user setting to overwrite')\n self.assertEqual(settings['marker']['color'], user_settings['marker']['color'], msg = 'Expect user to overwrite')\n self.assertEqual(settings['marker']['markersize'], default_settings['marker']['markersize'], msg = 'Expect default to persist')\n self.assertEqual(settings['linestyle'], user_settings['linestyle'], msg = 'Expect user setting to be added')\n\n\n# --------------------------\nclass SetupSubsample(unittest.TestCase):\n\n def test_max_lt_nsimu(self):\n skip = 1\n maxpoints = 10\n nsimu = 100\n inds = utilities.setup_subsample(skip, maxpoints, nsimu)\n self.assertTrue(isinstance(inds, np.ndarray),\n msg='Expect numpy array')\n self.assertEqual(inds.shape, (10,), msg='Expect (10,)')\n\n def test_max_gt_nsimu(self):\n skip = 1\n maxpoints = 1000\n nsimu = 100\n inds = utilities.setup_subsample(skip, maxpoints, nsimu)\n self.assertTrue(isinstance(inds, np.ndarray),\n msg='Expect numpy array')\n self.assertEqual(inds.shape, (100,), msg='Expect (100,)')\n skip = 3\n maxpoints = 1000\n nsimu = 100\n inds = utilities.setup_subsample(skip, maxpoints, nsimu)\n self.assertTrue(isinstance(inds, np.ndarray),\n msg='Expect numpy array')\n self.assertEqual(inds.shape, (34,), msg='Expect (34,)')\n\n def test_max_eq_nsimu(self):\n skip = 1\n maxpoints = 100\n nsimu = 100\n inds = utilities.setup_subsample(skip, maxpoints, nsimu)\n self.assertTrue(isinstance(inds, np.ndarray),\n msg='Expect numpy array')\n self.assertEqual(inds.shape, (100,), msg='Expect (100,)')"
]
| [
[
"numpy.linspace",
"numpy.eye",
"numpy.random.random_sample",
"numpy.linalg.norm",
"numpy.random.rand",
"numpy.array",
"numpy.zeros"
]
]
|
tdp2110/dldt | [
"87f321c5365ed813e849ea0ed987354ef2c39743"
]
| [
"model-optimizer/extensions/ops/sparse_segment_sqrtn.py"
]
| [
"\"\"\"\n Copyright (c) 2019 Intel 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\nimport logging as log\n\nimport networkx as nx\nimport numpy as np\n\nfrom mo.graph.graph import Node, Graph\nfrom mo.ops.op import Op\n\n\nclass SparseSegmentSqrtN(Op):\n ''' The operation computes the sum along sparse segments of a tensor and divides it by the square root of N, where N is a number of rows in a segment.\n For more details, see https://www.tensorflow.org/api_docs/cc/class/tensorflow/ops/sparse-segment-sqrt-n.\n\n Three inputs:\n - [0, required] Data tensor from which rows are selected for the sum divided by sqrt of N (ND),\n - [1, required] Tensor of indices of selected rows from the first input tensor along 0 dimension (1D),\n - [2, required] Tensor of segment IDs to which selected rows belong.\n Selected rows beloging to the same segment are summed up. The tensor has the same size as the second input.\n Values must be sorted and can be repeated. (1D).\n \n One output:\n - [0, required] The output has the same shape as the data tensor, except for dimension 0, which has a size equal to a number of segments (ND).\n '''\n op = 'SparseSegmentSqrtN'\n\n def __init__(self, graph: Graph, attrs: dict):\n mandatory_props = {\n 'type': __class__.op,\n 'op': __class__.op,\n 'infer': __class__.infer,\n 'in_ports_count': 3,\n 'out_ports_count': 1,\n }\n super().__init__(graph, mandatory_props, attrs)\n\n def supported_attrs(self):\n return []\n\n @staticmethod\n def infer(node: Node):\n # check a number of input/output edges\n assert len(node.in_nodes()) == 3\n assert len(node.out_nodes()) == 1\n\n data_shape = node.in_port(0).data.get_shape()\n indices_shape = node.in_port(1).data.get_shape()\n segment_ids_shape = node.in_port(2).data.get_shape()\n data_value = node.in_port(0).data.get_value()\n indices_value = node.in_port(1).data.get_value()\n segment_ids_value = node.in_port(2).data.get_value()\n\n # check input shapes\n assert data_shape is not None, \\\n \"Shape for input data tensor to SparseSegmentSqrtN must be defined\"\n assert indices_shape is not None and indices_shape.size == 1, \\\n \"SparseSegmentSqrtN supports only 1D indices tensor\"\n assert segment_ids_shape is not None and segment_ids_shape.size == 1, \\\n \"SparseSegmentSqrtN supports only 1D segment IDs tensor\"\n assert segment_ids_shape == indices_shape, \\\n \"Indices and segment IDs tensors must have the same shape\"\n\n # computes output shape\n output_shape = data_shape\n output_shape[0] = segment_ids_shape[0]\n node.out_port(0).data.set_shape(output_shape)\n\n # infer if all input is constant\n if data_value is None or indices_value is None or segment_ids_value is None:\n return\n\n # check that values in segment_ids are sorted\n for i in range(1, len(segment_ids_value)):\n assert segment_ids_value[i-1] <= segment_ids_value[i], \\\n \"Values in segment IDs are not sorted\"\n num_segments = int(segment_ids_value[-1]) + 1\n\n # check that indices are in a range [0, data_shape[0])\n assert np.all(indices_value >= 0) and np.all(indices_value < data_shape[0]), \\\n \"Some value in indices tensor is out of range\"\n\n # infer\n num_adds = np.zeros(num_segments, dtype=np.int)\n output_value = np.zeros([num_segments] + data_shape[1:].tolist(), dtype=np.float)\n output_shape = output_value.shape\n for i in range(len(segment_ids_value)):\n segment_id = int(segment_ids_value[i])\n indice = int(indices_value[i])\n output_value[segment_id, :] += data_value[indice, :]\n num_adds[segment_id] += 1\n \n num_adds = np.sqrt(num_adds)\n for segment_id in range(num_segments):\n if num_adds[segment_id] != 0:\n output_value[segment_id, :] /= num_adds[segment_id]\n node.out_port(0).data.set_shape(output_shape)\n node.out_port(0).data.set_value(output_value)\n"
]
| [
[
"numpy.all",
"numpy.zeros",
"numpy.sqrt"
]
]
|
judejeh/dominance-analysis-1.0.8.1 | [
"1fe7a361d4ca3a90f7ec062c036991b3bb44950a"
]
| [
"dominance_analysis/dominance.py"
]
| [
"import numpy as np\nfrom itertools import combinations\nimport sklearn\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.datasets import load_breast_cancer\nfrom sklearn.datasets import load_boston\nfrom tqdm import tqdm\nfrom sklearn.feature_selection import SelectKBest,chi2,f_regression\nimport pandas as pd\nfrom plotly import offline\nfrom plotly.offline import init_notebook_mode,iplot\nimport cufflinks as cf\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import log_loss\nimport statsmodels.api as sm\nfrom functools import reduce\nimport math\nimport random\n\nfrom bokeh.plotting import figure, show\nfrom bokeh.io import output_notebook\nfrom bokeh.models import ColumnDataSource, LabelSet\nfrom bokeh.models.formatters import NumeralTickFormatter\noutput_notebook()\ninit_notebook_mode(connected=True)\n\n\nclass Dominance:\n\t\"\"\"docstring for ClassName\"\"\"\n\tdef __init__(self,data,target,top_k=None,objective=1,pseudo_r2='mcfadden',data_format = 0): # Bala changes\n\t\t# super(ClassName, self).__init__()\n\t\tself.data = data\n\t\tself.target=target\n\t\tself.objective=objective\n#Bala changes start \n\t\tself.data_format = data_format\n\t\tif(self.data_format==0):\n#Bala changes end \n\t\t\tif(self.objective==0):\n\t\t\t\tself.data['intercept']=1\n\t\t\tself.top_k=top_k if top_k else min((len(self.data.columns)-1),15)\n\t\t\tself.pseudo_r2=pseudo_r2\n\t\t\tassert (self.top_k >1 ) and (self.top_k<(len(self.data.columns))),\"Value of top_k ranges from 1 to n-1 !\"\n\t\tself.complete_model_rsquare()\n\n \n\n\t\n\tdef conditional_dominance(self,model_rsquares,model_features_k,model_features_k_minus_1,columns):\n\t\t# print(\"#\"*25,\" Calculating Conditional Dominance \",\"#\"*25)\n\t\ttotal_model_r2=model_rsquares[\" \".join(model_features_k[0])]\n\t\t\n\t\tinteractional_comp_dom={}\n\t\tfor i in model_features_k_minus_1:\n\t\t\tinteractional_comp_dom[\" \".join(set(model_features_k[0])-set(i))]={\" \".join(set(i)):total_model_r2-model_rsquares[\" \".join(i)]}\n\t\t# print(\"Interactional Dominance\",interactional_comp_dom)\n\n\t\tinteractional_dominance=dict({(\" \".join(set(model_features_k[0])-set(i)),total_model_r2-model_rsquares[\" \".join(i)]) for i in model_features_k_minus_1})\n\t\treturn (interactional_dominance,interactional_comp_dom)\n\n\tdef individual_dominance(self,model_rsquares,model_features,columns):\n\t\t# print(\"#\"*25,\" Calculating individual Dominance \",\"#\"*25)\n\t\treturn dict({(\" \".join(col),model_rsquares[\" \".join(col)]) for col in model_features })\n\n\tdef partial_dominance(self,model_rsquares,model_features_k,model_features_k_minus_1,columns):\n\t\t# print(columns)\n\t\tpd={col: [] for col in columns}\n\t\t[pd[\" \".join(set(i)-set(j))].append(model_rsquares[\" \".join(i)]-model_rsquares[\" \".join(j)]) for i in model_features_k for j in model_features_k_minus_1 if(len(set(i)-set(j))==1)]\n\n\t\tpd_comp_dom={col: {} for col in columns}\n\n\t\tfor i in model_features_k:\n\t\t\tfor j in model_features_k_minus_1:\n\t\t\t\tif(len(set(i)-set(j))==1):\n\t\t\t\t\tpd_comp_dom[\" \".join(set(i)-set(j))].update({\n\t\t\t\t\t\" \".join(j):model_rsquares[\" \".join(i)]-model_rsquares[\" \".join(j)]\n\t\t\t\t\t})\n\n\t\t# [pd_comp_dom[\" \".join(set(i)-set(j))].append({\" \".join(j):model_rsquares[\" \".join(i)]-model_rsquares[\" \".join(j)]}) for i in model_features_k for j in model_features_k_minus_1 if(len(set(i)-set(j))==1)]\n\t\t# print(\" Partial Dominance \",pd_comp_dom)\n\n\t\treturn (pd,pd_comp_dom)\n\n\tdef model_features_combination(self,columns):\n\t\treturn [list(combinations(columns,i)) for i in range(1,len(columns)+1)]\n\n\tdef McFadden_RSquare(self,columns):\n\t\tcols=columns.copy()\n\t\tcols.append('intercept')\n\t\t# print(\"model columns :\",cols)\n\t\tlog_clf=sm.Logit(self.data[self.target],self.data[cols])\n\t\t# result=log_clf.fit(disp=0,method='powell')\n\t\ttry:\n\t\t\tresult=log_clf.fit(disp=0)\n\t\texcept:\n\t\t\tresult=log_clf.fit(disp=0,method='powell')\n\t\tmcfadden_rsquare=result.prsquared\n\t\treturn mcfadden_rsquare\n\n\tdef Nagelkerke_Rsquare(self,columns):\n\t\tcols=columns.copy()\n\t\tcols.append('intercept')\n\t\tlog_clf=sm.Logit(self.data[self.target],self.data[cols])\n\t\tN=self.data.shape[0]\n\t\t# result=log_clf.fit(disp=0,method='powell')\n\t\ttry:\n\t\t\tresult=log_clf.fit(disp=0)\n\t\texcept:\n\t\t\tresult=log_clf.fit(disp=0,method='powell')\n\t\tllf=result.llf\n\t\tllnull=result.llnull\n\t\tlm=np.exp(llf)\n\t\tlnull=np.exp(llnull)\n\t\tnaglkerke_rsquare=(1-(lnull/lm)**(2/N))/(1-lnull**(2/N))\n\t\treturn naglkerke_rsquare\n\n\tdef Cox_and_Snell_Rsquare(self,columns):\n\t\tcols=columns.copy()\n\t\tcols.append('intercept')\n\t\tlog_clf=sm.Logit(self.data[self.target],self.data[cols])\n\t\tN=self.data.shape[0]\n\t\t# result=log_clf.fit(disp=0,method='powell')\n\t\ttry:\n\t\t\tresult=log_clf.fit(disp=0)\n\t\texcept:\n\t\t\tresult=log_clf.fit(disp=0,method='powell')\n\t\tllf=result.llf\n\t\tllnull=result.llnull\n\t\tlm=np.exp(llf)\n\t\tlnull=np.exp(llnull)\n\t\tcox_and_snell_rsquare=(1-(lnull/lm)**(2/N))\n\t\treturn cox_and_snell_rsquare\n\n\tdef Estrella(self,columns):\n\t\tcols=columns.copy()\n\t\tcols.append('intercept')\n\t\tlog_clf=sm.Logit(self.data[self.target],self.data[cols])\n\t\tN=self.data.shape[0]\n\t\t# result=log_clf.fit(disp=0,method='powell')\n\t\ttry:\n\t\t\tresult=log_clf.fit(disp=0)\n\t\texcept:\n\t\t\tresult=log_clf.fit(disp=0,method='powell')\n\t\tllf=result.llf\n\t\tllnull=result.llnull\n\t\testrella_rsquare=1-((llf/llnull)**(-(2/N)*llnull))\n\t\treturn estrella_rsquare\n\n\tdef Adjusted_McFadden_RSquare(self,columns):\n\t\tlog_clf=sm.Logit(self.data[self.target],self.data[cols])\n\t\t# result=log_clf.fit(disp=0,method='powell')\n\t\ttry:\n\t\t\tresult=log_clf.fit(disp=0)\n\t\texcept:\n\t\t\tresult=log_clf.fit(disp=0,method='powell')\n\t\tllf=result.llf\n\t\tllnull=result.llnull\n\t\tadjusted_mcfadden_rsquare=1-((llf-len(columns))/llnull)\n\t\treturn adjusted_mcfadden_rsquare\n\n\tdef model_stats(self):\n\t\t# columns=list(self.data.columns.values)\n\t\t# columns.remove(self.target)\n\t\t# # print(\"Independent Variables : \",columns)\n\n\t\t## Calculating Incremental R2 for Top_K_Variables \n\t\tcolumns=self.get_top_k()\n\n\t\tmodel_combinations=self.model_features_combination(columns)\n\t\tmodel_rsquares={}\n\t\tif(self.objective==1):\n\t\t\tfor i in tqdm(model_combinations):\n\t\t\t for j in i:\n\t\t\t train_features=list(j)\n\t\t\t lin_reg=LinearRegression()\n\t\t\t lin_reg.fit(self.data[train_features],self.data[self.target])\n\t\t\t r_squared=lin_reg.score(self.data[list(j)],self.data[self.target])\n\t\t\t model_rsquares[\" \".join(train_features)]=r_squared\n\t\telse:\n\t\t\tfor i in tqdm(model_combinations):\n\t\t\t for j in i:\n\t\t\t train_features=list(j)\n\t\t\t if(self.pseudo_r2=='mcfadden'):\n\t\t\t \t# print(\"mcfadden\")\n\t\t\t \tr_squared=self.McFadden_RSquare(train_features)\n\t\t\t # elif(self.pseudo_r2=='adjusted_mcfadden'):\n\t\t\t # \tr_squared=self.Adjusted_McFadden_RSquare(train_features)\n\t\t\t elif(self.pseudo_r2=='nagelkerke'):\n\t\t\t \t# print(\"nagelkerke\")\n\t\t\t \tr_squared=self.Nagelkerke_Rsquare(train_features)\n\t\t\t elif(self.pseudo_r2=='cox_and_snell'):\n\t\t\t \tr_squared=self.Cox_and_Snell_Rsquare(train_features)\n\t\t\t elif(self.pseudo_r2=='estrella'):\n\t\t\t \tr_squared=self.Estrella(train_features)\n\t\t\t model_rsquares[\" \".join(train_features)]=r_squared\n\t\t\n\t\tself.model_rsquares=model_rsquares\n\t\treturn self.model_rsquares\n\n\tdef variable_statistics(self,model_rsquares,columns):\n\t\tstats={}\n\t\tcomplete_dominance_stats={}\n\t\t# print(columns)\n\t\tmodel_combinations=self.model_features_combination(columns)\n\t\tfor k in tqdm(range(len(columns),1,-1)):\n\t\t model_features_k=[i for j in model_combinations for i in j if len(i)==k]\n\t\t model_features_k_minus_1=[i for j in model_combinations for i in j if len(i)==k-1]\n\t\t if(k==len(columns)):\n\t\t stats['conditional_dominance'],complete_dominance_stats['interactional_dominance']=self.conditional_dominance(model_rsquares,model_features_k,model_features_k_minus_1,columns)\n\t\t else:\n\t\t \tstats['partial_dominance_'+str(k)],complete_dominance_stats['partial_dominance_'+str(k)]=self.partial_dominance(model_rsquares,model_features_k,model_features_k_minus_1,columns)\n\n\t\t if(k==2):\n\t\t stats['individual_dominance']=self.individual_dominance(model_rsquares,model_features_k_minus_1,columns)\n\t\t complete_dominance_stats['individual_dominance']=stats['individual_dominance']\n\n\t\tvariable_stats={}\n\t\tfor col in columns:\n\t\t variable_stats[col]={\n\t\t 'conditional_dominance':stats['conditional_dominance'][col],\n\t\t 'individual_dominance':stats['individual_dominance'][col],\n\t\t 'partial_dominance':[np.mean(stats[\"partial_dominance_\"+str(i)][col]) for i in range(len(columns)-1,1,-1)]\n\t\t }\n\n\t\tself.stats=stats\n\t\tself.complete_dominance_stats=complete_dominance_stats\n\t\tself.variable_stats=variable_stats\n\t\treturn self.variable_stats\n\n\tdef dominance_stats(self):\n\t\ttf=pd.DataFrame(self.variable_stats).T\n\t\ttf['Interactional Dominance']=tf['conditional_dominance']\n\t\ttf['Average Partial Dominance']=tf['partial_dominance'].apply(lambda x:np.mean(x))\n\t\ttf['partial_dominance_count']=tf['partial_dominance'].apply(lambda x:len(x))\n\t\ttf['Total Dominance']=(tf['partial_dominance_count']*tf['Average Partial Dominance']+tf['conditional_dominance']+tf['individual_dominance'])/(tf['partial_dominance_count']+2)\n\t\ttf['Percentage Relative Importance']=(tf['Total Dominance']*100)/tf['Total Dominance'].sum()\n\t\ttf=tf[['Interactional Dominance','individual_dominance','Average Partial Dominance','Total Dominance','Percentage Relative Importance']].sort_values(\"Total Dominance\",ascending=False)\n\t\ttf.rename(columns={\"individual_dominance\":\"Individual Dominance\"},inplace=True)\n\t\treturn tf\n\n\n\n\tdef get_top_k(self):\n\t\tcolumns=list(self.data.columns.values)\n\t\tcolumns.remove(self.target)\n\t\t# remove intercept from top_k\n\t\tif(self.objective):\n\t\t\ttop_k_vars=SelectKBest(f_regression, k=self.top_k)\n\t\telse:\n\t\t\tcolumns.remove('intercept')\n\t\t\ttop_k_vars=SelectKBest(chi2, k=self.top_k)\n\t\ttop_k_vars.fit_transform(self.data[columns], self.data[self.target])\n\t\treturn [columns[i] for i in top_k_vars.get_support(indices=True)]\n\n\tdef plot_waterfall_relative_importance(self,incremental_rsquare_df):\n\t\tindex = list(incremental_rsquare_df['Features'].values)\n\t\tdata = {'Percentage Relative Importance': list(incremental_rsquare_df['percentage_incremental_r2'].values)}\n\t\tdf = pd.DataFrame(data=data,index=index)\n\t\t\n\t\tnet = df['Percentage Relative Importance'].sum()\n\t\t# print(\"Net \",net)\n\n\t\tdf['running_total'] = df['Percentage Relative Importance'].cumsum()\n\t\tdf['y_start'] = df['running_total'] - df['Percentage Relative Importance']\n\n\t\tdf['label_pos'] = df['running_total']\n\n\t\tdf_net = pd.DataFrame.from_records([(net, net, 0, net)],\n\t\t\tcolumns=['Percentage Relative Importance', 'running_total', 'y_start', 'label_pos'],index=[\"net\"])\n\t\t\n\t\tdf = df.append(df_net)\n\n\t\tdf['color'] = '#1de9b6'\n\t\tdf.loc[df['Percentage Relative Importance'] == 100, 'color'] = '#29b6f6'\n\t\tdf.loc[df['Percentage Relative Importance'] < 0, 'label_pos'] = df.label_pos - 10000\n\t\tdf[\"bar_label\"] = df[\"Percentage Relative Importance\"].map('{:,.1f}'.format)\n\n\t\tTOOLS = \"reset,save\"\n\t\tsource = ColumnDataSource(df)\n\t\tp = figure(tools=TOOLS, x_range=list(df.index), y_range=(0, net+10),\n\t\t\tplot_width=1000, title = \"Percentage Relative Importance Waterfall\")\n\n\t\tp.segment(x0='index', y0='y_start', x1=\"index\", y1='running_total',\n\t\t\tsource=source, color=\"color\", line_width=35)\n\n\t\tp.grid.grid_line_alpha=0.4\n\t\tp.yaxis[0].formatter = NumeralTickFormatter(format=\"(0 a)\")\n\t\tp.xaxis.axis_label = \"Predictors\"\n\t\tp.yaxis.axis_label = \"Percentage Relative Importance(%)\"\n\t\tp.xaxis.axis_label_text_font_size='12pt'\n\t\tp.yaxis.axis_label_text_font_size='12pt'\n\n\t\tlabels = LabelSet(x='index', y='label_pos', text='bar_label',\n\t\ttext_font_size=\"11pt\", level='glyph',\n\t\tx_offset=-14, y_offset=0, source=source)\n\t\tp.add_layout(labels)\n\t\tp.xaxis.major_label_orientation = -math.pi/4\n\t\tshow(p)\n\n\tdef plot_incremental_rsquare(self):\n\t\tincremental_rsquare_df1=pd.DataFrame()\n\t\tincremental_rsquare_df1['Features']= list(self.incrimental_r2.keys())\n\t\tincremental_rsquare_df1['incremental_r2']=self.incrimental_r2.values()\n\t\tincremental_rsquare_df1.sort_values('incremental_r2',ascending=False,inplace=True)\n\n\t\tincremental_rsquare_df2=pd.DataFrame()\n\t\tincremental_rsquare_df2['Features']=list(self.percentage_incremental_r2.keys())\n\t\tincremental_rsquare_df2['percentage_incremental_r2']=self.percentage_incremental_r2.values()\n\t\tincremental_rsquare_df2.sort_values('percentage_incremental_r2',ascending=False,inplace=True)\n\n\n\t\tincremental_rsquare_df=pd.merge(left=incremental_rsquare_df1,right=incremental_rsquare_df2)\n\t\tincremental_rsquare_df['percentage_incremental_r2']=incremental_rsquare_df['percentage_incremental_r2']*100 \n#Bala changes start \n\t\tif(self.data_format==0):\n\t\t\tiplot(incremental_rsquare_df[['Features','incremental_r2']].set_index(\"Features\").iplot(asFigure=True,kind='bar',title=\"Incremetal \"+(\"Pseudo \" if (self.objective!=1) else \" \")+\"R Squared for Top \"+ str(self.top_k) +\" Variables \",yTitle=\"Incremental R2\",xTitle=\"Estimators\"))\n\t\t\tiplot(incremental_rsquare_df[['Features','percentage_incremental_r2']].iplot(asFigure=True,kind='pie',title=\"Percentage Relative Importance for Top \"+ str(self.top_k) +\" Variables \",values=\"percentage_incremental_r2\",labels=\"Features\"))\n\t\telse:\n\t\t\tiplot(incremental_rsquare_df[['Features','incremental_r2']].set_index(\"Features\").iplot(asFigure=True,kind='bar',title=\"Incremetal \"+(\"Pseudo \" if (self.objective!=1) else \" \")+\"R Squared of \" +\" Variables \",yTitle=\"Incremental R2\",xTitle=\"Estimators\"))\n\t\t\tiplot(incremental_rsquare_df[['Features','percentage_incremental_r2']].iplot(asFigure=True,kind='pie',title=\"Percentage Relative Importance of \" +\" Variables \",values=\"percentage_incremental_r2\",labels=\"Features\"))\n#Bala changes end#Bala changes end\n\t\tself.plot_waterfall_relative_importance(incremental_rsquare_df[['Features','percentage_incremental_r2']])\n\n\tdef predict_general_dominance(self):\n\t\tgeneral_dominance=[]\n\t\tl=list(self.dominance_stats().index)\n\t\tfor index,i in enumerate(l):\n\t\t\tgeneral_dominance.append({\"Predictors\":i,\"Dominating\":l[index+1:]})\n\n\t\treturn pd.DataFrame(general_dominance)[['Predictors','Dominating']]\n\n\tdef predict_conditional_dominance(self):\n\t\t\n\t\tgeneral_dominance=[]\n\t\tl=list(self.dominance_stats().index)\n\t\tfor index,i in enumerate(l):\n\t\t\tgeneral_dominance.append({\"Predictors\":i,\"Dominating\":l[index+1:]})\n\n\t\tconditinal_dominance=[] \n\t\tfor x in general_dominance:\n\t\t\tpredictor=x['Predictors']\n\t\t\tcd=True\n\t\t\tif(len(x['Dominating'])>0):\n\t\t\t\tfor j in x['Dominating']:\n\t\t\t\t\tif((self.variable_stats[predictor]['individual_dominance']<self.variable_stats[j]['individual_dominance']) or (self.variable_stats[predictor]['conditional_dominance']<self.variable_stats[j]['conditional_dominance'])):\n\t\t\t\t\t\tcd=False\n\t\t\t\t\t\tbreak\n\n\t\t\t\t\tif(cd):\n\t\t\t\t\t\tfor index,i in enumerate(self.variable_stats[predictor]['partial_dominance']):\n\t\t\t\t\t\t\tif(i<self.variable_stats[j]['partial_dominance'][index]):\n\t\t\t\t\t\t\t\tcd=False\n\t\t\t\t\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tcd=False\n\n\t\t\tif(cd):\n\t\t\t\tconditinal_dominance.append({\"Predictors\":predictor,\"Conditional Dominance\":True,\"Dominating\":x['Dominating']})\n\t\t\telse:\n\t\t\t\tconditinal_dominance.append({\"Predictors\":predictor,\"Conditional Dominance\":False,\"Dominating\":None})\n\t\t \n\t\treturn pd.DataFrame(conditinal_dominance)[['Predictors','Conditional Dominance','Dominating']]\n\n\tdef predict_complete_dominance(self):\n\t\tconditional_dominance_df=self.predict_conditional_dominance()\n\t\tconditional_dominant_predictors=list(conditional_dominance_df[conditional_dominance_df['Conditional Dominance']==True]['Predictors'].values)\n\t\tpredictors=list(conditional_dominance_df['Predictors'].values)\n\n\t\t# print(conditional_dominant_predictors,predictors)\n\n\t\tcd_df=[]\n\n\t\tcds=self.complete_dominance_stats\n\t\t# print(conditional_dominant_predictors)\n\n\t\tfor i in conditional_dominant_predictors:\n\t\t\t# print(i,conditional_dominance_df)\n\t\t\tdominating=conditional_dominance_df[conditional_dominance_df['Predictors']==i]['Dominating'].values[0]\n\t\t\tcomplete_dominance=True\n\t\t\tfor j in [p for p in list(cds.keys()) if p !='interactional_dominance']:\n\t\t\t\tif(j=='individual_dominance'):\n\t\t\t\t\tif(sum(cds[j][i]>[cds[j][key] for key in dominating])!=len(dominating)):\n\t\t\t\t\t\tcomplete_dominance=False\n\t\t\t\t\t\tbreak\n\t\t\t\telse:\n\t\t\t\t\tsearch_index=[]\n\t\t\t\t\tfor k in dominating:\n\t\t\t\t\t\tif(complete_dominance):\n\t\t\t\t\t\t\tfor key in cds[j][i].keys():\n\t\t\t\t\t\t\t\tl=list(set(predictors)-set(key.split(\" \"))-set([i]))\n\t\t\t\t\t\t\t\t[search_index.append((i,key,c)) for c in l]\n\t\t\t\t\t\n\t\t\t\t\tsearch_index=list(set(search_index))\n\t\t\t\t\t\n\t\t\t\t\tif(complete_dominance):\n\t\t\t\t\t\tfor search in search_index:\n\t\t\t\t\t\t\t# print(search[0],search[1],search[2],cds[j][search[0]][search[1]],cds[j][search[2]][search[1]])\n\t\t\t\t\t\t\tif(cds[j][search[0]][search[1]]<cds[j][search[2]][search[1]]):\n\t\t\t\t\t\t\t\tcomplete_dominance=False\n\t\t\t\t\t\t\t\tbreak\n\n\t\t\tcd_df.append({\"Predictors\":i,\"Dominating\":dominating})\n\t\t \n\t\treturn pd.DataFrame(cd_df)[['Predictors','Dominating']]\n\n\tdef dominance_level(self):\n\t\tgen_dom=self.predict_general_dominance()\n\t\tcondition_dom=self.predict_conditional_dominance()\n\t\tcomp_dom=self.predict_complete_dominance()\n\n\t\tgen_dom.rename(columns={'Dominating':'Generally Dominating'},inplace=True)\n\t\tcondition_dom.drop('Conditional Dominance',inplace=True,axis=1)\n\t\tcondition_dom.rename(columns={'Dominating':'Conditionally Dominating'},inplace=True)\n\t\tcomp_dom.rename(columns={'Dominating':'Completelly Dominating'},inplace=True)\n\n\t\treturn pd.merge(pd.merge(left=gen_dom,right=condition_dom[['Predictors','Conditionally Dominating']],how='left'),comp_dom,how='left').fillna(\"\")\n\n\tdef incremental_rsquare(self):\n\t\t# columns=list(self.data.columns.values)\n\t\t# columns.remove(self.target)\n\n\t\t## Calculating Incremental R2 for Top_K_Variables \n\t\tif(self.data_format==0): #Bala changes\n\t\t\tprint(\"Selecting %s Best Predictors for the Model\" %self.top_k)\n\t\t\tcolumns=self.get_top_k()\n\t\t\tprint(\"Selected Predictors : \",columns)\n\t\t\tprint()\n\t\t\tprint(\"Creating models for %s possible combinations of %s features :\"%((2**len(columns))-1,len(columns)))\n\t\t\tmodel_rsquares=self.model_stats()\n#Bala changes starts\n\t\telse:\n\t\t\tif(self.data_format == 2):\n\t\t\t\tcolumns = list(self.data.columns.values)\n\t\t\t\td = np.sqrt(self.data.values.diagonal()) \n\t\t\t\tcorr_array = ((self.data.values.T/d).T)/d\n\t\t\t\tself.data = pd.DataFrame(data=corr_array,index=columns)\n\t\t\t\tself.data.columns = columns\n\t\t\tmodel_rsquares=self.Dominance_correlation()\n\t\t\tcolumns=list(self.data.columns.values)\n\t\t\tcolumns.remove(self.target)\n#Bala changes ends\n\t\tprint(\"#\"*25,\" Model Training Done!!!!! \", \"#\"*25)\n\t\tprint()\n\t\tprint(\"#\"*25,\" Calculating Variable Dominances \", \"#\"*25)\n\n\t\tvariable_stats=self.variable_statistics(model_rsquares,columns)\n\n\t\tprint(\"#\"*25,\" Variable Dominance Calculation Done!!!!! \", \"#\"*25)\n\t\tprint()\n\n\t\tincrimental_r2={}\n\t\tfor col in columns:\n\t\t l=[variable_stats[col]['individual_dominance'],variable_stats[col]['conditional_dominance']]\n\t\t l.extend(variable_stats[col]['partial_dominance'])\n\t\t incrimental_r2[col]=np.mean(l)\n\t\t \n\t\tself.incrimental_r2=incrimental_r2\n\t\tself.percentage_incremental_r2={col:incrimental_r2[col]/np.sum(list(incrimental_r2.values())) for col in columns}\n\t\t\n\t\treturn incrimental_r2\n\n\tdef complete_model_rsquare(self):\n\t\tif(self.data_format==0): #Bala changes\n\t\t\tprint(\"Selecting %s Best Predictors for the Model\" %self.top_k)\n\t\t\tcolumns=self.get_top_k()\n\t\t\tprint(\"Selected Predictors : \",columns)\n\t\t\tprint()\n\n\t\t\tif(self.objective==1):\n\t\t\t\tprint(\"*\"*20,\" R-Squared of Complete Model : \",\"*\"*20)\n\t\t\t\tlin_reg=LinearRegression()\n\t\t\t\tlin_reg.fit(self.data[columns],self.data[self.target])\n\t\t\t\tr_squared=lin_reg.score(self.data[columns],self.data[self.target])\n\t\t\t\tprint(\"R Squared : %s\" %(r_squared))\n\t\t\t\tprint()\n\t\t\telse:\n\t\t\t\tprint(\"*\"*20,\" Pseudo R-Squared of Complete Model : \",\"*\"*20)\n\t\t\t\tprint()\n\t\t\t\t\n\t\t\t\tif(self.pseudo_r2=='mcfadden'):\n\t\t\t\t\tprint(\"MacFadden's R-Squared : %s \"%(self.McFadden_RSquare(columns)))\n\t\t\t\telif(pseudo_r2=='nagelkerke'):\n\t\t\t\t\tprint(\"Nagelkerke R-Squared : %s \"%(self.Nagelkerke_Rsquare(columns)))\n\t\t\t\telif(pseudo_r2=='cox_and_snell'):\n\t\t\t\t\tprint(\"Cox and Snell R-Squared : %s \"%(self.Cox_and_Snell_Rsquare(columns)))\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Estrella R-Squared : %s \"%(self.Estrella(columns)))\n\t\t\t\tprint()\n#Bala changes start\n\t\telse:\n\t\t\tif(self.data_format == 2):\n\t\t\t\tcolumns = list(self.data.columns.values)\n\t\t\t\td = np.sqrt(self.data.values.diagonal()) \n\t\t\t\tcorr_array = ((self.data.values.T/d).T)/d\n\t\t\t\tself.data = pd.DataFrame(data=corr_array,index=columns)\n\t\t\t\tself.data.columns = columns\n\t\t\t\tprint()\n\t\t\tcolumns=list(self.data.columns.values)\n\t\t\tcolumns.remove(self.target)\n\t\t\tcorr_all_matrix=self.data.loc[columns,[self.target]]\n\t\t\tcorr_pred_matrix = self.data.loc[columns,columns]\n\t\t\tcorr_pred_matrix_inverse = pd.DataFrame(np.linalg.pinv(corr_pred_matrix.values), corr_pred_matrix.columns, corr_pred_matrix.index)\n\t\t\tbeta = corr_pred_matrix_inverse.dot(corr_all_matrix)\n\t\t\tcorr_all_matrix_transpose = corr_all_matrix.transpose()\n\t\t\tr_squared = corr_all_matrix_transpose.dot(beta)\n\t\t\tprint(\"R Squared : %s\" %(r_squared.iloc[0,0]))\n\t\t\tprint()\n#Bala changes ends\n\n#Bala changes starts\n\tdef Dominance_correlation(self):\n ## Calculating Incremental R2 from Correlation Matrix\n\t\tcolumns=list(self.data.columns.values)\n\t\tcolumns.remove(self.target)\n\t\tprint(\"Predictors : \",columns)\n\t\tprint()\n\n\t\tprint(\"Calculating R2 for %s possible combinations of %s features :\"%((2**len(columns))-1,len(columns)))\n\t\tmodel_combinations=self.model_features_combination(columns)\n\t\tmodel_rsquares={}\n\t\tfor i in tqdm(model_combinations):\n\t\t\tfor j in i:\n\t\t\t\tmodel_combinations = list(j)\n\t\t\t\tcorr_all_matrix = self.data.loc[model_combinations,[self.target]]\n\t\t\t\tcorr_pred_matrix = self.data.loc[model_combinations,model_combinations]\n\t\t\t\tcorr_pred_matrix_inverse = pd.DataFrame(np.linalg.pinv(corr_pred_matrix.values), corr_pred_matrix.columns, corr_pred_matrix.index)\n\t\t\t\tbeta = corr_pred_matrix_inverse.dot(corr_all_matrix)\n\t\t\t\tcorr_all_matrix_transpose = corr_all_matrix.transpose()\n\t\t\t\tr_square = corr_all_matrix_transpose.dot(beta)\n\t\t\t\tmodel_rsquares[\" \".join(model_combinations)]=r_square.iloc[0,0]\n\t\tself.model_rsquares=model_rsquares\n\t\treturn self.model_rsquares\n#Bala changes ends\n\nclass Dominance_Datasets:\n\t\"\"\"docstring for Dominance_Datasets\"\"\"\n\t\n\t@classmethod\n\tdef get_breast_cancer(cls):\n\t\tprint(\"\"\"The copy of UCI ML Breast Cancer Wisconsin (Diagnostic) dataset is downloaded from: https://goo.gl/U2Uwz2\"\"\")\n\t\tprint(\"\"\"Internally using load_breast_cancer function from sklearn.datasets \"\"\")\n\t\tbreast_cancer_data=pd.DataFrame(data=load_breast_cancer()['data'],columns=load_breast_cancer()['feature_names'])\n\t\tbreast_cancer_data['target']=load_breast_cancer()['target']\n\t\ttarget_dict=dict({j for i,j in zip(load_breast_cancer()['target_names'],enumerate(load_breast_cancer()['target_names']))})\n\t\tbreast_cancer_data['target_names']=breast_cancer_data['target'].map(target_dict)\n\t\treturn breast_cancer_data.iloc[:,:-1]\n\t\n\t@classmethod\n\tdef get_boston(cls):\n\t\tprint(\"\"\"The copy of Boston Housing Dataset is downloaded from: https://www.cs.toronto.edu/~delve/data/boston/bostonDetail.html\"\"\")\n\t\tprint(\"\"\"Internally using load_boston function from sklearn.datasets \"\"\")\n\t\tboston_data=pd.DataFrame(data=load_boston()['data'],columns=load_boston()['feature_names'])\n\t\tboston_data['House_Price']=load_boston()['target']\n\t\treturn boston_data\n\n\tdef __init__(self):\n\t\tprint(\"Datasets for Dominance Analysis\")\n\t\t\n\n"
]
| [
[
"pandas.merge",
"sklearn.datasets.load_breast_cancer",
"pandas.DataFrame",
"sklearn.feature_selection.SelectKBest",
"numpy.linalg.pinv",
"numpy.mean",
"sklearn.linear_model.LinearRegression",
"sklearn.datasets.load_boston",
"pandas.DataFrame.from_records",
"numpy.exp"
]
]
|
Kefeng91/Forlab | [
"070c96a20ac4d3d41c41cbf4b9a198284c5cea50"
]
| [
"utils/view_kde.py"
]
| [
"# -*- coding: utf-8 -*-\n\n\"\"\"\nAuthor: Keurfon Luu <[email protected]>\nLicense: MIT\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nif __name__ == \"__main__\":\n # Parameters\n fkind = \"float32\"\n \n # Initialize figure\n fig = plt.figure(figsize = (10, 5), facecolor = \"white\")\n fig.patch.set_alpha(0.)\n ax1 = fig.add_subplot(1, 2, 1)\n ax2 = fig.add_subplot(1, 2, 2)\n ax1.patch.set_alpha(1.)\n ax2.patch.set_alpha(1.)\n \n # 1D Kernel Density Estimation\n data1d = np.fromfile(\"../examples/rand/data1d.bin\", dtype = fkind)\n data1d_kde = np.fromfile(\"../examples/rand/data1d_kde.bin\", dtype = fkind)\n xi = np.fromfile(\"../examples/rand/data1d_kde_xaxis.bin\", dtype = fkind)\n \n n = 1500\n nx = len(xi)\n\n ax1.hist(data1d, 30, normed = True, color = \"black\", alpha = 0.8)\n ax1.plot(xi, data1d_kde, color = \"red\", linewidth = 2)\n ax1.set_title(\"1D KDE\")\n ax1.set_xlabel(\"X\")\n ax1.set_ylabel(\"PDF\")\n ax1.set_xlim(np.min(xi), np.max(xi))\n ax1.grid(True, linestyle = \":\")\n \n # 2D Kernel Density Estimation\n data2d = np.fromfile(\"../examples/rand/data2d.bin\", dtype = fkind)\n data2d_kde = np.fromfile(\"../examples/rand/data2d_kde.bin\", dtype = fkind)\n xi = np.fromfile(\"../examples/rand/data2d_kde_xaxis.bin\", dtype = fkind)\n yi = np.fromfile(\"../examples/rand/data2d_kde_yaxis.bin\", dtype = fkind)\n \n n = 750\n nx, ny = len(xi), len(yi)\n data2d = np.reshape(data2d, (n, 2), order = \"F\")\n data2d_kde = np.reshape(data2d_kde, (nx, ny), order = \"F\")\n \n ax2.contour(xi, yi, data2d_kde.T, 30)\n ax2.plot(data2d[:,0], data2d[:,1], color = \"black\", linestyle = \"none\", marker = \"o\", markersize = 6, alpha = 0.33)\n ax2.set_title(\"2D KDE\")\n ax2.set_xlabel(\"X\")\n ax2.set_ylabel(\"Y\")\n ax2.set_xlim(np.min(xi), np.max(xi))\n ax2.set_ylim(np.min(yi), np.max(yi))\n ax2.grid(True, linestyle = \":\")\n \n fig.tight_layout()"
]
| [
[
"numpy.fromfile",
"numpy.min",
"numpy.reshape",
"numpy.max",
"matplotlib.pyplot.figure"
]
]
|
jenzenho/pyMARS | [
"3612580fe58c69b441211eaea18baa9dc1045751"
]
| [
"pymars/drgep.py"
]
| [
"import networkx as nx\nimport numpy as np\nimport h5py\nimport os, sys, argparse\nimport cantera as ct\nimport soln2ck\nimport soln2cti\nfrom readin_initial_conditions import readin_conditions\nfrom simulation import Simulation\nimport helper\nfrom create_trimmed_model import trim\nfrom numpy import genfromtxt\nimport math\nfrom dijkstra import ss_dijkstra_path_length_modified\n\n\ndef make_dic_drgep(solution_object, total_edge_data, target_species):\n\n \"\"\" \n Makes the dictionary of overall interaction coefficients for DRGEP by building a graph and searching it as explained in DRGEP\n\n Parameters\n ----------\n\n solution_object: the Cantera soluton object that is being reduced\n target_species: an array of target species for the reduction as specified by the user\n total_edge_data: a dictionary with keys of initial conditions and values of dictionarys that hold information for caculating DICs at each timestep.\n *the subdictionaries have the timestep as their keys and their values hold an array of numberator and denominator information for calculating DICs.\n\n Returns\n -------\n\n A dictionary with keys of species and values of that species OIC\n \n \"\"\"\n\n # Initalize solution and components\n solution = solution_object\n species_objects = solution.species()\n reaction_objects = solution.reactions()\n \n # Use the networkx library to create a weighted graph of all of the species and their dependencies on each other.\n graph = nx.DiGraph()\n\n max_dic = {} # Dictionary holding the maximum values for the iteration\n\n # Calculate edge weights based on list received from get_rate_data and use them to create a graph\n for ic in total_edge_data.keys(): # For each initial condition\n for species in species_objects: # Make graph\n graph.add_node(species.name)\n # Timestep\n for tstep in total_edge_data[ic].keys(): # Make a graph at each timestep\n # DRGEP calculations of direct interaction coeffients are done in the total_edge_data function.\n numerator = total_edge_data[ic][tstep][1]\n denominator = total_edge_data[ic][tstep][0]\n for edge in numerator: # For each edge, determine its weight amnd add it to the graph\n try:\n edge_name = edge.split('_', 1)\n species_a_name = edge_name[0]\n species_b_name = edge_name[1]\n # DRGEP weight between two species\n if denominator[species_a_name] != 0:\n weight = abs(\n float(numerator[edge])/float(denominator[species_a_name]))\n if graph.has_edge(species_a_name, species_b_name):\n old_weight = graph[species_a_name][species_b_name]['weight']\n if weight > old_weight and weight <= 1:\n graph.add_weighted_edges_from(\n [(species_a_name, species_b_name, weight)])\n elif weight > 1:\n print(\n \"Error. Edge weights should not be greater than one.\")\n exit()\n elif weight <= 1:\n graph.add_weighted_edges_from(\n [(species_a_name, species_b_name, weight)])\n elif weight > 1:\n print(\n \"Error. Edge weights should not be greater than one.\")\n exit()\n except IndexError:\n print(edge)\n continue\n\n # Search the graph for overall interaction coefficents and add them to max_dic if they belong\n dic = graph_search_drgep(graph, target_species) # Search graph for max values to each species based on targets\n for sp in dic: # Add to max dictionary if it is new or greater than the value already there.\n if sp not in max_dic:\n max_dic[sp] = dic[sp]\n elif dic[sp] > max_dic[sp]:\n max_dic[sp] = dic[sp]\n graph.clear() # Reset graph\n return max_dic\n\n\ndef trim_drgep(max_dic, solution_object, threshold_value, retained_species, done):\n \n \"\"\"\n Determines what species should be excluded from the reduced model based on their OICs compared to the threshold value.\n\n Parameters\n ----------\n max_dic: Dictionary of OICs for all species\n solution_object: The solution being reduced\n threshold_value: User specified threshold value\n keeper_list: Speicies that should always be kept\n done: Determines wether or not the reduction is complete\n\n Returns\n -------\n An array of species that should be excluded from the original model at this threshold level\n \n \"\"\"\n \n core_species = []\n species_objects = solution_object.species()\n\n for sp in retained_species:\n core_species.append(sp)\n \n # Take all species that are over the threshold value and add them to essential species.\n essential_species = []\n for sp in species_objects:\n if sp.name in max_dic:\n if max_dic[sp.name] > threshold_value and sp not in essential_species:\n essential_species.append(sp)\n done[0] = True\n for sp in species_objects: # If any more can be taken out, we are not done yet.\n if sp.name in max_dic:\n if max_dic[sp.name] > threshold_value:\n done[0] = False\n\n for sp in essential_species:\n if sp not in core_species:\n core_species.append(sp.name)\n\n exclusion_list = []\n\n for species in solution_object.species():\n # If its not one of our species we must keep, add it to the list of species to be trimmed.\n if species.name not in core_species: \n exclusion_list.append(species.name)\n\n return exclusion_list\n\n\ndef run_drgep(solution_object, conditions_file, error_limit, target_species, retained_species, model_file, final_error):\n \n\t\"\"\"\"\n\tThis is the MAIN top level function for running DRGEP\n\n\tParameters\n\t----------\n\n\tsolution_object: A Cantera object of the solution to be reduced\n\tconditions_file: A file holding the initial conditions for the simulation\n\terror_limit: The maximum error allowed for the reduced model\n\ttarget_species: An array of the target species for reduction\n\tretained_species: An array of species that should not be removed from the model\n\tmodel_file: The path to the file holding the original model\n\tfinal_error: A singleton holding the final error percentage\n\n\tReturns\n\t-------\n\n\tWrites reduced Cantera file and returns reduced Catnera solution object\n \n\t\"\"\"\n\n\t# Set up variables\n\tif len(target_species) == 0: # If the target species are not specified, puke and die.\n\t\tprint(\"Please specify a target species.\")\n\t\texit()\n\tdone = [] # Singleton to hold wether or not any more species can be cut from the simulation.\n\tdone.append(False)\n\tthreshold = .1 # Starting threshold value\n\tthreshold_i = .1\n\tn = 1\n\terror = [10.0] # Singleton to hold the error value of the previously ran simulation.\n\n\t# Check to make sure that conditions exist\n\tif conditions_file:\n\t\tconditions_array = readin_conditions(str(conditions_file))\n\telif not conditions_file:\n\t\tprint(\"Conditions file not found\")\n\t\texit()\n\n\tsim_array = helper.setup_simulations(conditions_array,solution_object) # Turn conditions array into unran simulation objects for the original solution\n\tignition_delay_detailed = helper.simulate(sim_array) # Run simulations and process results\n\n\trate_edge_data = get_rates(sim_array,solution_object) # Get edge weight calculation data.\n\tmax_dic = make_dic_drgep(solution_object, rate_edge_data, target_species) # Make a dictionary of overall interaction coefficients.\n\n\t# Trim the solution at that treshold and find the error.\n\tprint(\"Testing for starting threshold value\")\n\tdrgep_loop_control(\n\t\tsolution_object, target_species, retained_species, model_file, error, threshold, done, max_dic, ignition_delay_detailed, conditions_array)\n\t\n\twhile error[0] != 0 and threshold_i > .001: # While the error for trimming with that threshold value is greater than allowed.\n\t\tthreshold = threshold / 10 # Reduce the starting threshold value and try again.\n\t\tthreshold_i = threshold_i / 10\n\t\tn = n + 1\n\t\tdrgep_loop_control(\n\t\t\tsolution_object, target_species, retained_species, model_file, error, threshold, done, max_dic, ignition_delay_detailed, conditions_array)\n\t\tif error[0] <= .02:\n\t\t\terror[0] = 0\n\n\tprint(\"Starting with a threshold value of \" + str(threshold))\n\tsol_new = solution_object\n\tfinal_error[0] = 0 # An integer representing the error introduced in the past simulation.\n\tdone[0] = False\n\n\twhile not done[0] and error[0] < error_limit: # Run the simulation until nothing else can be cut.\n\t\t# Trim at this threshold value and calculate error.\n\t\tsol_new = drgep_loop_control(\n\t\t\tsolution_object, target_species, retained_species, model_file, error, threshold, done, max_dic, ignition_delay_detailed, conditions_array)\n\t\tif error_limit > error[0]: # If a new max species cut without exceeding what is allowed is reached, save that threshold.\n\t\t\tmax_t = threshold\n #if (final_error[0] == error[0]): #If error wasn't increased, increase the threshold at a higher rate.\n\t\t #threshold = threshold + (threshold_i * 4)\n\t\t\tfinal_error[0] = error[0]\n\t\t #if (threshold >= .01):\n #threshold_i = .01\n\t\t\tthreshold = threshold + threshold_i\n\t\t\tthreshold = round(threshold, n)\n\n\tprint(\"\\nGreatest result: \")\n\tsol_new = drgep_loop_control(\n\t\tsolution_object, target_species, retained_species, model_file, error, max_t, done, max_dic, ignition_delay_detailed, conditions_array)\n\t\n\treturn sol_new\n\n\ndef drgep_loop_control(solution_object, target_species, retained_species, model_file, stored_error, threshold, done, max_dic, ignition_delay_detailed, conditions_array):\n\n \"\"\" \n This function handles the reduction, simulation, and comparision for a single threshold value.\n\n Parameters\n ----------\n\n solution_object: object being reduced\n target_species: An array of the target species for reduction\n retained_species: An array of species that should not be removed from the model\n model_file: The path to the file holding the original model\n stored_error: past error\n threshold: current threshold value\n done: are we done reducing yet? Boolean\n max_dic: OIC dictionary for DRGEP\n ignition_delay_detailed: ignition delay of detailed model\n conditions_array: array holding information about initial conditions\n\n Returns\n -------\n\n Returns the reduced solution object for this threshold and updates error value\n \n \"\"\" \n\n # Run detailed mechanism and retain initial conditions\n species_retained = []\n printout = ''\n print('Threshold Species in Mech Error')\n\n # Run DRGEP and create new reduced solution\n exclusion_list = trim_drgep(max_dic, solution_object, threshold, retained_species, done) # Find out what to cut from the model\n new_solution_objects = trim(solution_object, exclusion_list, model_file) # Cut the exclusion list from the model.\n species_retained.append(len(new_solution_objects[1].species()))\n\n # Simulated reduced solution\n new_sim = helper.setup_simulations(conditions_array,new_solution_objects[1]) # Create simulation objects for reduced model for all conditions\n ignition_delay_reduced = helper.simulate(new_sim) # Run simulations and process results\n\n if ignition_delay_detailed.all() == 0: # Ensure that ignition occured\n print(\"Original model did not ignite. Check initial conditions.\")\n exit()\n\n # Calculate and print error.\n error = (abs(ignition_delay_reduced-ignition_delay_detailed)/ignition_delay_detailed)*100 # Calculate error\n printout += str(threshold) + ' ' + str(len(new_solution_objects[1].species())) + ' '+ str(round(np.max(error), 2)) +'%' + '\\n'\n print(printout)\n stored_error[0] = round(np.max(error), 2)\n\n # Return new model\n new_solution_objects = new_solution_objects[1]\n return new_solution_objects\n\n\ndef get_rates(sim_array, solution_object):\n\n \"\"\" \n This function calculates values to be used in the calculation of Direct Interaction Coefficients\n\n Parameters\n ----------\n \n sim_array: Array of simulated simulation objects\n solution_object: Cantera object of the solution being reduced\n\n Returns\n -------\n\n Returns a dictionary for calculating interaction coefficients as described in the make_dic_drgep function comments\n\n \"\"\"\n\n # Initialize solution\n old_solution = solution_object\n # Iterate through all initial conditions\n total_edge_data = {}\n for ic in sim_array:\n ic_edge_data = {}\n for tstep in ic.sample_points: # Iterate through all timesteps\n temp = tstep[0] # Set up variables\n pressure = tstep[1]\n mass_fractions = np.array(tstep[2])\n\n # Set up solution at current timestep\n new_solution = old_solution\n new_solution.TPY = temp, pressure, mass_fractions\n new_reaction_production_rates = new_solution.net_rates_of_progress\n new_species_prod_rates = new_solution.net_production_rates\n\n denom = {}\n numerator = {}\n for spc in new_solution.species():\n denom[spc.name] = []\n denom[spc.name].append(0)\n denom[spc.name].append(0)\n\n # Calculate direct interaction coefficients as specified by the DRGEP method\n for i, reac in enumerate(new_solution.reactions()): # For all reactions\n reac_prod_rate = float(new_reaction_production_rates[i])\n reactants = reac.reactants\n products = reac.products\n all_species = reac.reactants\n all_species.update(reac.products)\n\n if reac_prod_rate != 0:\n if reac_prod_rate > 0:\n for species in products: # Add to denominator for all of the species in products\n denom[species][1] += abs(float(reac_prod_rate * products[species]))\n for species_b in all_species:\n if species_b != species:\n partial_name = species + '_' + species_b\n if partial_name in numerator: # Add to numerator for all species pairs\n numerator[partial_name] += float(reac_prod_rate * products[species])\n else:\n numerator[partial_name] = float(reac_prod_rate * products[species])\n\n for species in reactants: # For all reactants subtract instead of add\n denom[species][0] += abs(float(reac_prod_rate * reactants[species]))\n for species_b in all_species:\n if species_b != species:\n partial_name = species + '_' + species_b\n if partial_name in numerator:\n numerator[partial_name] += float(-reac_prod_rate * reactants[species])\n else:\n numerator[partial_name] = float(-reac_prod_rate * reactants[species])\n\n if reac_prod_rate < 0: # Same as above but for negative.\n for species in products:\n denom[species][0] += abs(float(reac_prod_rate * products[species]))\n for species_b in all_species:\n if species_b != species:\n partial_name = species + '_' + species_b\n if partial_name in numerator:\n numerator[partial_name] += float(reac_prod_rate * products[species])\n else:\n numerator[partial_name] = float(reac_prod_rate * products[species])\n\n for species in reactants:\n denom[species][1] += abs(float(reac_prod_rate * reactants[species]))\n for species_b in all_species:\n if species_b != species:\n partial_name = species + '_' + species_b\n if partial_name in numerator:\n numerator[partial_name] += float(-reac_prod_rate * reactants[species])\n else:\n numerator[partial_name] = float(-reac_prod_rate * reactants[species])\n\n for species in new_solution.species(): # Use greater value as denominator\n if abs(denom[species.name][0]) > abs(denom[species.name][1]):\n denom[species.name] = abs(denom[species.name][0])\n else:\n denom[species.name] = abs(denom[species.name][1])\n\n for name in numerator: # Use absolute value of numerator\n numerator[name] = abs(numerator[name])\n ic_edge_data[temp] = [denom, numerator] # Add to ic data\n total_edge_data[ic] = ic_edge_data # Add to information to be used to make the graph\n\n return total_edge_data\n\n\ndef graph_search_drgep(nx_graph, target_species):\n\n \"\"\"\n This function searches the graph to generate a dictionary of the greatest paths to all species from one of the targets.\n \n Parameters\n ----------\n nx_graph : obj\n networkx graph object of solution\n target_species : list\n List of target species to search from\n\n Returns\n -------\n max_dic : dictionary\n Values of the greatest possible path to each species from one of the targets on this graph keyed by species name.\n \n \"\"\"\n\n max_dic = {} # A dictionary holding the maximum path to each species.\n for target in target_species:\n dic = ss_dijkstra_path_length_modified(nx_graph, target) # Get dictionary of each values maximum path\n for sp in dic: # If the species are not in the max dictionary or the new value for that species is greater than the one in the max dictionary, add it to the max dictionary.\n if sp not in max_dic:\n max_dic[sp] = dic[sp]\n elif max_dic[sp] < dic[sp]:\n max_dic[sp] = dic[sp]\n return max_dic\n"
]
| [
[
"numpy.max",
"numpy.array"
]
]
|
resuly/Traffic-3DResnets | [
"cb48c6b7a4921d8593368c262c0d3c0406a6cc32"
]
| [
"main/synthesize_results.py"
]
| [
"\"\"\"Aggregates results from the metrics_eval_best_weights.json in a parent folder\"\"\"\n\nimport argparse\nimport json\nimport os\nworking_path = os.path.abspath(os.path.dirname(__file__))\n\nfrom tabulate import tabulate\nimport pandas as pd\n\nimport utils\nimport model.net as net\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--parent_dir', default='experiments',\n help='Directory containing results of experiments')\n\n\ndef aggregate_metrics(parent_dir, metrics):\n \"\"\"Aggregate the metrics of all experiments in folder `parent_dir`.\n\n Assumes that `parent_dir` contains multiple experiments, with their results stored in\n `parent_dir/subdir/metrics_dev.json`\n\n Args:\n parent_dir: (string) path to directory containing experiments results\n metrics: (dict) subdir -> {'accuracy': ..., ...}\n \"\"\"\n \n # Get the metrics for the folder if it has results from an experiment\n metrics_file = os.path.join(parent_dir, 'metrics_test_best_weights.json')\n if os.path.isfile(metrics_file):\n # Get the number of params\n model_name = metrics_file.split('\\\\')[-2]\n params = utils.Params(os.path.join(parent_dir, 'params.json'))\n model = getattr(net, model_name)(params).cuda()\n pytorch_total_params = sum(p.numel() for p in model.parameters())\n # for trainable params only\n # pytorch_total_params = sum(p.numel() for p in model.parameters() if p.requires_grad)\n\n # logfile - findout the training time\n df = pd.read_csv(os.path.join(parent_dir, '_train.log'), header=None)\n df[0] = pd.to_datetime(df[0])\n traintime = (df.iloc[-1, 0] - df.iloc[0, 0]).total_seconds()\n\n headname = parent_dir.split('\\\\')[-2] + ' - ' + parent_dir.split('\\\\')[-1]\n \n with open(metrics_file, 'r') as f:\n best_json = json.load(f)\n del(best_json['loss'])\n best_json['time(s)'] = traintime\n best_json['params'] = pytorch_total_params\n metrics[headname] = best_json\n\n # Check every subdirectory of parent_dir\n for subdir in os.listdir(parent_dir):\n if not os.path.isdir(os.path.join(parent_dir, subdir)):\n continue\n else:\n aggregate_metrics(os.path.join(parent_dir, subdir), metrics)\n\n\ndef metrics_to_table(metrics):\n # Get the headers from the first subdir. Assumes everything has the same metrics\n headers = metrics[list(metrics.keys())[0]].keys()\n table = [[subdir] + [values[h] for h in headers] for subdir, values in metrics.items()]\n res = tabulate(table, headers, tablefmt='pipe')\n\n return res\n\nif __name__ == \"__main__\":\n args = parser.parse_args()\n # args.parent_dir = os.path.join(working_path, args.parent_dir)\n \n # Aggregate metrics from args.parent_dir directory\n metrics = dict()\n aggregate_metrics(args.parent_dir, metrics)\n table = metrics_to_table(metrics)\n\n # Display the table to terminal\n print(table)\n\n # Save results in parent_dir/results.md\n save_file = os.path.join(args.parent_dir, \"results.md\")\n with open(save_file, 'w') as f:\n f.write(table)\n\n # python synthesize_results.py --parent_dir experiments_4_4_4"
]
| [
[
"pandas.to_datetime"
]
]
|
rmit-ir/AnswerPassageQuality | [
"83c2d6c6467dfa71e887bc6f4a893d6d594fc3b5"
]
| [
"models/AnswerPassages.py"
]
| [
"from __future__ import print_function\n\nimport argparse\nimport collections\nimport itertools\nimport json\nimport krovetzstemmer\nimport logging\nimport math\nimport string\n\nimport fastText\nimport numpy as np\nimport scipy.stats.mstats\nimport scipy.special\nimport sklearn\n\nfrom smart_open import smart_open\nfrom ortools.linear_solver import pywraplp\nfrom tqdm import tqdm\n\n\n# Tokenizer\n#\nPUNCTUATION_REMOVER = string.maketrans(string.punctuation, ' ' * len(string.punctuation))\n\n\ndef to_terms(text):\n return text.encode('utf8', errors='replace').translate(PUNCTUATION_REMOVER).split()\n\n\nclass Tokenizer(object):\n def __init__(self, stemmer=None, stoplist=None):\n self.stemmer = stemmer if stemmer else krovetzstemmer.Stemmer()\n self.stoplist = stoplist if stoplist else set()\n\n def __call__(self, text):\n return [self.stemmer(term) for term in to_terms(text) if term not in self.stoplist]\n\n\n# Feature extraction\n#\nclass Pipeline():\n \"\"\"Feature extraction pipeline\"\"\"\n\n def __init__(self):\n self.jobs = []\n\n def add(self, features, adaptor=None):\n \"\"\"Add a group of features into pipeline, optionally under adapted input\n\n Args:\n features: one or a list of callable feature objects\n adaptor: callable object to transform input data\n \"\"\"\n if not isinstance(features, (tuple, list)):\n features = [features]\n self.jobs.append({'adaptor': adaptor, 'extractors': features})\n\n def extract(self, item):\n \"\"\"Execute pipeline to extract features from item\n\n Args:\n item: input data\n \"\"\"\n vector = []\n for job in self.jobs:\n input_ = item if job['adaptor'] is None else job['adaptor'](item)\n for extractor in job['extractors']:\n vector.append(extractor(input_))\n return vector\n\n\n# Quality features\n#\ndef get_bigrams(sentences):\n for sentence in sentences:\n for bigram in itertools.izip(sentence, sentence[1:]):\n yield bigram\n\n\ndef CQAOverlap(doc):\n model, sentences = doc\n gold = set([b for b in get_bigrams(model['answers'])])\n system = set([b for b in get_bigrams(sentences)])\n return float(len(gold & system)) / len(gold)\n\n\ndef NumSentences(doc):\n _, sentences = doc\n return len(sentences)\n\n\ndef QueryOverlap(doc):\n model, terms = doc\n query = set(model['query'])\n return sum(int(t in query) for t in terms)\n\n\ndef AvgWordWeight(doc):\n model, terms = doc\n return float(sum(model['weights'](t) for t in terms)) / len(terms) if terms else 0\n\n\ndef AvgTermLen(doc):\n \"\"\"Average length of visible term on the page\"\"\"\n _, terms = doc\n return float(sum(len(t) for t in terms)) / len(terms) if terms else 0\n\n\ndef Entropy(doc):\n \"\"\"Entropy of the page content\"\"\"\n _, terms = doc\n N = len(terms)\n tf = collections.Counter(terms)\n return math.log(N) - float(sum(n * math.log(n) for n in tf.values())) / N if N > 0 else 0\n\n\nclass FracStops():\n \"\"\"Stopword/non-stopword ratio\"\"\"\n def __init__(self, stoplist):\n self.stoplist = stoplist\n\n def __call__(self, doc):\n _, terms = doc\n return float(sum(term in self.stoplist for term in terms)) / len(terms) if terms else 0\n\n\nclass StopCover():\n \"\"\"Fraction of terms in the stopword list that appear on the page\"\"\"\n def __init__(self, stoplist):\n self.stoplist = stoplist\n\n def __call__(self, doc):\n _, terms = doc\n if self.stoplist:\n return float(sum(sw in terms for sw in self.stoplist)) / len(self.stoplist)\n else:\n return 0\n\n\ndef load_freqstats(iterable):\n tf, df = {}, {}\n for line in iterable:\n term, tf_value, df_value = line.split()\n tf[term] = int(tf_value)\n df[term] = int(df_value)\n N, D = tf.pop(\"TOTAL\"), df.pop(\"TOTAL\")\n return N, D, tf, df\n\n\ndef load_idf(iterable):\n idf = {}\n for line in iterable:\n term, value = line.split()\n idf[term] = float(value)\n return idf\n\n\ndef load_dr_data(iterable):\n res = {}\n for line in iterable:\n payload = json.loads(line)\n bag = {}\n for docno in payload['passages'].keys():\n passage = payload['passages'][docno]\n score = payload['psg_scores'][docno]\n\n # FIXME: quick and dirty\n sentences = [p + ' .' for p in passage.split(' . ')]\n tokenized_sentences = [s.split() for s in sentences]\n bag[docno] = {'passage': tokenized_sentences, 'passage_text': sentences, 'objective': score}\n res[payload['qid']] = bag\n return res\n\n\n# Answer relevance models\n#\ndef UniformRelevance(n):\n return np.ones(n) / n\n\n\ndef GradedRelevance(n):\n return 1 / np.log(np.arange(1, n + 1) + 1)\n\n\n# Term relevance estimates\n#\nclass Thingy(sklearn.base.BaseEstimator):\n pass\n\n\nclass QLEstimator(Thingy):\n \"\"\"Estimating p(t|A) using query likelihood\"\"\"\n def __init__(self, N, ctf, mu):\n assert mu >= 0\n\n self.N = N\n self.ctf = ctf\n self.mu = mu\n\n def get_estimate(self, doc, tf):\n dl = sum(tf.values())\n\n def _zero_estimate(t):\n return 0\n def _estimate(t):\n if t not in tf:\n return 0\n p_background = float(self.ctf.get(t, 0)) / self.N if self.N > 0 else 0\n return float(tf[t] + self.mu * p_background) / (dl + self.mu)\n\n return _estimate if dl + self.mu > 0 else _zero_estimate\n\n\nclass BM25Estimator(Thingy):\n \"\"\"Estimating p(t|A) using BM25\"\"\"\n def __init__(self, D, df, k1, b, avg_dl):\n self.D = D\n self.df = df\n self.k1 = k1\n self.b = b\n self.avg_dl = avg_dl\n\n def get_estimate(self, doc, tf):\n dl = sum(tf.values())\n\n def _estimate(t):\n res = 0\n if t in tf and t in self.df:\n freq = tf[t]\n idf = math.log(float(self.D) / self.df[t])\n res = idf * ((freq * (self.k1 + 1)) /\n (freq + self.k1 * (1 - self.b + self.b * (dl / self.avg_dl))))\n return res\n return _estimate\n\n\nclass WordEmbeddingEstimator(Thingy):\n \"\"\"Estimating p(t|A) using word embeddings\"\"\"\n def __init__(self, vectors, k, x0):\n self.vectors = vectors\n self.top_words = vectors.get_top_words(n=1000)\n self.k = k\n self.x0 = x0\n\n def get_estimate(self, doc, tf):\n terms = filter(lambda t: t in self.vectors, tf.keys()) # NOTE: exclude OOV words\n if not terms:\n return lambda t: 0\n\n freq = np.array([tf[t0] for t0 in terms])\n vec = np.vstack([self.vectors[t0] for t0 in terms])\n\n def _score(t):\n res = 0\n if t in self.vectors:\n # v = self.vectors[t]\n # values = scipy.special.expit(self.k * (np.array([np.dot(v, v0) for v0 in vec]) - self.x0)) ** freq\n # res = scipy.stats.mstats.gmean(values)\n values = -np.log1p(np.exp(- self.k * (np.dot(vec, self.vectors[t]) - self.x0)))\n res = np.exp(np.dot(values, freq) / freq.sum())\n return res\n\n Z = sum(_score(t) for t in self.top_words)\n\n return lambda t: _score(t) / Z\n\n\ndef build_weight_function(answers, relevance, estimator):\n estimates = []\n for answer in answers:\n tf = collections.Counter(answer)\n estimates.append(estimator.get_estimate(answer, tf))\n rels = relevance(len(answers))\n pairs = zip(rels, estimates)\n\n def _weight_function(t):\n return sum(r * est(t) for r, est in pairs)\n return _weight_function\n\n\ndef build_models(queries, relevance, estimator, tokenizer):\n models = {}\n for query in queries:\n original_query = tokenizer(query['text'])\n answers = [tokenizer(q['best_answer'] or '') for q in query['questions']]\n weights = build_weight_function(answers, relevance, estimator)\n models[query['qid']] = {'query': original_query,\n 'answers': answers,\n 'weights': weights}\n return models\n\n\ndef build_pipeline(stoplist):\n def MODEL_TERMS(doc):\n model, summary = doc\n return model, list(itertools.chain(*summary))\n\n pipeline = Pipeline()\n pipeline.add([CQAOverlap, NumSentences])\n pipeline.add([QueryOverlap, AvgWordWeight, AvgTermLen, Entropy, FracStops(stoplist), StopCover(stoplist)],\n adaptor=MODEL_TERMS)\n return pipeline\n\n\nclass PSGExtractor(Thingy):\n\n def __init__(self, K):\n self.K = K\n\n def extract(self, doc, tokenizer, weights, alpha):\n tokenized_sentences = map(tokenizer, doc['sentences'])\n obj, idx = find_max_scoring_passages(tokenized_sentences, weights, K=self.K)\n passage = [tokenized_sentences[i] for i in idx]\n passage_text = [doc['sentences'][i] for i in idx]\n return {'objective': obj, 'idx': idx, 'passage': passage, 'passage_text': passage_text}\n\n\nclass ILPExtractor(Thingy):\n\n def __init__(self, K, M):\n self.K = K\n self.M = M\n self.blacklist = set()\n\n def add_to_blacklist(self, qid, docno):\n self.blacklist.add((qid, docno))\n\n def extract(self, doc, tokenizer, weights, alpha):\n # FIXME: work around the Google or-tools segfault problem\n if (doc['qid'], doc['docno']) in self.blacklist:\n return {'objective': 0, 'idx': [], 'passage': [], 'passage_text': []}\n\n tokenized_sentences = map(tokenizer, doc['sentences'])\n obj, idx = summarize(tokenized_sentences, weights, M=self.M, K=self.K, alpha=alpha)\n passage = [tokenized_sentences[i] for i in idx]\n passage_text = [doc['sentences'][i] for i in idx]\n return {'objective': obj, 'idx': idx, 'passage': passage, 'passage_text': passage_text}\n\n\nclass DRProcessor(Thingy):\n\n def __init__(self, K, dr_data):\n self.K = K\n self.dr_data = dr_data\n\n def extract(self, doc, tokenizer, weights, alpha):\n qid, docno = doc['qid'], doc['docno']\n assert qid in self.dr_data, 'Missing qid %s in dr_data' % qid\n\n if docno in self.dr_data[qid]:\n entry = self.dr_data[qid][docno]\n obj, idx, passage, passage_text = entry['objective'], [], entry['passage'], entry['passage_text']\n else:\n obj, idx, passage, passage_text = 0, [], [], []\n\n return {'objective': obj, 'idx': idx, 'passage': passage, 'passage_text': passage_text}\n\n def get_estimate(self, doc, tf):\n def _estimate(t):\n return 0\n return _estimate\n\n\nclass WordEmbeddings(Thingy):\n def __init__(self, fname, engine):\n self.cache = {}\n if engine in ['fastText', 'fasttext']:\n self.model = fastText.load_model(fname)\n else:\n raise ValueError('invalid engine name: {}'.format(engine))\n\n def __contains__(self, word):\n return self.model.get_word_id(word) != -1\n\n def __getitem__(self, word):\n if word not in self.cache:\n v = self.model.get_word_vector(word)\n self.cache[word] = v / np.linalg.norm(v, 2) # NOTE: also normalize the vector\n return self.cache[word]\n\n def get_top_words(self, n):\n return self.model.get_words()[:n]\n\n\ndef yield_passages(sentences, K):\n sentence_lengths = [len(sentence) for sentence in sentences]\n i, sz = 0, 0\n for j in range(1, len(sentences)):\n assert i <= j\n sz += sentence_lengths[j]\n if sz >= K:\n yield range(i, j + 1)\n while sz >= 0.5 * K:\n sz -= sentence_lengths[i]\n i += 1\n\n\ndef find_max_scoring_passages(sentences, weights, K):\n terms = set()\n for sentence in sentences:\n terms.update(sentence)\n w = {t: weights(t) for t in terms}\n\n best_score, best_psg_idx = 0, []\n for psg_idx in yield_passages(sentences, K=K):\n score, sz = 0, 0\n for i in psg_idx:\n score += sum(w[t] for t in sentences[i])\n sz += len(sentences[i])\n score = float(score) / sz if sz != 0 else 0\n if score > best_score:\n best_score, best_psg_idx = score, psg_idx\n return best_score, best_psg_idx\n\n\ndef summarize(sentences, weights, M, K, alpha):\n \"\"\"Maximum coverage summarization algorithm (Takamura & Okumura, 2009)\"\"\"\n terms = set()\n for sentence in sentences:\n for t in sentence:\n terms.add(t)\n terms = {t: j for j, t in enumerate(terms)}\n\n w = {t: weights(t) for t in terms}\n\n a = {t: [] for t in terms}\n for i, sentence in enumerate(sentences):\n for t in sentence:\n a[t].append(i)\n\n solver = pywraplp.Solver('SolveIntegerProblem',\n pywraplp.Solver.CBC_MIXED_INTEGER_PROGRAMMING)\n x = [solver.IntVar(0, int(len(sentences[i]) >= M), 'x_{}'.format(i)) for i in range(len(sentences))]\n z = [solver.IntVar(0, 1, 'z_{}'.format(i)) for i in range(len(terms))]\n\n # Budget constraint\n budget = solver.Constraint(0, K)\n for i, sentence in enumerate(sentences):\n budget.SetCoefficient(x[i], len(sentence))\n\n # Per-term coverage constraint\n for j, term in enumerate(terms):\n term_coverage = solver.Constraint(-solver.infinity(), 0)\n term_coverage.SetCoefficient(z[j], 1)\n for i in a[term]:\n term_coverage.SetCoefficient(x[i], -1)\n\n obj = solver.Objective()\n for i, sentence in enumerate(sentences):\n obj.SetCoefficient(x[i], alpha * sum(w[t] for t in sentence))\n for j, term in enumerate(terms):\n obj.SetCoefficient(z[j], (1 - alpha) * w[term])\n obj.SetMaximization()\n\n result_status = solver.Solve()\n\n # FIXME: workaround\n if result_status != pywraplp.Solver.OPTIMAL:\n return 0, []\n\n assert result_status == pywraplp.Solver.OPTIMAL\n obj_value = solver.Objective().Value()\n return obj_value, [i for i, elem in enumerate(x) if elem.solution_value() > 0]\n\n\ndef main():\n parser = argparse.ArgumentParser(description='Extract answer passages')\n parser.add_argument('-alpha', type=float,\n help='alpha')\n parser.add_argument('-n', type=int,\n help='produce a summary of at most N words')\n parser.add_argument('-m', type=int,\n help='only select sentences with more than M words')\n parser.add_argument('-dump-passages', metavar='FILE',\n help='dump passage output to FILE')\n\n parser.add_argument('-k1', type=float)\n parser.add_argument('-b', type=float)\n parser.add_argument('-avg-dl', type=float)\n parser.add_argument('-k', type=float)\n parser.add_argument('-x0', type=float)\n parser.add_argument('-idf')\n parser.add_argument('-mu', type=float)\n parser.add_argument('-stoplist')\n parser.add_argument('-freqstats')\n parser.add_argument('-fasttext-bin')\n parser.add_argument('-dr-jsonl')\n\n parser.add_argument('method')\n parser.add_argument('corpus_json')\n parser.add_argument('ya_json')\n parser.add_argument('output')\n\n parser.set_defaults(alpha=0.1, n=50, m=5, k1=1.2, b=0.75, avg_dl=100, mu=100, k=10, x0=0)\n args = parser.parse_args()\n \n if args.method not in ['PSG+QL', 'PSG+BM25', 'PSG+Emb', 'DR', 'ILP+QL', 'ILP+BM25', 'ILP+Emb']:\n raise ValueError('invalid method: {}'.format(args.method))\n\n logging.info('Load queries/YA data')\n queries = json.load(smart_open(args.ya_json))\n\n logging.info('Set up feature extraction pipeline')\n stoplist = set(l.strip() for l in smart_open(args.stoplist))\n tokenizer = Tokenizer(stoplist=stoplist)\n pipeline = build_pipeline(stoplist=stoplist)\n\n # use graded relevance by default\n relevance = GradedRelevance\n\n # assign the extractor based on the method\n if args.method in ['PSG+QL', 'PSG+BM25', 'PSG+Emb']:\n extractor = PSGExtractor(K=args.n)\n elif args.method in ['ILP+QL', 'ILP+BM25', 'ILP+Emb']:\n extractor = ILPExtractor(K=args.n, M=args.m)\n\n # FIXME: workaround \n extractor.add_to_blacklist('767', 'GX245-22-3433326')\n extractor.add_to_blacklist('785', 'GX025-94-8770307')\n extractor.add_to_blacklist('837', 'GX268-01-5397177')\n extractor.add_to_blacklist('136', 'clueweb09-enwp01-82-19274')\n\n # assign the estimator based on the method\n if args.method in ['PSG+QL', 'ILP+QL']:\n if not args.freqstats:\n logging.error('Missing option -freqstats')\n return\n logging.info('Load freqstats')\n N, _, ctf, _ = load_freqstats(smart_open(args.freqstats))\n estimator = QLEstimator(N=N, ctf=ctf, mu=args.mu)\n\n elif args.method in ['PSG+BM25', 'ILP+BM25']:\n if not args.freqstats:\n logging.error('Missing option -freqstats')\n return\n logging.info('Load freqstats')\n _, D, _, df = load_freqstats(smart_open(args.freqstats))\n estimator = BM25Estimator(D=D, df=df, k1=args.k1, b=args.b, avg_dl=args.avg_dl)\n\n elif args.method in ['PSG+Emb', 'ILP+Emb']:\n if not args.fasttext_bin:\n logging.error('Missing option -fasttext-bin')\n return\n logging.info('Load fasttext bin')\n vectors = WordEmbeddings(args.fasttext_bin, 'fastText')\n estimator = WordEmbeddingEstimator(vectors=vectors, k=args.k, x0=args.x0)\n\n # NOTE: DR is configured in a particular way as it primarily loads precomputed data\n if args.method in ['DR']:\n if not args.dr_jsonl:\n logging.error('Missing option -dr-jsonl')\n return\n logging.info('Load dr_jsonl')\n dr_data = load_dr_data(smart_open(args.dr_jsonl))\n extractor = estimator = DRProcessor(K=args.n, dr_data=dr_data)\n\n print(extractor)\n print(estimator)\n\n models = build_models(queries,\n relevance=relevance,\n estimator=estimator,\n tokenizer=tokenizer)\n\n logging.info('Load corpus data (may take a while...)')\n ranked_lists = json.load(smart_open(args.corpus_json))\n\n logging.info('Will send output to {}'.format(args.output))\n output = smart_open(args.output, 'wb')\n\n passage_output = None\n if args.dump_passages:\n logging.info('Will send passage output to {}'.format(args.dump_passages))\n passage_output = smart_open(args.dump_passages, 'wb')\n\n for rl in tqdm(ranked_lists, desc='Process ranked lists'):\n qid = rl['topic']['qid']\n\n for doc in rl['docs']:\n docno = doc['docno']\n rel = max(doc['rel'], 0)\n score = doc['score']\n logging.debug('Process qid {} docno {}'.format(qid, docno))\n\n result = extractor.extract(doc,\n tokenizer=tokenizer,\n weights=models[qid]['weights'],\n alpha=args.alpha)\n\n obj = result['objective']\n answer_passage = result['passage']\n answer_passage_text = result['passage_text']\n\n if passage_output:\n print(qid, docno, rel, score, file=passage_output)\n for sentence in answer_passage_text:\n print(' ' + sentence.encode('utf8', errors='ignore'), file=passage_output)\n\n vector = ' '.join(['{}:{}'.format(i, val) for i, val in\n enumerate(pipeline.extract((models[qid], answer_passage)), 3)])\n print('{rel} qid:{qid} 1:{score} 2:{obj} {vector} # {docno}'.format(**locals()),\n file=output)\n\n\nif __name__ == '__main__':\n logging.basicConfig(format='[%(asctime)s] %(levelname)s: %(message)s',\n datefmt='%m/%d/%Y %I:%M:%S %p',\n level=logging.INFO)\n main()\n"
]
| [
[
"numpy.dot",
"numpy.arange",
"numpy.linalg.norm",
"numpy.ones",
"numpy.array",
"numpy.vstack"
]
]
|
Balance-Breaker/keras-contrib | [
"312c66dbcfdc95d865b848da8287525877f8f89f"
]
| [
"tests/keras_contrib/layers/test_normalization.py"
]
| [
"import pytest\nimport numpy as np\nfrom numpy.testing import assert_allclose\n\nfrom keras.layers import Dense, Activation, Input\nfrom keras.utils.test_utils import layer_test, keras_test\nfrom keras_contrib.layers import normalization\nfrom keras.models import Sequential, Model\nfrom keras import backend as K\nfrom keras_contrib import backend as KC\n\ninput_1 = np.arange(10)\ninput_2 = np.zeros(10)\ninput_3 = np.ones((10))\ninput_shapes = [np.ones((10, 10)), np.ones((10, 10, 10))]\n\n\n@keras_test\ndef basic_instancenorm_test():\n from keras import regularizers\n layer_test(normalization.InstanceNormalization,\n kwargs={'epsilon': 0.1,\n 'gamma_regularizer': regularizers.l2(0.01),\n 'beta_regularizer': regularizers.l2(0.01)},\n input_shape=(3, 4, 2))\n layer_test(normalization.InstanceNormalization,\n kwargs={'gamma_initializer': 'ones',\n 'beta_initializer': 'ones'},\n input_shape=(3, 4, 2))\n layer_test(normalization.InstanceNormalization,\n kwargs={'scale': False, 'center': False},\n input_shape=(3, 3))\n\n\n@keras_test\ndef test_instancenorm_correctness_rank2():\n model = Sequential()\n norm = normalization.InstanceNormalization(input_shape=(10, 1), axis=-1)\n model.add(norm)\n model.compile(loss='mse', optimizer='sgd')\n\n # centered on 5.0, variance 10.0\n x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10, 1))\n model.fit(x, x, epochs=4, verbose=0)\n out = model.predict(x)\n out -= K.eval(norm.beta)\n out /= K.eval(norm.gamma)\n\n assert_allclose(out.mean(), 0.0, atol=1e-1)\n assert_allclose(out.std(), 1.0, atol=1e-1)\n\n\n@keras_test\ndef test_instancenorm_correctness_rank1():\n # make sure it works with rank1 input tensor (batched)\n model = Sequential()\n norm = normalization.InstanceNormalization(input_shape=(10,), axis=None)\n model.add(norm)\n model.compile(loss='mse', optimizer='sgd')\n\n # centered on 5.0, variance 10.0\n x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10))\n model.fit(x, x, epochs=4, verbose=0)\n out = model.predict(x)\n out -= K.eval(norm.beta)\n out /= K.eval(norm.gamma)\n\n assert_allclose(out.mean(), 0.0, atol=1e-1)\n assert_allclose(out.std(), 1.0, atol=1e-1)\n\n\n@keras_test\ndef test_instancenorm_training_argument():\n bn1 = normalization.InstanceNormalization(input_shape=(10,))\n x1 = Input(shape=(10,))\n y1 = bn1(x1, training=True)\n\n model1 = Model(x1, y1)\n np.random.seed(123)\n x = np.random.normal(loc=5.0, scale=10.0, size=(20, 10))\n output_a = model1.predict(x)\n\n model1.compile(loss='mse', optimizer='rmsprop')\n model1.fit(x, x, epochs=1, verbose=0)\n output_b = model1.predict(x)\n assert np.abs(np.sum(output_a - output_b)) > 0.1\n assert_allclose(output_b.mean(), 0.0, atol=1e-1)\n assert_allclose(output_b.std(), 1.0, atol=1e-1)\n\n bn2 = normalization.InstanceNormalization(input_shape=(10,))\n x2 = Input(shape=(10,))\n bn2(x2, training=False)\n\n\n@keras_test\ndef test_instancenorm_convnet():\n model = Sequential()\n norm = normalization.InstanceNormalization(axis=1, input_shape=(3, 4, 4))\n model.add(norm)\n model.compile(loss='mse', optimizer='sgd')\n\n # centered on 5.0, variance 10.0\n x = np.random.normal(loc=5.0, scale=10.0, size=(1000, 3, 4, 4))\n model.fit(x, x, epochs=4, verbose=0)\n out = model.predict(x)\n out -= np.reshape(K.eval(norm.beta), (1, 3, 1, 1))\n out /= np.reshape(K.eval(norm.gamma), (1, 3, 1, 1))\n\n assert_allclose(np.mean(out, axis=(0, 2, 3)), 0.0, atol=1e-1)\n assert_allclose(np.std(out, axis=(0, 2, 3)), 1.0, atol=1e-1)\n\n\n@keras_test\ndef test_shared_instancenorm():\n '''Test that a IN layer can be shared\n across different data streams.\n '''\n # Test single layer reuse\n bn = normalization.InstanceNormalization(input_shape=(10,))\n x1 = Input(shape=(10,))\n bn(x1)\n\n x2 = Input(shape=(10,))\n y2 = bn(x2)\n\n x = np.random.normal(loc=5.0, scale=10.0, size=(2, 10))\n model = Model(x2, y2)\n model.compile('sgd', 'mse')\n model.train_on_batch(x, x)\n\n # Test model-level reuse\n x3 = Input(shape=(10,))\n y3 = model(x3)\n new_model = Model(x3, y3)\n new_model.compile('sgd', 'mse')\n new_model.train_on_batch(x, x)\n\n\n@keras_test\ndef test_instancenorm_perinstancecorrectness():\n model = Sequential()\n norm = normalization.InstanceNormalization(input_shape=(10,))\n model.add(norm)\n model.compile(loss='mse', optimizer='sgd')\n\n # bimodal distribution\n z = np.random.normal(loc=5.0, scale=10.0, size=(2, 10))\n y = np.random.normal(loc=-5.0, scale=17.0, size=(2, 10))\n x = np.append(z, y)\n x = np.reshape(x, (4, 10))\n model.fit(x, x, epochs=4, batch_size=4, verbose=1)\n out = model.predict(x)\n out -= K.eval(norm.beta)\n out /= K.eval(norm.gamma)\n\n # verify that each instance in the batch is individually normalized\n for i in range(4):\n instance = out[i]\n assert_allclose(instance.mean(), 0.0, atol=1e-1)\n assert_allclose(instance.std(), 1.0, atol=1e-1)\n\n # if each instance is normalized, so should the batch\n assert_allclose(out.mean(), 0.0, atol=1e-1)\n assert_allclose(out.std(), 1.0, atol=1e-1)\n\n\n@keras_test\ndef test_instancenorm_perchannel_correctness():\n\n # have each channel with a different average and std\n x = np.random.normal(loc=5.0, scale=2.0, size=(10, 1, 4, 4))\n y = np.random.normal(loc=10.0, scale=3.0, size=(10, 1, 4, 4))\n z = np.random.normal(loc=-5.0, scale=5.0, size=(10, 1, 4, 4))\n\n batch = np.append(x, y, axis=1)\n batch = np.append(batch, z, axis=1)\n\n # this model does not provide a normalization axis\n model = Sequential()\n norm = normalization.InstanceNormalization(axis=None, input_shape=(3, 4, 4), center=False, scale=False)\n model.add(norm)\n model.compile(loss='mse', optimizer='sgd')\n model.fit(batch, batch, epochs=4, verbose=0)\n out = model.predict(batch)\n\n # values will not be normalized per-channel\n for instance in range(10):\n for channel in range(3):\n activations = out[instance, channel]\n assert abs(activations.mean()) > 1e-2\n assert abs(activations.std() - 1.0) > 1e-6\n\n # but values are still normalized per-instance\n activations = out[instance]\n assert_allclose(activations.mean(), 0.0, atol=1e-1)\n assert_allclose(activations.std(), 1.0, atol=1e-1)\n\n # this model sets the channel as a normalization axis\n model = Sequential()\n norm = normalization.InstanceNormalization(axis=1, input_shape=(3, 4, 4), center=False, scale=False)\n model.add(norm)\n model.compile(loss='mse', optimizer='sgd')\n\n model.fit(batch, batch, epochs=4, verbose=0)\n out = model.predict(batch)\n\n # values are now normalized per-channel\n for instance in range(10):\n for channel in range(3):\n activations = out[instance, channel]\n assert_allclose(activations.mean(), 0.0, atol=1e-1)\n assert_allclose(activations.std(), 1.0, atol=1e-1)\n\n\n@keras_test\ndef basic_batchrenorm_test():\n from keras import regularizers\n\n layer_test(normalization.BatchRenormalization,\n input_shape=(3, 4, 2))\n\n layer_test(normalization.BatchRenormalization,\n kwargs={'gamma_regularizer': regularizers.l2(0.01),\n 'beta_regularizer': regularizers.l2(0.01)},\n input_shape=(3, 4, 2))\n\n\n@keras_test\ndef test_batchrenorm_mode_0_or_2():\n for training in [1, 0, None]:\n ip = Input(shape=(10,))\n norm_m0 = normalization.BatchRenormalization(momentum=0.8)\n out = norm_m0(ip, training=training)\n model = Model(ip, out)\n model.compile(loss='mse', optimizer='sgd')\n\n # centered on 5.0, variance 10.0\n X = np.random.normal(loc=5.0, scale=10.0, size=(1000, 10))\n model.fit(X, X, epochs=4, verbose=0)\n out = model.predict(X)\n out -= K.eval(norm_m0.beta)\n out /= K.eval(norm_m0.gamma)\n\n assert_allclose(out.mean(), 0.0, atol=1e-1)\n assert_allclose(out.std(), 1.0, atol=1e-1)\n\n\n@keras_test\ndef test_batchrenorm_mode_0_or_2_twice():\n # This is a regression test for issue #4881 with the old\n # batch normalization functions in the Theano backend.\n model = Sequential()\n model.add(normalization.BatchRenormalization(input_shape=(10, 5, 5), axis=1))\n model.add(normalization.BatchRenormalization(input_shape=(10, 5, 5), axis=1))\n model.compile(loss='mse', optimizer='sgd')\n\n X = np.random.normal(loc=5.0, scale=10.0, size=(20, 10, 5, 5))\n model.fit(X, X, epochs=1, verbose=0)\n model.predict(X)\n\n\n@keras_test\ndef test_batchrenorm_mode_0_convnet():\n model = Sequential()\n norm_m0 = normalization.BatchRenormalization(axis=1, input_shape=(3, 4, 4), momentum=0.8)\n model.add(norm_m0)\n model.compile(loss='mse', optimizer='sgd')\n\n # centered on 5.0, variance 10.0\n X = np.random.normal(loc=5.0, scale=10.0, size=(1000, 3, 4, 4))\n model.fit(X, X, epochs=4, verbose=0)\n out = model.predict(X)\n out -= np.reshape(K.eval(norm_m0.beta), (1, 3, 1, 1))\n out /= np.reshape(K.eval(norm_m0.gamma), (1, 3, 1, 1))\n\n assert_allclose(np.mean(out, axis=(0, 2, 3)), 0.0, atol=1e-1)\n assert_allclose(np.std(out, axis=(0, 2, 3)), 1.0, atol=1e-1)\n\n\n@keras_test\ndef test_shared_batchrenorm():\n '''Test that a BN layer can be shared\n across different data streams.\n '''\n # Test single layer reuse\n bn = normalization.BatchRenormalization(input_shape=(10,))\n x1 = Input(shape=(10,))\n bn(x1)\n\n x2 = Input(shape=(10,))\n y2 = bn(x2)\n\n x = np.random.normal(loc=5.0, scale=10.0, size=(2, 10))\n model = Model(x2, y2)\n assert len(model.updates) == 5\n model.compile('sgd', 'mse')\n model.train_on_batch(x, x)\n\n # Test model-level reuse\n x3 = Input(shape=(10,))\n y3 = model(x3)\n new_model = Model(x3, y3)\n assert len(model.updates) == 5\n new_model.compile('sgd', 'mse')\n new_model.train_on_batch(x, x)\n\n\n@keras_test\ndef test_batchrenorm_clipping_schedule():\n '''Test that the clipping schedule isn't fixed at r_max=1, d_max=0'''\n inp = Input(shape=(10,))\n bn = normalization.BatchRenormalization(t_delta=1.)\n out = bn(inp)\n model = Model(inp, out)\n model.compile('sgd', 'mse')\n\n x = np.random.normal(5, 10, size=(2, 10))\n y = np.random.normal(5, 10, size=(2, 10))\n\n r_max, d_max = K.get_value(bn.r_max), K.get_value(bn.d_max)\n assert r_max == 1\n assert d_max == 0\n\n for i in range(10):\n model.train_on_batch(x, y)\n\n r_max, d_max = K.get_value(bn.r_max), K.get_value(bn.d_max)\n assert_allclose([r_max, d_max], [3, 5], atol=1e-1)\n\n\n@keras_test\ndef test_batchrenorm_get_config():\n '''Test that get_config works on a model with a batchrenorm layer.'''\n x = Input(shape=(10,))\n y = normalization.BatchRenormalization()(x)\n model = Model(x, y)\n model.get_config()\n\n\nif __name__ == '__main__':\n pytest.main([__file__])\n"
]
| [
[
"numpy.random.seed",
"numpy.reshape",
"numpy.arange",
"numpy.ones",
"numpy.random.normal",
"numpy.append",
"numpy.mean",
"numpy.std",
"numpy.testing.assert_allclose",
"numpy.zeros",
"numpy.sum"
]
]
|
kevinbdsouza/VaeLM | [
"31e2d6abc0f49f2ca72d3f22ff17484859fc3601"
]
| [
"archive/encoders/encoder_gating.py"
]
| [
"import tensorflow as tf\nimport numpy as np\nimport collections\nimport os\nimport argparse\nimport datetime as dt\n\nfrom collections import Counter\nfrom random import random\nfrom nltk import word_tokenize\n\n\ndef preprocess(mode):\n # load text files\n train_sentences = [line.strip() for line in open(\"data/english/train.txt\").readlines()]\n val_sentences = [line.strip() for line in open(\"data/english/valid.txt\").readlines()]\n test_sentences = [line.strip() for line in open(\"data/english/test.txt\").readlines()]\n train_sentences = [x for x in train_sentences if x]\n val_sentences = [x for x in val_sentences if x]\n test_sentences = [x for x in test_sentences if x]\n max_char_len = 371\n\n if mode == \"train\":\n sentences = train_sentences\n pop_list = [4607, 38450, 24213, 27130, 28833, 39006, 38446, 20728, 2066, 11982, 2298, 18158, 4820, 29089, 24112,\n 35834,\n 8573, 30944, 5791, 12130, 10752, 30857, 34030, 458, 35900, 3219, 7860, 10241]\n for pop in pop_list:\n sentences.pop(pop)\n # max_char_len = 494\n elif mode == \"val\":\n sentences = val_sentences\n # max_char_len = 356\n elif mode == \"test\":\n sentences = test_sentences\n # max_char_len = 463\n\n sentences = [[\"<SOS>\"] + word_tokenize(sentence.lower()) + [\"<EOS>\"] for sentence in sentences]\n\n # set > as unk\n for ind, sen in enumerate(sentences):\n for i in range(20):\n try:\n sen.remove(\"<\")\n sen.remove(\"unk\")\n except:\n pass\n\n # define vocab\n vocabulary = [\"<SOS>\"] + [\"a\"] + [\"b\"] + [\"c\"] + [\"d\"] + [\"e\"] + [\"f\"] + \\\n [\"g\"] + [\"h\"] + [\"i\"] + [\"j\"] + [\"k\"] + [\"l\"] + [\"m\"] + [\"n\"] + [\"o\"] + \\\n [\"p\"] + [\"q\"] + [\"r\"] + [\"s\"] + [\"t\"] + [\"u\"] + [\"v\"] + [\"w\"] + \\\n [\"x\"] + [\"y\"] + [\"z\"] + [\"<EOW>\"] + [\"<EOS>\"] + [\">\"] + [\"-\"] + [\".\"] + [\"'\"] + [\"0\"] + [\"1\"] + [\n \"2\"] + [\"3\"] + \\\n [\"4\"] + [\"5\"] + [\"6\"] + [\"7\"] + [\"8\"] + [\"9\"] + [\"&\"] + [\"<\"] + [\"$\"] + [\"#\"] + [\"/\"] + [\",\"] + [\"|\"] + \\\n [\"@\"] + [\"%\"] + [\"^\"] + [\"\\\\\"] + [\"*\"] + [\"(\"] + [\")\"] + [\"{\"] + [\"}\"] + [\":\"] + [\";\"]\n\n vocabulary_size = len(vocabulary)\n token2index = {token: index for index, token in enumerate(vocabulary)}\n index2token = {index: token for index, token in enumerate(vocabulary)}\n one_hot_embeddings = np.eye(vocabulary_size)\n\n # find max word length\n max_word_length = 0\n maxid = 0\n for i in range(len(sentences)):\n l = len(sentences[i])\n if l > max_word_length:\n maxid = i\n max_word_length = l\n\n return sentences, vocabulary_size, max_word_length, one_hot_embeddings, token2index, max_char_len, index2token\n\n\n# produce character embeddings\ndef embed_producer(sentences, vocabulary_size, max_word_length, one_hot_embeddings, token2index, max_char_len):\n s_tensor = np.empty((len(sentences), max_char_len, vocabulary_size))\n word_loc_all = np.zeros((len(sentences), max_word_length))\n eow_loc_all = np.zeros((len(sentences), max_char_len))\n sen_lens = []\n num_words = []\n for i in range(len(sentences)):\n s = sentences[i]\n embed = np.zeros((max_char_len, vocabulary_size))\n word_loc = np.zeros(max_word_length)\n eow_loc = np.zeros(max_char_len)\n prev = 0\n count = 0\n # print(i)\n for k in range(len(s)):\n w = s[k]\n # print(w)\n for id, token in enumerate(w):\n\n if (w == \"<EOS>\") | (w == \"<SOS>\") | (w == \">\"):\n break\n else:\n # print(prev + id)\n # print(token)\n count += 1\n embed[prev + id, :] = np.squeeze(one_hot_embeddings[token2index.get(token)])\n\n if (w == \"<EOS>\") | (w == \"<SOS>\"):\n word_loc[k] = id + 1\n # print(prev)\n embed[prev, :] = one_hot_embeddings[token2index.get(w)]\n count += 1\n eow_loc[count] = 1\n prev = prev + id + 1\n\n elif (w == \">\"):\n word_loc[k] = id + 1\n count += 1\n embed[prev, :] = one_hot_embeddings[token2index.get(w)]\n prev = prev + id + 1\n embed[prev, :] = one_hot_embeddings[token2index.get(\"<EOW>\")]\n count += 1\n eow_loc[count] = 1\n prev = prev + 1\n\n else:\n prev = prev + id + 1\n word_loc[k] = id + 1\n # print(prev)\n embed[prev, :] = one_hot_embeddings[token2index.get(\"<EOW>\")]\n count += 1\n eow_loc[count] = 1\n prev = prev + 1\n\n s_tensor[i, :, :] = embed\n eow_loc_all[i, :] = eow_loc\n n_w = int(np.sum(eow_loc_all[i]))\n\n num_words.append(2 * n_w - 1)\n sen_lens.append(count + 1)\n\n # to get word end locations to retrieve hidden states later\n word_loc_all[i, 0] = word_loc[0]\n for j in range(1, len(s)):\n word_loc_all[i, j] = word_loc_all[i, j - 1] + word_loc[j]\n\n return s_tensor, eow_loc_all, sen_lens, num_words\n\n\ndef run_preprocess(mode):\n # preprocess the data\n sentences, vocabulary_size, max_word_length, one_hot_embeddings, token2index, max_char_len, index2token = preprocess(\n mode)\n # produce embeddings\n data, eow_loc_all, sen_lens, num_words = embed_producer(sentences, vocabulary_size, max_word_length,\n one_hot_embeddings, token2index, max_char_len)\n\n return data, eow_loc_all, sen_lens, num_words, vocabulary_size, index2token, max_char_len\n\n\ndef get_output_sentences(index2token, indices):\n # indices of size (_,maxChar)\n space = \"\"\n sentences_all = []\n for sample in range(len(indices)):\n sentence = []\n sen = indices[sample]\n for char in range(len(sen)):\n if (index2token.get(sen[char]) == \"<SOS>\"):\n sentence.append(\"\")\n elif (index2token.get(sen[char]) == \"<EOS>\"):\n break\n elif (index2token.get(sen[char]) == \"<EOW>\"):\n sentence.append(\" \")\n else:\n sentence.append(index2token.get(sen[char]))\n\n sentences_all.append(space.join(sentence))\n\n return sentences_all\n\n\nclass Encoder:\n def __init__(self, **kwargs):\n # self.data =kwargs['data']\n # self.sentences =kwargs['sentences']\n self.vocabulary_size = kwargs['vocabulary_size']\n # self.max_word_length = kwargs['max_word_length']\n self.max_char_len = kwargs['max_char_len']\n self.batch_size = kwargs['batch_size']\n self.input_size = kwargs['input_size']\n self.hidden_size = kwargs['hidden_size']\n \n\n def vanilla_encoder(self, inputs, seq_length, reuse):\n inputs = tf.reshape(inputs, [-1, self.vocabulary_size])\n with tf.variable_scope('projection', reuse=reuse):\n inputs = tf.layers.dense(inputs=inputs, units=self.input_size, activation=None)\n inputs = tf.reshape(inputs, [self.batch_size, self.max_char_len, self.input_size])\n cell = tf.contrib.rnn.LSTMCell(self.hidden_size)\n with tf.variable_scope('vanilla_rnn_enc', reuse=reuse):\n _, state = tf.nn.dynamic_rnn(cell=cell, inputs=inputs, dtype=tf.float32, sequence_length=seq_length)\n\n with tf.variable_scope('lat_var', reuse=reuse):\n out = tf.layers.dense(inputs=state[-1], units=self.hidden_size * 2, activation=tf.nn.relu)\n mu, logsig = tf.split(tf.layers.dense(inputs=out, units=self.hidden_size * 2, activation=None), 2, axis=-1)\n eps = tf.random_normal(shape=[self.batch_size], dtype=tf.float32)\n lat_var = mu + tf.exp(logsig) * eps\n return lat_var, mu, logsig\n\n # our [494, 52, 61] tensor becomes [[52, 61], [52, 61], ...]\n def run_encoder(self, train, inputs, word_pos, sentence_lens, reuse):\n\n '''\n inputs = tf.reshape(inputs, [-1, self.vocabulary_size])\n print('inputs_1 {}'.format(inputs))\n with tf.variable_scope('projection1', reuse=reuse):\n inputs = tf.layers.dense(inputs=inputs, units=self.input_size, activation=None)\n '''\n inputs = tf.reshape(inputs, [self.batch_size, self.max_char_len, self.input_size])\n inputs.set_shape([self.batch_size, self.max_char_len, self.input_size])\n sentence_lens = tf.cast(sentence_lens,dtype=tf.int32)\n\n #Bi LSTM\n with tf.variable_scope('encoder_bi', reuse=reuse):\n \tcell1 = tf.contrib.rnn.LSTMCell(num_units=self.input_size)\n \tcell2 = tf.contrib.rnn.LSTMCell(num_units=self.input_size)\n \tvalues, _ = tf.nn.bidirectional_dynamic_rnn(inputs=inputs, dtype=tf.float32, cell_bw=cell1,\n \t cell_fw=cell2, sequence_length=sentence_lens)\n \tprint('values {}'.format(values))\n\n inputs = tf.concat(values,2)\n print('bi_outputs {}'.format(inputs))\n\n #input projection\n inputs = tf.reshape(inputs, [-1, self.input_size*2])\n print('inputs_2 {}'.format(inputs))\n with tf.variable_scope('projection', reuse=reuse):\n inputs = tf.layers.dense(inputs=inputs, units=self.input_size, activation=None)\n\n print('inputs_3 {}'.format(inputs))\n\n inputs = tf.reshape(inputs, [self.batch_size, self.max_char_len, self.input_size])\n inputs.set_shape([self.batch_size, self.max_char_len, self.input_size])\n\n inputs_t = tf.transpose(inputs, perm=[1, 0, 2])\n inputs_t.set_shape([self.max_char_len, self.batch_size, self.input_size])\n _inputs_ta = tf.TensorArray(dtype=tf.float32, size=self.max_char_len, name='char_array')\n _inputs_ta = _inputs_ta.unstack(inputs_t)\n\n cell = tf.contrib.rnn.LSTMCell(self.hidden_size)\n output_ta = tf.TensorArray(size=self.max_char_len, dtype=tf.float32, name='word_array')\n mean_ta = tf.TensorArray(size=self.max_char_len, dtype=tf.float32, name='mean_array')\n sigma_ta = tf.TensorArray(size=self.max_char_len, dtype=tf.float32, name='sigma_array')\n word_pos = tf.convert_to_tensor(word_pos, dtype=tf.float32)\n\n # create loop_fn for raw_rnn\n def loop_fn(time, cell_output, cell_state, loop_state):\n emit_output = cell_output # == None if time = 0\n\n if cell_output is None: # time = 0\n next_cell_state = cell.zero_state(self.batch_size, tf.float32)\n sample_loop_state = output_ta\n mean_loop_state = mean_ta\n sigma_loop_state = sigma_ta\n next_loop_state = (sample_loop_state, mean_loop_state, sigma_loop_state)\n # next_input = tf.zeros(shape=[self.batch_size,self.input_size],dtype=tf.float32)\n\n else:\n word_slice = tf.tile(word_pos[:, time - 1], [self.hidden_size])\n word_slice = tf.reshape(word_slice, [self.hidden_size, self.batch_size])\n word_slice = tf.transpose(word_slice, perm=[1, 0])\n next_sampled_input = tf.multiply(cell_output, word_slice)\n\n # reparametrization\n z_concat = tf.contrib.layers.fully_connected(next_sampled_input, 2 * self.hidden_size)\n z_concat = tf.contrib.layers.fully_connected(z_concat, 2 * self.hidden_size,activation_fn=None)\n\n z_mean = z_concat[:, :self.hidden_size]\n z_mean = z_mean * 10\n z_log_sigma_sq = z_concat[:, self.hidden_size:self.hidden_size * 2]\n z_log_sigma_sq = z_log_sigma_sq - 3\n eps = tf.random_normal((self.batch_size, self.hidden_size), 0, 1, dtype=tf.float32)\n\n z_sample = tf.add(z_mean, tf.multiply(tf.exp(z_log_sigma_sq), eps))\n\n z_sample = tf.multiply(z_sample, word_slice)\n z_mean = tf.multiply(z_mean, word_slice)\n z_log_sigma_sq = tf.multiply(z_log_sigma_sq, word_slice)\n\n #try gating \n if train:\n z_sample_gate = tf.sigmoid(z_sample)\n z_sample_gate = tf.multiply(z_sample_gate, word_slice)\n next_cell_state = tf.multiply(cell_state[0],z_sample_gate)\n \n else:\n z_mean_gate = tf.sigmoid(z_mean)\n z_mean_gate = tf.multiply(z_mean_gate, word_slice)\n next_cell_state = tf.multiply(cell_state[0 ],z_mean_gate)\n \n sample_loop_state = loop_state[0].write(time - 1, next_cell_state)\n mean_loop_state = loop_state[1].write(time - 1, z_mean)\n sigma_loop_state = loop_state[2].write(time - 1, z_log_sigma_sq)\n next_loop_state = (sample_loop_state, mean_loop_state, sigma_loop_state)\n\n word_slice = tf.logical_not(tf.cast(word_slice, dtype=tf.bool))\n word_slice = tf.cast(word_slice, dtype=tf.float32)\n next_cell_state = next_cell_state + tf.multiply(cell_state[0], word_slice)\n next_cell_state = tf.contrib.rnn.LSTMStateTuple(next_cell_state, cell_output)\n\n next_input = tf.cond(time < self.max_char_len, lambda: _inputs_ta.read(time),\n lambda: tf.zeros(shape=[self.batch_size, self.input_size], dtype=tf.float32))\n\n elements_finished = (time >= (self.max_char_len))\n\n return (elements_finished, next_input, next_cell_state, emit_output, next_loop_state)\n\n with tf.variable_scope('encoder_rnn', reuse=reuse):\n outputs_ta, final_state_out, word_state = tf.nn.raw_rnn(cell, loop_fn)\n\n word_state_out = word_state[0].stack()\n mean_state_out = word_state[1].stack()\n sigma_state_out = word_state[2].stack()\n outputs_out = outputs_ta.stack()\n\n return word_state_out, mean_state_out, sigma_state_out\n\n\nif __name__ == \"__main__\":\n\n data, eow_loc_all,sen_lens, _, _, _, _ = run_preprocess(mode=\"train\")\n print(len(data))\n max_char_len = 371\n batch_size = 40\n vocabulary_size = 61\n input_size = 61\n hidden_size = 20\n num_batches = len(data) // batch_size\n sen_lens = np.reshape(sen_lens,[-1,batch_size])\n arg_dict = {'max_char_len': max_char_len, 'batch_size': batch_size, 'input_size': input_size,\n 'hidden_size': hidden_size,'vocabulary_size':vocabulary_size}\n encoder = Encoder(**arg_dict)\n\n\n # placeholders\n inputs_pl = tf.placeholder(tf.float32, [batch_size, max_char_len, input_size])\n word_pos_pl = tf.placeholder(tf.float32, [batch_size, max_char_len])\n sen_lens_pl = tf.placeholder(tf.float32, [batch_size])\n\n word_state_out, mean_state_out, sigma_state_out = encoder.run_encoder(True,inputs=inputs_pl,word_pos=word_pos_pl,sentence_lens=sen_lens_pl,reuse=None)\n\n # example\n init_op = tf.global_variables_initializer()\n with tf.Session() as sess:\n sess.run([init_op])\n for epoch in range(1):\n epoch_error = 0\n\n for bt in range(2):\n x = data[bt * batch_size:(bt + 1) * batch_size]\n word_pos_batch = eow_loc_all[bt * batch_size:(bt + 1) * batch_size]\n word_state, mean_state, sigma_state = sess.run([word_state_out, mean_state_out, sigma_state_out],\n feed_dict={inputs_pl: x, word_pos_pl: word_pos_batch,sen_lens_pl:sen_lens[bt]})\n\n print(mean_state)\n"
]
| [
[
"tensorflow.convert_to_tensor",
"tensorflow.nn.dynamic_rnn",
"tensorflow.nn.raw_rnn",
"tensorflow.concat",
"tensorflow.zeros",
"tensorflow.cast",
"tensorflow.nn.bidirectional_dynamic_rnn",
"numpy.reshape",
"numpy.eye",
"tensorflow.layers.dense",
"tensorflow.Session",
"numpy.zeros",
"tensorflow.tile",
"tensorflow.TensorArray",
"tensorflow.placeholder",
"tensorflow.exp",
"tensorflow.global_variables_initializer",
"tensorflow.contrib.rnn.LSTMStateTuple",
"numpy.sum",
"tensorflow.multiply",
"tensorflow.transpose",
"tensorflow.reshape",
"tensorflow.sigmoid",
"tensorflow.contrib.layers.fully_connected",
"tensorflow.contrib.rnn.LSTMCell",
"tensorflow.variable_scope",
"tensorflow.random_normal"
]
]
|
Mainframed69/tensorflow | [
"f8b5c95a7882efd58b123aeb308dfb173658a9e6"
]
| [
"tensorflow/python/compat/compat.py"
]
| [
"# 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\"\"\"Utilities for API compatibility between TensorFlow release versions.\n\nSee [Version\nCompatibility](https://tensorflow.org/guide/version_compat#backward_forward)\n\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport datetime\nfrom tensorflow.python.util import tf_contextlib\nfrom tensorflow.python.util.tf_export import tf_export\n\n_FORWARD_COMPATIBILITY_HORIZON = datetime.date(2018, 11, 12)\n\n\n@tf_export(\"compat.forward_compatible\")\ndef forward_compatible(year, month, day):\n \"\"\"Return true if the forward compatibility window has expired.\n\n See [Version\n compatibility](https://tensorflow.org/guide/version_compat#backward_forward).\n\n Forward-compatibility refers to scenarios where the producer of a TensorFlow\n model (a GraphDef or SavedModel) is compiled against a version of the\n TensorFlow library newer than what the consumer was compiled against. The\n \"producer\" is typically a Python program that constructs and trains a model\n while the \"consumer\" is typically another program that loads and serves the\n model.\n\n TensorFlow has been supporting a 3 week forward-compatibility window for\n programs compiled from source at HEAD.\n\n For example, consider the case where a new operation `MyNewAwesomeAdd` is\n created with the intent of replacing the implementation of an existing Python\n wrapper - `tf.add`. The Python wrapper implementation should change from\n something like:\n\n ```python\n def add(inputs, name=None):\n return gen_math_ops.add(inputs, name)\n ```\n\n to:\n\n ```python\n from tensorflow.python.compat import compat\n\n def add(inputs, name=None):\n if compat.forward_compatible(year, month, day):\n # Can use the awesome new implementation.\n return gen_math_ops.my_new_awesome_add(inputs, name)\n # To maintain forward compatibiltiy, use the old implementation.\n return gen_math_ops.add(inputs, name)\n ```\n\n Where `year`, `month`, and `day` specify the date beyond which binaries\n that consume a model are expected to have been updated to include the\n new operations. This date is typically at least 3 weeks beyond the date\n the code that adds the new operation is committed.\n\n Args:\n year: A year (e.g., 2018).\n month: A month (1 <= month <= 12) in year.\n day: A day (1 <= day <= 31, or 30, or 29, or 28) in month.\n\n Returns:\n True if the caller can expect that serialized TensorFlow graphs produced\n can be consumed by programs that are compiled with the TensorFlow library\n source code after (year, month, day).\n \"\"\"\n return _FORWARD_COMPATIBILITY_HORIZON > datetime.date(year, month, day)\n\n\n@tf_export(\"compat.forward_compatibility_horizon\")\n@tf_contextlib.contextmanager\ndef forward_compatibility_horizon(year, month, day):\n \"\"\"Context manager for testing forward compatibility of generated graphs.\n\n See [Version\n compatibility](https://tensorflow.org/guide/version_compat#backward_forward).\n\n To ensure forward compatibility of generated graphs (see `forward_compatible`)\n with older binaries, new features can be gated with:\n\n ```python\n if compat.forward_compatible(year=2018, month=08, date=01):\n generate_graph_with_new_features()\n else:\n generate_graph_so_older_binaries_can_consume_it()\n ```\n\n However, when adding new features, one may want to unittest it before\n the forward compatibility window expires. This context manager enables\n such tests. For example:\n\n ```python\n from tensorflow.python.compat import compat\n\n def testMyNewFeature(self):\n with compat.forward_compatibility_horizon(2018, 08, 02):\n # Test that generate_graph_with_new_features() has an effect\n ```\n\n Args :\n year: A year (e.g. 2018).\n month: A month (1 <= month <= 12) in year.\n day: A day (1 <= day <= 31, or 30, or 29, or 28) in month.\n\n Yields:\n Nothing.\n \"\"\"\n global _FORWARD_COMPATIBILITY_HORIZON\n try:\n old_compat_date = _FORWARD_COMPATIBILITY_HORIZON\n _FORWARD_COMPATIBILITY_HORIZON = datetime.date(year, month, day)\n yield\n finally:\n _FORWARD_COMPATIBILITY_HORIZON = old_compat_date\n"
]
| [
[
"tensorflow.python.util.tf_export.tf_export"
]
]
|
colinski/mmclassification | [
"447c8291bc2e2abda6f3eafe2e6d0f13d65843cb"
]
| [
"mmcls/datasets/builder.py"
]
| [
"# Copyright (c) OpenMMLab. All rights reserved.\nimport copy\nimport platform\nimport random\nfrom functools import partial\n\nimport numpy as np\nimport torch\nfrom mmcv.parallel import collate\nfrom mmcv.runner import get_dist_info\nfrom mmcv.utils import Registry, build_from_cfg, digit_version\nfrom torch.utils.data import DataLoader\n\nif platform.system() != 'Windows':\n # https://github.com/pytorch/pytorch/issues/973\n import resource\n rlimit = resource.getrlimit(resource.RLIMIT_NOFILE)\n hard_limit = rlimit[1]\n soft_limit = min(4096, hard_limit)\n resource.setrlimit(resource.RLIMIT_NOFILE, (soft_limit, hard_limit))\n\nDATASETS = Registry('dataset')\nPIPELINES = Registry('pipeline')\nSAMPLERS = Registry('sampler')\n\n\ndef build_dataset(cfg, default_args=None):\n from .dataset_wrappers import (ClassBalancedDataset, ConcatDataset,\n KFoldDataset, RepeatDataset)\n if isinstance(cfg, (list, tuple)):\n dataset = ConcatDataset([build_dataset(c, default_args) for c in cfg])\n elif cfg['type'] == 'ConcatDataset':\n dataset = ConcatDataset(\n [build_dataset(c, default_args) for c in cfg['datasets']],\n separate_eval=cfg.get('separate_eval', True))\n elif cfg['type'] == 'RepeatDataset':\n dataset = RepeatDataset(\n build_dataset(cfg['dataset'], default_args), cfg['times'])\n elif cfg['type'] == 'ClassBalancedDataset':\n dataset = ClassBalancedDataset(\n build_dataset(cfg['dataset'], default_args), cfg['oversample_thr'])\n elif cfg['type'] == 'KFoldDataset':\n cp_cfg = copy.deepcopy(cfg)\n if cp_cfg.get('test_mode', None) is None:\n cp_cfg['test_mode'] = (default_args or {}).pop('test_mode', False)\n cp_cfg['dataset'] = build_dataset(cp_cfg['dataset'], default_args)\n cp_cfg.pop('type')\n dataset = KFoldDataset(**cp_cfg)\n else:\n dataset = build_from_cfg(cfg, DATASETS, default_args)\n\n return dataset\n\n\ndef build_dataloader(dataset,\n samples_per_gpu,\n workers_per_gpu,\n num_gpus=1,\n dist=True,\n shuffle=True,\n round_up=True,\n seed=None,\n pin_memory=True,\n persistent_workers=True,\n sampler_cfg=None,\n **kwargs):\n \"\"\"Build PyTorch DataLoader.\n\n In distributed training, each GPU/process has a dataloader.\n In non-distributed training, there is only one dataloader for all GPUs.\n\n Args:\n dataset (Dataset): A PyTorch dataset.\n samples_per_gpu (int): Number of training samples on each GPU, i.e.,\n batch size of each GPU.\n workers_per_gpu (int): How many subprocesses to use for data loading\n for each GPU.\n num_gpus (int): Number of GPUs. Only used in non-distributed training.\n dist (bool): Distributed training/test or not. Default: True.\n shuffle (bool): Whether to shuffle the data at every epoch.\n Default: True.\n round_up (bool): Whether to round up the length of dataset by adding\n extra samples to make it evenly divisible. Default: True.\n pin_memory (bool): Whether to use pin_memory in DataLoader.\n Default: True\n persistent_workers (bool): If True, the data loader will not shutdown\n the worker processes after a dataset has been consumed once.\n This allows to maintain the workers Dataset instances alive.\n The argument also has effect in PyTorch>=1.7.0.\n Default: True\n sampler_cfg (dict): sampler configuration to override the default\n sampler\n kwargs: any keyword argument to be used to initialize DataLoader\n\n Returns:\n DataLoader: A PyTorch dataloader.\n \"\"\"\n rank, world_size = get_dist_info()\n\n # Custom sampler logic\n if sampler_cfg:\n # shuffle=False when val and test\n sampler_cfg.update(shuffle=shuffle)\n sampler = build_sampler(\n sampler_cfg,\n default_args=dict(\n dataset=dataset, num_replicas=world_size, rank=rank,\n seed=seed))\n # Default sampler logic\n elif dist:\n sampler = build_sampler(\n dict(\n type='DistributedSampler',\n dataset=dataset,\n num_replicas=world_size,\n rank=rank,\n shuffle=shuffle,\n round_up=round_up,\n seed=seed))\n else:\n sampler = None\n\n # If sampler exists, turn off dataloader shuffle\n if sampler is not None:\n shuffle = False\n\n if dist:\n batch_size = samples_per_gpu\n num_workers = workers_per_gpu\n else:\n batch_size = num_gpus * samples_per_gpu\n num_workers = num_gpus * workers_per_gpu\n\n init_fn = partial(\n worker_init_fn, num_workers=num_workers, rank=rank,\n seed=seed) if seed is not None else None\n\n if digit_version(torch.__version__) >= digit_version('1.8.0'):\n kwargs['persistent_workers'] = persistent_workers\n\n data_loader = DataLoader(\n dataset,\n batch_size=batch_size,\n sampler=sampler,\n num_workers=num_workers,\n collate_fn=partial(collate, samples_per_gpu=samples_per_gpu),\n pin_memory=pin_memory,\n shuffle=shuffle,\n worker_init_fn=init_fn,\n **kwargs)\n\n return data_loader\n\n\ndef worker_init_fn(worker_id, num_workers, rank, seed):\n # The seed of each worker equals to\n # num_worker * rank + worker_id + user_seed\n worker_seed = num_workers * rank + worker_id + seed\n np.random.seed(worker_seed)\n random.seed(worker_seed)\n torch.manual_seed(worker_seed)\n\n\ndef build_sampler(cfg, default_args=None):\n if cfg is None:\n return None\n else:\n return build_from_cfg(cfg, SAMPLERS, default_args=default_args)\n"
]
| [
[
"torch.manual_seed",
"numpy.random.seed"
]
]
|
Odiurd/deep-reinforcement-learning-continuous-control | [
"b1fb17ceab8cf23200dbdada21ba2ab0e33aa1a2"
]
| [
"model.py"
]
| [
"#https://github.com/udacity/deep-reinforcement-learning/tree/master/ddpg-pendulum\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\ndef hidden_init(layer):\n fan_in = layer.weight.data.size()[0]\n lim = 1. / np.sqrt(fan_in)\n return (-lim, lim)\n\nclass Actor(nn.Module):\n \"\"\"Actor (Policy) Model.\"\"\"\n\n def __init__(self, state_size, action_size, seed, fc1_units=400, fc2_units=300):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fc1_units (int): Number of nodes in first hidden layer\n fc2_units (int): Number of nodes in second hidden layer\n \"\"\"\n super(Actor, self).__init__()\n self.seed = torch.manual_seed(seed)\n self.fc1 = nn.Linear(state_size, fc1_units)\n self.fc2 = nn.Linear(fc1_units, fc2_units)\n self.fc3 = nn.Linear(fc2_units, action_size)\n self.reset_parameters()\n\n def reset_parameters(self):\n self.fc1.weight.data.uniform_(*hidden_init(self.fc1))\n self.fc2.weight.data.uniform_(*hidden_init(self.fc2))\n self.fc3.weight.data.uniform_(-3e-3, 3e-3)\n\n def forward(self, state):\n \"\"\"Build an actor (policy) network that maps states -> actions.\"\"\"\n x = F.relu(self.fc1(state))\n x = F.relu(self.fc2(x))\n return F.tanh(self.fc3(x))\n\n\nclass Critic(nn.Module):\n \"\"\"Critic (Value) Model.\"\"\"\n\n def __init__(self, state_size, action_size, seed, fcs1_units=400, fc2_units=300):\n \"\"\"Initialize parameters and build model.\n Params\n ======\n state_size (int): Dimension of each state\n action_size (int): Dimension of each action\n seed (int): Random seed\n fcs1_units (int): Number of nodes in the first hidden layer\n fc2_units (int): Number of nodes in the second hidden layer\n \"\"\"\n super(Critic, self).__init__()\n self.seed = torch.manual_seed(seed)\n self.fcs1 = nn.Linear(state_size, fcs1_units)\n self.fc2 = nn.Linear(fcs1_units+action_size, fc2_units)\n self.fc3 = nn.Linear(fc2_units, 1)\n self.reset_parameters()\n\n def reset_parameters(self):\n self.fcs1.weight.data.uniform_(*hidden_init(self.fcs1))\n self.fc2.weight.data.uniform_(*hidden_init(self.fc2))\n self.fc3.weight.data.uniform_(-3e-3, 3e-3)\n\n def forward(self, state, action):\n \"\"\"Build a critic (value) network that maps (state, action) pairs -> Q-values.\"\"\"\n xs = F.relu(self.fcs1(state))\n x = torch.cat((xs, action), dim=1)\n x = F.relu(self.fc2(x))\n return self.fc3(x)"
]
| [
[
"torch.nn.Linear",
"torch.manual_seed",
"numpy.sqrt",
"torch.cat"
]
]
|
Mikoto10032/CycleGAN | [
"c565387c8e068955dfa3134734af9638b0e05c74"
]
| [
"layers.py"
]
| [
"import tensorflow as tf\n\ndef lrelu(x, leak=0.2, name=\"lrelu\", alt_relu_impl=False):\n\n with tf.variable_scope(name):\n if alt_relu_impl:\n f1 = 0.5 * (1 + leak)\n f2 = 0.5 * (1 - leak)\n # lrelu = 1/2 * (1 + leak) * x + 1/2 * (1 - leak) * |x|\n return f1 * x + f2 * abs(x)\n else:\n return tf.maximum(x, leak*x)\n\ndef instance_norm(x):\n\n with tf.variable_scope(\"instance_norm\"):\n epsilon = 1e-5\n mean, var = tf.nn.moments(x, [1, 2], keep_dims=True)\n scale = tf.get_variable('scale',[x.get_shape()[-1]],\n initializer=tf.truncated_normal_initializer(mean=1.0, stddev=0.02))\n offset = tf.get_variable('offset',[x.get_shape()[-1]],initializer=tf.constant_initializer(0.0))\n out = scale*tf.div(x-mean, tf.sqrt(var+epsilon)) + offset\n\n return out\n'''\n/**\n *@params inputconv,่พๅ
ฅๅพๅ๏ผo_d๏ผๅท็งฏๆ ธๆฐ็ฎ๏ผf_h๏ผๅท็งฏๆ ธ้ซ๏ผf_w๏ผๅท็งฏๆ ธๅฎฝ๏ผs_h๏ผๆปๅจ้ซๅบฆ๏ผs_h๏ผๆปๅจๅฎฝๅบฆ\n * stddev๏ผๅท็งฏๆ ธๆ ๅๅทฎ๏ผpadding๏ผๅกซๅ
๏ผdo_norm๏ผๆฏๅฆๅฝไธ๏ผdo_relu๏ผๆฏๅฆๅฏนๅท็งฏไนๅๅreluๅฝๆฐๆฟๆดป๏ผ\n */\n'''\ndef general_conv2d(inputconv, o_d=64, f_h=7, f_w=7, s_h=1, s_w=1, stddev=0.02, padding=\"VALID\", name=\"conv2d\", do_norm=True, do_relu=True, relufactor=0):\n with tf.variable_scope(name):\n\n conv = tf.contrib.layers.conv2d(inputconv, o_d, f_w, s_w, padding, activation_fn=None, weights_initializer=tf.truncated_normal_initializer(stddev=stddev),biases_initializer=tf.constant_initializer(0.0))\n if do_norm:\n conv = instance_norm(conv)\n # conv = tf.contrib.layers.batch_norm(conv, decay=0.9, updates_collections=None, epsilon=1e-5, scale=True, scope=\"batch_norm\")\n\n if do_relu:\n if(relufactor == 0):\n conv = tf.nn.relu(conv,\"relu\")\n else:\n conv = lrelu(conv, relufactor, \"lrelu\")\n\n return conv\n\n\n\ndef general_deconv2d(inputconv, outshape, o_d=64, f_h=7, f_w=7, s_h=1, s_w=1, stddev=0.02, padding=\"VALID\", name=\"deconv2d\", do_norm=True, do_relu=True, relufactor=0):\n with tf.variable_scope(name):\n\n conv = tf.contrib.layers.conv2d_transpose(inputconv, o_d, [f_h, f_w], [s_h, s_w], padding, activation_fn=None, weights_initializer=tf.truncated_normal_initializer(stddev=stddev),biases_initializer=tf.constant_initializer(0.0))\n\n if do_norm:\n conv = instance_norm(conv)\n # conv = tf.contrib.layers.batch_norm(conv, decay=0.9, updates_collections=None, epsilon=1e-5, scale=True, scope=\"batch_norm\")\n\n if do_relu:\n if(relufactor == 0):\n conv = tf.nn.relu(conv,\"relu\")\n else:\n conv = lrelu(conv, relufactor, \"lrelu\")\n\n return conv\n"
]
| [
[
"tensorflow.nn.relu",
"tensorflow.maximum",
"tensorflow.nn.moments",
"tensorflow.truncated_normal_initializer",
"tensorflow.constant_initializer",
"tensorflow.variable_scope",
"tensorflow.sqrt"
]
]
|
billzhao1990/CS231n-Spring-2017 | [
"a87597da2605be9f4ce0b84ed84408b313a3dc72"
]
| [
"assignment2/cs231n/classifiers/fc_net.py"
]
| [
"from builtins import range\nfrom builtins import object\nimport numpy as np\n\nfrom cs231n.layers import *\nfrom cs231n.layer_utils import *\n\n\nclass TwoLayerNet(object):\n \"\"\"\n A two-layer fully-connected neural network with ReLU nonlinearity and\n softmax loss that uses a modular layer design. We assume an input dimension\n of D, a hidden dimension of H, and perform classification over C classes.\n\n The architecure should be affine - relu - affine - softmax.\n\n Note that this class does not implement gradient descent; instead, it\n will interact with a separate Solver object that is responsible for running\n optimization.\n\n The learnable parameters of the model are stored in the dictionary\n self.params that maps parameter names to numpy arrays.\n \"\"\"\n\n def __init__(self, input_dim=3*32*32, hidden_dim=100, num_classes=10,\n weight_scale=1e-3, reg=0.0):\n \"\"\"\n Initialize a new network.\n\n Inputs:\n - input_dim: An integer giving the size of the input\n - hidden_dim: An integer giving the size of the hidden layer\n - num_classes: An integer giving the number of classes to classify\n - dropout: Scalar between 0 and 1 giving dropout strength.\n - weight_scale: Scalar giving the standard deviation for random\n initialization of the weights.\n - reg: Scalar giving L2 regularization strength.\n \"\"\"\n self.params = {}\n self.reg = reg\n\n ############################################################################\n # TODO: Initialize the weights and biases of the two-layer net. Weights #\n # should be initialized from a Gaussian with standard deviation equal to #\n # weight_scale, and biases should be initialized to zero. All weights and #\n # biases should be stored in the dictionary self.params, with first layer #\n # weights and biases using the keys 'W1' and 'b1' and second layer weights #\n # and biases using the keys 'W2' and 'b2'. #\n ############################################################################\n pass\n self.params['W1'] = weight_scale * np.random.randn(input_dim, hidden_dim)\n self.params['b1'] = np.zeros(hidden_dim)\n self.params['W2'] = weight_scale * np.random.randn(hidden_dim, num_classes)\n self.params['b2'] = np.zeros(num_classes)\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n\n def loss(self, X, y=None):\n \"\"\"\n Compute loss and gradient for a minibatch of data.\n\n Inputs:\n - X: Array of input data of shape (N, d_1, ..., d_k)\n - y: Array of labels, of shape (N,). y[i] gives the label for X[i].\n\n Returns:\n If y is None, then run a test-time forward pass of the model and return:\n - scores: Array of shape (N, C) giving classification scores, where\n scores[i, c] is the classification score for X[i] and class c.\n\n If y is not None, then run a training-time forward and backward pass and\n return a tuple of:\n - loss: Scalar value giving the loss\n - grads: Dictionary with the same keys as self.params, mapping parameter\n names to gradients of the loss with respect to those parameters.\n \"\"\"\n scores = None\n \n ############################################################################\n # TODO: Implement the forward pass for the two-layer net, computing the #\n # class scores for X and storing them in the scores variable. #\n ############################################################################\n W1, W2 = self.params['W1'], self.params['W2']\n b1, b2 = self.params['b1'], self.params['b2']\n \n out_h, cache_h = affine_relu_forward(X, W1, b1)\n scores, cache_s = affine_forward(out_h, W2, b2)\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n # If y is None then we are in test mode so just return scores\n if y is None:\n return scores\n\n loss, grads = 0, {}\n ############################################################################\n # TODO: Implement the backward pass for the two-layer net. Store the loss #\n # in the loss variable and gradients in the grads dictionary. Compute data #\n # loss using softmax, and make sure that grads[k] holds the gradients for #\n # self.params[k]. Don't forget to add L2 regularization! #\n # #\n # NOTE: To ensure that your implementation matches ours and you pass the #\n # automated tests, make sure that your L2 regularization includes a factor #\n # of 0.5 to simplify the expression for the gradient. #\n ############################################################################\n # loss value\n loss, d_score = softmax_loss(scores, y)\n loss += 1./2*self.reg*(np.sum(W1*W1)+np.sum(W2*W2))\n \n # backpropagation\n d_h, grads['W2'], grads['b2'] = affine_backward(d_score, cache_s)\n _, grads['W1'], grads['b1'] = affine_relu_backward(d_h, cache_h) \n\n # regularization\n grads['W2'] += self.reg * W2 \n grads['W1'] += self.reg * W1\n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n return loss, grads\n\n\nclass FullyConnectedNet(object):\n \"\"\"\n A fully-connected neural network with an arbitrary number of hidden layers,\n ReLU nonlinearities, and a softmax loss function. This will also implement\n dropout and batch normalization as options. For a network with L layers,\n the architecture will be\n\n {affine - [batch norm] - relu - [dropout]} x (L - 1) - affine - softmax\n\n where batch normalization and dropout are optional, and the {...} block is\n repeated L - 1 times.\n\n Similar to the TwoLayerNet above, learnable parameters are stored in the\n self.params dictionary and will be learned using the Solver class.\n \"\"\"\n\n def __init__(self, hidden_dims, input_dim=3*32*32, num_classes=10,\n dropout=0, use_batchnorm=False, reg=0.0,\n weight_scale=1e-2, dtype=np.float32, seed=None):\n \"\"\"\n Initialize a new FullyConnectedNet.\n\n Inputs:\n - hidden_dims: A list of integers giving the size of each hidden layer.\n - input_dim: An integer giving the size of the input.\n - num_classes: An integer giving the number of classes to classify.\n - dropout: Scalar between 0 and 1 giving dropout strength. If dropout=0 then\n the network should not use dropout at all.\n - use_batchnorm: Whether or not the network should use batch normalization.\n - reg: Scalar giving L2 regularization strength.\n - weight_scale: Scalar giving the standard deviation for random\n initialization of the weights.\n - dtype: A numpy datatype object; all computations will be performed using\n this datatype. float32 is faster but less accurate, so you should use\n float64 for numeric gradient checking.\n - seed: If not None, then pass this random seed to the dropout layers. This\n will make the dropout layers deteriminstic so we can gradient check the\n model.\n \"\"\"\n self.use_batchnorm = use_batchnorm\n self.use_dropout = dropout > 0\n self.reg = reg\n self.num_layers = 1 + len(hidden_dims)\n self.dtype = dtype\n self.params = {}\n\n ############################################################################\n # TODO: Initialize the parameters of the network, storing all values in #\n # the self.params dictionary. Store weights and biases for the first layer #\n # in W1 and b1; for the second layer use W2 and b2, etc. Weights should be #\n # initialized from a normal distribution with standard deviation equal to #\n # weight_scale and biases should be initialized to zero. #\n # #\n # When using batch normalization, store scale and shift parameters for the #\n # first layer in gamma1 and beta1; for the second layer use gamma2 and #\n # beta2, etc. Scale parameters should be initialized to one and shift #\n # parameters should be initialized to zero. #\n ############################################################################\n self.affine_cache = {}\n self.relu_cache = {}\n self.dropout_cache = {}\n self.hidden_layer_values = {}\n self.hidden_layer_grads = {}\n \n for l in range(1, self.num_layers+1):\n W_name, b_name = 'W' + str(l), 'b' + str(l)\n \n prev_layer_dim = (input_dim if l==1 else hidden_dims[l-2])\n current_layer_dim = (num_classes if l == self.num_layers else hidden_dims[l-1])\n \n self.params[W_name] = weight_scale * np.random.randn(prev_layer_dim, current_layer_dim)\n self.params[b_name] = np.zeros(current_layer_dim)\n \n if use_batchnorm and l != self.num_layers:\n gamma_name, beta_name = 'gamma' + str(l), 'beta' + str(l)\n self.params[gamma_name] = np.ones(current_layer_dim)\n self.params[beta_name] = np.zeros(current_layer_dim)\n \n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n # When using dropout we need to pass a dropout_param dictionary to each\n # dropout layer so that the layer knows the dropout probability and the mode\n # (train / test). You can pass the same dropout_param to each dropout layer.\n self.dropout_param = {}\n if self.use_dropout:\n self.dropout_param = {'mode': 'train', 'p': dropout}\n if seed is not None:\n self.dropout_param['seed'] = seed\n\n # With batch normalization we need to keep track of running means and\n # variances, so we need to pass a special bn_param object to each batch\n # normalization layer. You should pass self.bn_params[0] to the forward pass\n # of the first batch normalization layer, self.bn_params[1] to the forward\n # pass of the second batch normalization layer, etc.\n self.bn_params = []\n if self.use_batchnorm:\n self.bn_params = [{'mode': 'train'} for i in range(self.num_layers - 1)]\n\n # Cast all parameters to the correct datatype\n for k, v in self.params.items():\n self.params[k] = v.astype(dtype)\n\n\n def loss(self, X, y=None):\n \"\"\"\n Compute loss and gradient for the fully-connected net.\n\n Input / output: Same as TwoLayerNet above.\n \"\"\"\n X = X.astype(self.dtype)\n mode = 'test' if y is None else 'train'\n\n # Set train/test mode for batchnorm params and dropout param since they\n # behave differently during training and testing.\n if self.use_dropout:\n self.dropout_param['mode'] = mode\n if self.use_batchnorm:\n for bn_param in self.bn_params:\n bn_param['mode'] = mode\n\n scores = None\n ############################################################################\n # TODO: Implement the forward pass for the fully-connected net, computing #\n # the class scores for X and storing them in the scores variable. #\n # #\n # When using dropout, you'll need to pass self.dropout_param to each #\n # dropout forward pass. #\n # #\n # When using batch normalization, you'll need to pass self.bn_params[0] to #\n # the forward pass for the first batch normalization layer, pass #\n # self.bn_params[1] to the forward pass for the second batch normalization #\n # layer, etc. #\n ############################################################################\n for l in range(1, self.num_layers + 1):\n W_name, b_name, input_name, output_name, gamma_name, beta_name \\\n = 'W' + str(l), 'b' + str(l), 'h' + str(l-1), 'h' + str(l), 'gamma' + str(l), 'beta' + str(l)\n \n W, b = self.params[W_name], self.params[b_name]\n \n i_value = (self.hidden_layer_values[input_name] if l!=1 else X)\n \n # hidden layers\n if l != self.num_layers:\n \n # affine forward\n self.hidden_layer_values[output_name], self.affine_cache[output_name] = affine_forward(i_value, W, b)\n\n # batch norm forward\n if self.use_batchnorm:\n bn_param = {'mode': 'train'}\n gamma = self.params[gamma_name]\n beta = self.params[beta_name]\n self.hidden_layer_values[output_name], self.bn_params[l-1] =\\\n batchnorm_forward(self.hidden_layer_values[output_name], gamma, beta, bn_param)\n \n # ReLU forward\n self.hidden_layer_values[output_name], self.relu_cache[output_name] = relu_forward(self.hidden_layer_values[output_name])\n\n # dropout\n if self.use_dropout:\n self.hidden_layer_values[output_name], self.dropout_cache[output_name] =\\\n dropout_forward(self.hidden_layer_values[output_name], self.dropout_param)\n \n # output layer \n else:\n scores, self.affine_cache[output_name] = affine_forward(i_value, W, b) \n \n \n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n # If test mode return early\n if mode == 'test':\n return scores\n\n loss, grads = 0.0, {}\n ############################################################################\n # TODO: Implement the backward pass for the fully-connected net. Store the #\n # loss in the loss variable and gradients in the grads dictionary. Compute #\n # data loss using softmax, and make sure that grads[k] holds the gradients #\n # for self.params[k]. Don't forget to add L2 regularization! #\n # #\n # When using batch normalization, you don't need to regularize the scale #\n # and shift parameters. #\n # #\n # NOTE: To ensure that your implementation matches ours and you pass the #\n # automated tests, make sure that your L2 regularization includes a factor #\n # of 0.5 to simplify the expression for the gradient. #\n ############################################################################\n # primitive loss value\n loss, d_score = softmax_loss(scores, y) \n #import pdb\n #pdb.set_trace()\n \n # iterate from the output layer to the input layer\n for l in range(self.num_layers, 0, -1):\n \n W_name, b_name, input_name, output_name, gamma_name, beta_name \\\n = 'W' + str(l), 'b' + str(l), 'h' + str(l-1), 'h' + str(l), 'gamma' + str(l), 'beta' + str(l)\n \n # loss value with regularization\n loss += 1./2*self.reg*(np.sum(self.params[W_name]*self.params[W_name]))\n \n # backpropagation - output layer\n if l == self.num_layers:\n self.hidden_layer_grads[input_name], grads[W_name], grads[b_name] =\\\n affine_backward(d_score, self.affine_cache[output_name])\n # backpropagation - hidden layers\n else:\n self.hidden_layer_grads[input_name] = self.hidden_layer_grads[output_name]\n \n # dropout\n if self.use_dropout:\n self.hidden_layer_grads[input_name] =\\\n dropout_backward(self.hidden_layer_grads[input_name], self.dropout_cache[output_name])\n \n # ReLU\n self.hidden_layer_grads[input_name] = relu_backward(self.hidden_layer_grads[input_name], self.relu_cache[output_name]) \n \n # batch norm\n if self.use_batchnorm: \n bn_cache = self.bn_params[l-1] \n self.hidden_layer_grads[input_name], grads[gamma_name], grads[beta_name] =\\\n batchnorm_backward(self.hidden_layer_grads[input_name], bn_cache) \n \n # affine\n self.hidden_layer_grads[input_name], grads[W_name], grads[b_name] =\\\n affine_backward(self.hidden_layer_grads[input_name], self.affine_cache[output_name])\n \n\n # regularization\n grads[W_name] += self.reg * self.params[W_name]\n \n ############################################################################\n # END OF YOUR CODE #\n ############################################################################\n\n return loss, grads\n"
]
| [
[
"numpy.random.randn",
"numpy.zeros",
"numpy.sum",
"numpy.ones"
]
]
|
astoc/kaggle_dsb2017 | [
"2421442cb220518d9ad70b0f3f7611ccf6303af4"
]
| [
"code/Andre/py/iseg_luna3_lub_222f.py"
]
| [
"\"\"\"\nCreated on Thu Jan 26 17:04:11 2017\n\nPreprocess Luna datasets and create nodule masks (and/or blank subsets)\n\nNOTE that:\n 1. we do NOT segment the lungs at all -- we will use the raw images for training (DO_NOT_SEGMENT = True)\n 2. No corrections are made to the nodule radius in relation to the thickness of the layers (radius = (ca[4])/2, simply)\n \n@author: Andre Stochniol, [email protected]\nSome functions have reused from the respective examples/kernels openly published at the https://www.kaggle.com/arnavkj95/data-science-bowl-2017/ , as referenced within the file\n\"\"\"\n\n#%matplotlib inline\n\nimport matplotlib.pyplot as plt\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport scipy.ndimage as ndimage\n\nimport scipy.ndimage # added for scaling\\\n\nimport cv2\nimport time\nimport glob\n\n\nfrom skimage import measure, morphology, segmentation\nimport SimpleITK as sitk\n\nDO_NOT_SEGMENT = True #### major difference with the initial/Feb version\nRESIZE_SPACING = [2,2,2] \n### z, y, x (x & y MUST be the same)\n\n\nluna_subset = 0 # initial \nLUNA_BASE_DIR = \"../luna/data/original_lungs/subset%s/\" # added on AWS; data as well \nLUNA_DIR = LUNA_BASE_DIR % luna_subset\nCSVFILES = \"../luna/data/original_lungs/CSVFILES/%s\"\nLUNA_ANNOTATIONS = CSVFILES % \"annotations.csv\"\nLUNA_CANDIDATES = CSVFILES % \"candidates.csv\"\n\n \nMARKER_INTERNAL_THRESH = -400 # was -400; maybe use -320 ??\nMARKER_FRAME_WIDTH = 9 # 9 seems OK for the half special case ...\ndef generate_markers(image):\n #Creation of the internal Marker\n \n useTestPlot = False\n if useTestPlot:\n timg = image\n plt.imshow(timg, cmap='gray')\n plt.show()\n\n add_frame_vertical = True # NOT a good idea; no added value\n if add_frame_vertical: # add frame for potentially closing the lungs that touch the edge, but only vertically\n \n fw = MARKER_FRAME_WIDTH # frame width (it looks that 2 is the minimum width for the algorithms implemented here, namely the first 2 operations for the marker_internal)\n \n xdim = image.shape[1]\n #ydim = image.shape[0]\n img2 = np.copy(image)\n \n \n img2 [:, 0] = -1024\n img2 [:, 1:fw] = 0\n\n img2 [:, xdim-1:xdim] = -1024\n img2 [:, xdim-fw:xdim-1] = 0 \n marker_internal = img2 < MARKER_INTERNAL_THRESH \n else:\n marker_internal = image < MARKER_INTERNAL_THRESH # was -400\n \n useTestPlot = False\n if useTestPlot:\n timg = marker_internal\n plt.imshow(timg, cmap='gray')\n plt.show() \n \n correct_edges2 = False ## NOT a good idea - no added value\n if correct_edges2: \n marker_internal[0,:] = 0\n marker_internal[:,0] = 0\n #marker_internal[:,1] = True\n #marker_internal[:,2] = True\n marker_internal[511,:] = 0\n marker_internal[:,511] = 0\n \n marker_internal = segmentation.clear_border(marker_internal, buffer_size=0)\n marker_internal_labels = measure.label(marker_internal)\n areas = [r.area for r in measure.regionprops(marker_internal_labels)]\n areas.sort()\n if len(areas) > 2:\n for region in measure.regionprops(marker_internal_labels):\n if region.area < areas[-2]:\n for coordinates in region.coords: \n marker_internal_labels[coordinates[0], coordinates[1]] = 0\n marker_internal = marker_internal_labels > 0\n #Creation of the external Marker\n external_a = ndimage.binary_dilation(marker_internal, iterations=10) # was 10\n external_b = ndimage.binary_dilation(marker_internal, iterations=55) # was 55 \n marker_external = external_b ^ external_a\n #Creation of the Watershed Marker matrix\n #marker_watershed = np.zeros((512, 512), dtype=np.int) # origi\n marker_watershed = np.zeros((marker_external.shape), dtype=np.int)\n \n marker_watershed += marker_internal * 255\n marker_watershed += marker_external * 128\n \n return marker_internal, marker_external, marker_watershed\n\n\ndef generate_markers_3d(image):\n #Creation of the internal Marker\n marker_internal = image < -400\n marker_internal_labels = np.zeros(image.shape).astype(np.int16)\n for i in range(marker_internal.shape[0]):\n marker_internal[i] = segmentation.clear_border(marker_internal[i])\n marker_internal_labels[i] = measure.label(marker_internal[i])\n #areas = [r.area for r in measure.regionprops(marker_internal_labels)]\n areas = [r.area for i in range(marker_internal.shape[0]) for r in measure.regionprops(marker_internal_labels[i])]\n for i in range(marker_internal.shape[0]):\n areas = [r.area for r in measure.regionprops(marker_internal_labels[i])]\n areas.sort()\n if len(areas) > 2:\n for region in measure.regionprops(marker_internal_labels[i]):\n if region.area < areas[-2]:\n for coordinates in region.coords: \n marker_internal_labels[i, coordinates[0], coordinates[1]] = 0\n marker_internal = marker_internal_labels > 0\n #Creation of the external Marker\n \n # 3x3 structuring element with connectivity 1, used by default\n struct1 = ndimage.generate_binary_structure(2, 1)\n struct1 = struct1[np.newaxis,:,:] # expand by z axis .\n \n external_a = ndimage.binary_dilation(marker_internal, structure=struct1, iterations=10)\n external_b = ndimage.binary_dilation(marker_internal, structure=struct1, iterations=55)\n marker_external = external_b ^ external_a\n #Creation of the Watershed Marker matrix\n #marker_watershed = np.zeros((512, 512), dtype=np.int) # origi\n marker_watershed = np.zeros((marker_external.shape), dtype=np.int)\n \n marker_watershed += marker_internal * 255\n marker_watershed += marker_external * 128\n \n return marker_internal, marker_external, marker_watershed\n\n\n\nBINARY_CLOSING_SIZE = 7 ## added for tests; 5 for disk seems sufficient - fo safety let's go with 6 or even 7\ndef seperate_lungs(image):\n #Creation of the markers as shown above:\n marker_internal, marker_external, marker_watershed = generate_markers(image)\n \n #Creation of the Sobel-Gradient\n sobel_filtered_dx = ndimage.sobel(image, 1)\n sobel_filtered_dy = ndimage.sobel(image, 0)\n sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)\n sobel_gradient *= 255.0 / np.max(sobel_gradient)\n \n #Watershed algorithm\n watershed = morphology.watershed(sobel_gradient, marker_watershed)\n \n #Reducing the image created by the Watershed algorithm to its outline\n outline = ndimage.morphological_gradient(watershed, size=(3,3))\n outline = outline.astype(bool)\n \n #Performing Black-Tophat Morphology for reinclusion\n #Creation of the disk-kernel and increasing its size a bit\n blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [0, 1, 1, 1, 1, 1, 0],\n [0, 0, 1, 1, 1, 0, 0]]\n blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)\n #Perform the Black-Hat\n outline += ndimage.black_tophat(outline, structure=blackhat_struct)\n \n #Use the internal marker and the Outline that was just created to generate the lungfilter\n lungfilter = np.bitwise_or(marker_internal, outline)\n #Close holes in the lungfilter\n #fill_holes is not used here, since in some slices the heart would be reincluded by accident\n ##structure = np.ones((BINARY_CLOSING_SIZE,BINARY_CLOSING_SIZE)) # 5 is not enough, 7 is\n structure = morphology.disk(BINARY_CLOSING_SIZE) # better , 5 seems sufficient, we use 7 for safety/just in case\n lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=structure, iterations=3) #, iterations=3) # was structure=np.ones((5,5))\n ### NOTE if no iterattions, i.e. default 1 we get holes within lungs for the disk(5) and perhaps more\n \n #Apply the lungfilter (note the filtered areas being assigned -2000 HU)\n segmented = np.where(lungfilter == 1, image, -2000*np.ones((512, 512))) ### was -2000\n \n return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed\n\ndef rescale_n(n,reduce_factor):\n return max( 1, int(round(n / reduce_factor)))\n\n#image = image_slices[70]\ndef seperate_lungs_cv2(image):\n #Creation of the markers as shown above:\n marker_internal, marker_external, marker_watershed = generate_markers(image)\n reduce_factor = 512 / image.shape[0]\n \n #Creation of the Sobel-Gradient\n sobel_filtered_dx = ndimage.sobel(image, 1)\n sobel_filtered_dy = ndimage.sobel(image, 0)\n sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)\n sobel_gradient *= 255.0 / np.max(sobel_gradient) \n \n useTestPlot = False\n if useTestPlot:\n timg = sobel_gradient\n plt.imshow(timg, cmap='gray')\n plt.show()\n\n #Watershed algorithm\n watershed = morphology.watershed(sobel_gradient, marker_watershed)\n \n if useTestPlot:\n timg = marker_external\n plt.imshow(timg, cmap='gray')\n plt.show() \n \n #Reducing the image created by the Watershed algorithm to its outline\n #wsize = rescale_n(3,reduce_factor) # THIS IS TOO SMALL, dynamically adjusting the size for the watersehed algorithm\n outline = ndimage.morphological_gradient(watershed, size=(3,3)) # original (3,3), (wsize, wsize) is too small to create an outline\n outline = outline.astype(bool)\n outline_u = outline.astype(np.uint8) #added\n \n #Performing Black-Tophat Morphology for reinclusion\n #Creation of the disk-kernel and increasing its size a bit\n blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [0, 1, 1, 1, 1, 1, 0],\n [0, 0, 1, 1, 1, 0, 0]]\n \n\n blackhat_struct = ndimage.iterate_structure(blackhat_struct, rescale_n(8,reduce_factor)) # dyanmically adjust the number of iterattions; original was 8\n \n blackhat_struct_cv2 = blackhat_struct.astype(np.uint8)\n #Perform the Black-Hat\n outline += (cv2.morphologyEx(outline_u, cv2.MORPH_BLACKHAT, kernel=blackhat_struct_cv2)).astype(np.bool) # fats\n\n\n if useTestPlot:\n timg = outline\n plt.imshow(timg, cmap='gray')\n plt.show()\n \n\n #Use the internal marker and the Outline that was just created to generate the lungfilter\n lungfilter = np.bitwise_or(marker_internal, outline)\n \n if useTestPlot:\n timg = lungfilter\n plt.imshow(timg, cmap='gray')\n plt.show()\n \n #Close holes in the lungfilter\n #fill_holes is not used here, since in some slices the heart would be reincluded by accident\n ##structure = np.ones((BINARY_CLOSING_SIZE,BINARY_CLOSING_SIZE)) # 5 is not enough, 7 is\n structure2 = morphology.disk(2) # used to fill the gaos/holes close to the border (otherwise the large sttructure would create a gap by the edge)\n structure3 = morphology.disk(rescale_n(BINARY_CLOSING_SIZE,reduce_factor)) # dynanically adjust; better , 5 seems sufficient, we use 7 for safety/just in case\n \n \n ##lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=structure, iterations=3) #, ORIGINAL iterations=3) # was structure=np.ones((5,5))\n lungfilter2 = ndimage.morphology.binary_closing(lungfilter, structure=structure2, iterations=3) # ADDED\n lungfilter3 = ndimage.morphology.binary_closing(lungfilter, structure=structure3, iterations=3)\n lungfilter = np.bitwise_or(lungfilter2, lungfilter3)\n \n ### NOTE if no iterattions, i.e. default 1 we get holes within lungs for the disk(5) and perhaps more\n \n #Apply the lungfilter (note the filtered areas being assigned -2000 HU)\n #image.shape\n #segmented = np.where(lungfilter == 1, image, -2000*np.ones((512, 512)).astype(np.int16)) # was -2000 someone suggested 30\n segmented = np.where(lungfilter == 1, image, -2000*np.ones(image.shape).astype(np.int16)) # was -2000 someone suggested 30\n \n return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed\n\n\n\ndef seperate_lungs_3d(image):\n #Creation of the markers as shown above:\n marker_internal, marker_external, marker_watershed = generate_markers_3d(image)\n \n #Creation of the Sobel-Gradient\n sobel_filtered_dx = ndimage.sobel(image, axis=2)\n sobel_filtered_dy = ndimage.sobel(image, axis=1)\n sobel_gradient = np.hypot(sobel_filtered_dx, sobel_filtered_dy)\n sobel_gradient *= 255.0 / np.max(sobel_gradient)\n \n #Watershed algorithm\n watershed = morphology.watershed(sobel_gradient, marker_watershed)\n \n #Reducing the image created by the Watershed algorithm to its outline\n outline = ndimage.morphological_gradient(watershed, size=(1,3,3))\n outline = outline.astype(bool)\n \n #Performing Black-Tophat Morphology for reinclusion\n #Creation of the disk-kernel and increasing its size a bit\n blackhat_struct = [[0, 0, 1, 1, 1, 0, 0],\n [0, 1, 1, 1, 1, 1, 0],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [1, 1, 1, 1, 1, 1, 1],\n [0, 1, 1, 1, 1, 1, 0],\n [0, 0, 1, 1, 1, 0, 0]]\n \n blackhat_struct = ndimage.iterate_structure(blackhat_struct, 8)\n \n blackhat_struct = blackhat_struct[np.newaxis,:,:]\n #Perform the Black-Hat\n outline += ndimage.black_tophat(outline, structure=blackhat_struct) # very long time\n \n #Use the internal marker and the Outline that was just created to generate the lungfilter\n lungfilter = np.bitwise_or(marker_internal, outline)\n #Close holes in the lungfilter\n #fill_holes is not used here, since in some slices the heart would be reincluded by accident\n ##structure = np.ones((BINARY_CLOSING_SIZE,BINARY_CLOSING_SIZE)) # 5 is not enough, 7 is\n structure = morphology.disk(BINARY_CLOSING_SIZE) # better , 5 seems sufficient, we use 7 for safety/just in case\n structure = structure[np.newaxis,:,:]\n lungfilter = ndimage.morphology.binary_closing(lungfilter, structure=structure, iterations=3) #, iterations=3) # was structure=np.ones((5,5))\n ### NOTE if no iterattions, i.e. default 1 we get holes within lungs for the disk(5) and perhaps more\n \n #Apply the lungfilter (note the filtered areas being assigned -2000 HU)\n segmented = np.where(lungfilter == 1, image, -2000*np.ones(marker_internal.shape))\n \n return segmented, lungfilter, outline, watershed, sobel_gradient, marker_internal, marker_external, marker_watershed\n\ndef get_slice_location(dcm):\n return float(dcm[0x0020, 0x1041].value)\n\ndef thru_plane_position(dcm):\n \"\"\"Gets spatial coordinate of image origin whose axis\n is perpendicular to image plane.\n \"\"\"\n orientation = tuple((float(o) for o in dcm.ImageOrientationPatient))\n position = tuple((float(p) for p in dcm.ImagePositionPatient))\n rowvec, colvec = orientation[:3], orientation[3:]\n normal_vector = np.cross(rowvec, colvec)\n slice_pos = np.dot(position, normal_vector)\n return slice_pos\n \ndef resample(image, scan, new_spacing=[1,1,1]):\n # Determine current pixel spacing\n spacing = map(float, ([scan[0].SliceThickness] + scan[0].PixelSpacing))\n spacing = np.array(list(spacing))\n \n #scan[2].SliceThickness\n\n\n resize_factor = spacing / new_spacing\n new_real_shape = image.shape * resize_factor\n new_shape = np.round(new_real_shape)\n real_resize_factor = new_shape / image.shape\n new_spacing = spacing / real_resize_factor\n \n #image = scipy.ndimage.interpolation.zoom(image, real_resize_factor) # nor mode= \"wrap\"/xxx, nor cval=-1024 can ensure that the min and max values are unchanged .... # cval added\n image = scipy.ndimage.interpolation.zoom(image, real_resize_factor, mode='nearest') ### early orig modified \n #image = scipy.ndimage.zoom(image, real_resize_factor, order=1) # order=1 bilinear , preserves the min and max of the image -- pronbably better for us (also faster than spkine/order=2)\n \n #image = scipy.ndimage.zoom(image, real_resize_factor, mode='nearest', order=1) # order=1 bilinear , preserves the min and max of the image -- pronbably better for us (also faster than spkine/order=2)\n \n return image, new_spacing\n\ndef segment_one(image_slices):\n \n useTestPlot = False\n if useTestPlot:\n print(\"Shape before segmenting\\t\", image_slices.shape)\n plt.hist(image_slices.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n \n shape = image_slices.shape\n l_segmented = np.zeros(shape).astype(np.int16)\n l_lungfilter = np.zeros(shape).astype(np.bool)\n l_outline = np.zeros(shape).astype(np.bool)\n l_watershed = np.zeros(shape).astype(np.int16)\n l_sobel_gradient = np.zeros(shape).astype(np.float32)\n l_marker_internal = np.zeros(shape).astype(np.bool)\n l_marker_external = np.zeros(shape).astype(np.bool)\n l_marker_watershed = np.zeros(shape).astype(np.int16) \n \n i=0\n for i in range(shape[0]):\n l_segmented[i], l_lungfilter[i], l_outline[i], l_watershed[i], l_sobel_gradient[i], l_marker_internal[i], l_marker_external[i], l_marker_watershed[i] = seperate_lungs_cv2(image_slices[i])\n \n \n if useTestPlot:\n plt.hist(image_slices.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n \n \n plt.hist(l_segmented.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n \n img_sel_i = shape[0] // 2\n # Show some slice in the middle\n plt.imshow(image_slices[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n \n # Show some slice in the middle\n plt.imshow(l_segmented[img_sel_i], cmap='gray')\n plt.show()\n\n mask = l_lungfilter.astype(np.int8)\n \n regions = measure.regionprops(mask) # this measures the largest region and may lead to incorrect results when the mask is not the largest region !!!\n\n \n bb = regions[0].bbox\n #print(bb)\n zlen = bb[3] - bb[0]\n ylen = bb[4] - bb[1]\n xlen = bb[5] - bb[2]\n \n dx = 0 \n ## have to reduce dx to 0 as for instance at least one image of the lungs stretch right to the border even without cropping \n ## namely for '../input/stage1/be57c648eb683a31e8499e278a89c5a0'\n \n crop_max_ratio_z = 0.6 # 0.8 is to big make_submit2(45, 1)\n crop_max_ratio_y = 0.4\n crop_max_ratio_x = 0.6\n \n bxy_min = np.min(bb[1:3]) \n bxy_max = np.max(bb[4:6])\n mask_shape= mask.shape\n image_shape = l_segmented.shape\n \n mask_volume = zlen*ylen*zlen /(mask_shape[0] * mask_shape[1] * mask_shape[2])\n mask_volume_thresh = 0.08 # anything below is too small (maybe just one half of the lung or something very small0)\n mask_volume_check = mask_volume > mask_volume_thresh\n # print (\"Mask Volume: \", mask_volume ) \n \n ### DO NOT allow the mask to touch x & y ---> if it does it is likely a wrong one as for:\n ## folders[3] , path = '../input/stage1/9ba5fbcccfbc9e08edcfe2258ddf7\n \n #maskOK = False\n if bxy_min >0 and bxy_max < 512 and mask_volume_check and zlen/mask_shape[0] > crop_max_ratio_z and ylen/mask_shape[1] > crop_max_ratio_y and xlen/mask_shape[2] > crop_max_ratio_x:\n # mask OK< crop the image and mask\n ### full crop\n #image = image[bb[0]:bb[3], bb[1]:bb[4], bb[2]:bb[5]]\n #mask = mask[bb[0]:bb[3], bb[1]:bb[4], bb[2]:bb[5]]\n \n ## square crop and at least dx elements on both sides on x & y\n bxy_min = np.min(bb[1:3]) \n bxy_max = np.max(bb[4:6])\n \n if bxy_min == 0 or bxy_max == 512:\n # Mask to bigg, auto-correct\n print(\"The following mask likely too big, autoreducing by:\", dx)\n \n bxy_min = np.max((bxy_min, dx)) \n bxy_max = np.min ((bxy_max, mask_shape[1] - dx))\n \n image = l_segmented[bb[0]:bb[3], bxy_min:bxy_max, bxy_min:bxy_max]\n mask = mask[bb[0]:bb[3], bxy_min:bxy_max, bxy_min:bxy_max]\n #maskOK = True\n \n print (\"Shape, cropped, bbox \", mask_shape, mask.shape, bb)\n\n elif bxy_min> 0 and bxy_max < 512 and mask_volume_check and zlen/mask.shape[0] > crop_max_ratio_z:\n ## cut on z at least\n \n image = l_segmented[bb[0]:bb[3], dx: image_shape[1] - dx, dx: image_shape[2] - dx]\n #mask = mask[bb[0]:bb[3], dx: mask_shape[1] - dx, dx: mask_shape[2] - dx]\n print(\"Mask too small, NOT auto-cropping x-y: shape, cropped, bbox, ratios, violume:\", mask_shape, image.shape, bb, zlen/mask_shape[0], ylen/mask_shape[1], xlen/mask_shape[2], mask_volume)\n\n\n else:\n image = l_segmented[0:mask_shape[0], dx: image_shape[1] - dx, dx: image_shape[2] - dx]\n #mask = mask[0:mask_shape[0], dx: mask_shape[1] - dx, dx: mask_shape[2] - dx]\n print(\"Mask wrong, NOT auto-cropping: shape, cropped, bbox, ratios, volume:\", mask_shape, image.shape, bb, zlen/mask_shape[0], ylen/mask_shape[1], xlen/mask_shape[2], mask_volume)\n \n \n useSummaryPlot = True\n if useSummaryPlot:\n \n img_sel_i = shape[0] // 2\n # Show some slice in the middle\n plt.imshow(l_segmented[img_sel_i], cmap='gray')\n plt.show()\n \n return l_segmented, image\n\n\n# the following 3 functions to read LUNA files are from: https://www.kaggle.com/arnavkj95/data-science-bowl-2017/candidate-generation-and-luna16-preprocessing/notebook\n'''\nThis funciton reads a '.mhd' file using SimpleITK and return the image array, \norigin and spacing of the image.\n'''\ndef load_itk(filename):\n # Reads the image using SimpleITK\n itkimage = sitk.ReadImage(filename)\n \n # Convert the image to a numpy array first and then shuffle the dimensions to get axis in the order z,y,x\n ct_scan = sitk.GetArrayFromImage(itkimage)\n \n # Read the origin of the ct_scan, will be used to convert the coordinates from world to voxel and vice versa.\n origin = np.array(list(reversed(itkimage.GetOrigin())))\n \n # Read the spacing along each dimension\n spacing = np.array(list(reversed(itkimage.GetSpacing())))\n \n return ct_scan, origin, spacing\n\n'''\nThis function is used to convert the world coordinates to voxel coordinates using \nthe origin and spacing of the ct_scan\n'''\ndef world_2_voxel(world_coordinates, origin, spacing):\n stretched_voxel_coordinates = np.absolute(world_coordinates - origin)\n voxel_coordinates = stretched_voxel_coordinates / spacing\n return voxel_coordinates\n\n'''\nThis function is used to convert the voxel coordinates to world coordinates using \nthe origin and spacing of the ct_scan.\n'''\ndef voxel_2_world(voxel_coordinates, origin, spacing):\n stretched_voxel_coordinates = voxel_coordinates * spacing\n world_coordinates = stretched_voxel_coordinates + origin\n return world_coordinates\n\ndef seq(start, stop, step=1):\n\tn = int(round((stop - start)/float(step)))\n\tif n > 1:\n\t\treturn([start + step*i for i in range(n+1)])\n\telse:\n\t\treturn([])\n\n'''\nThis function is used to create spherical regions in binary masks\nat the given locations and radius.\n'''\n\n\ndef draw_circles(image,cands,origin,spacing): \n\t#make empty matrix, which will be filled with the mask\n\timage_mask = np.zeros(image.shape, dtype=np.int16)\n\n\t#run over all the nodules in the lungs\n\tfor ca in cands.values:\n\t\tradius = (ca[4])/2 # VERSION iseg_luna3 - DO NOT CORRECT the radiius in ANY way ...!!\n \n\t\tcoord_x = ca[1]\n\t\tcoord_y = ca[2]\n\t\tcoord_z = ca[3]\n\t\timage_coord = np.array((coord_z,coord_y,coord_x))\n\n\t\t#determine voxel coordinate given the worldcoordinate\n\t\timage_coord = world_2_voxel(image_coord,origin,spacing)\n\n\t\t#determine the range of the nodule\n\t\t#noduleRange = seq(-radius, radius, RESIZE_SPACING[0]) # original, uniform spacing \n\t\tnoduleRange_z = seq(-radius, radius, spacing[0])\n\t\tnoduleRange_y = seq(-radius, radius, spacing[1])\n\t\tnoduleRange_x = seq(-radius, radius, spacing[2])\n\n\t\t#create the mask\n\t\tfor x in noduleRange_x:\n\t\t\tfor y in noduleRange_y:\n\t\t\t\tfor z in noduleRange_z:\n\t\t\t\t\tcoords = world_2_voxel(np.array((coord_z+z,coord_y+y,coord_x+x)),origin,spacing)\n\t\t\t\t\t#if (np.linalg.norm(image_coord-coords) * RESIZE_SPACING[0]) < radius: ### original (constrained to a uniofrm RESIZE)\n\t\t\t\t\tif (np.linalg.norm((image_coord-coords) * spacing)) < radius:\n\t\t\t\t\t\timage_mask[int(np.round(coords[0])),int(np.round(coords[1])),int(np.round(coords[2]))] = int(1)\n\t\n\treturn image_mask\n\n'''\nThis function takes the path to a '.mhd' file as input and \nis used to create the nodule masks and segmented lungs after \nrescaling to 1mm size in all directions. It saved them in the .npz\nformat. It also takes the list of nodule locations in that CT Scan as \ninput.\n'''\n\nluna_subset = 0 # initial \nLUNA_DIR = LUNA_BASE_DIR % luna_subset\n\nfiles = glob.glob(''.join([LUNA_DIR,'*.mhd']))\nfile = files[12] # rough empty set test - if file is empty this would fail; 12th - 3 nodules\nimagePath = file\nseriesuid = file[file.rindex('/')+1:] # everything after the last slash\nseriesuid = seriesuid[:len(seriesuid)-len(\".mhd\")] # cut out the suffix to get the uid\n\nprint (\"Luna annotations (head)\")\nannotations = pd.read_csv(LUNA_ANNOTATIONS)\nannotations.head()\ncands = annotations[seriesuid == annotations.seriesuid] # select the annotations for the current series\nprint (cands)\n\ndef create_nodule_mask(imagePath, cands):\n #if os.path.isfile(imagePath.replace('original',SAVE_FOLDER_image)) == False:\n img, origin, spacing = load_itk(imagePath)\n\n #calculate resize factor\n resize_factor = spacing / RESIZE_SPACING # was [1, 1, 1]\n new_real_shape = img.shape * resize_factor\n new_shape = np.round(new_real_shape)\n real_resize = new_shape / img.shape\n new_spacing = spacing / real_resize \n\t\n start = time.time()\n #resize image \n lung_img = scipy.ndimage.interpolation.zoom(img, real_resize, mode='nearest') # Andre mode added\n if DO_NOT_SEGMENT:\n lung_seg = lung_img\n lung_seg_crop = lung_img\n print(\"Rescale time, and path: \", ((time.time() - start)), imagePath )\n\n else:\n lung_seg, lung_seg_crop = segment_one(lung_img)\n print(\"Rescale & Seg time, and path: \", ((time.time() - start)), imagePath )\n\n useTestPlot = False\n if useTestPlot:\n plt.hist(img.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n \n \n plt.hist(lung_img.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n\n plt.hist(lung_seg.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n \n \n img_sel_i = img.shape[0] // 2\n # Show some slice in the middle\n plt.imshow(img[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n\n img_sel_i = lung_seg.shape[0] // 2\n # Show some slice in the middle\n plt.imshow(lung_seg[img_sel_i], cmap='gray')\n plt.show()\n \n # Show some slice in the middle\n plt.imshow(lung_seg_crop[img_sel_i], cmap='gray')\n plt.show()\n\n\t#create nodule mask\n nodule_mask = draw_circles(lung_img,cands,origin,new_spacing)\n \n if useTestPlot: \n lung_img.shape\n lung_seg.shape\n lung_seg_crop.shape\n nodule_mask.shape\n \n for i in range(nodule_mask.shape[0]):\n print (\"Slice: \", i) \n plt.imshow(nodule_mask[i], cmap='gray')\n plt.show()\n \n \n img_sel_i = 146 # 36\n plt.imshow(lung_seg[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n \n plt.imshow(nodule_mask[img_sel_i], cmap='gray')\n plt.show()\n \n \n for i in range (141, 153):\n print (\"Slice: \", i) \n plt.imshow(lung_seg[i], cmap='gray') \n plt.show()\n #plt.imshow(nodule_mask[i], cmap='gray')\n #plt.show()\n\n w448 = int(448 // RESIZE_SPACING[1]) # we use 448 as this would be not enough just for 3 out of 1595 patients giving the pixels resolution ...:\n #lung_img_448, lung_seg_448, nodule_mask_448 = np.zeros((lung_img.shape[0], w448, w448)), np.zeros((lung_seg.shape[0], w448, w448)), np.zeros((nodule_mask.shape[0], w448, w448))\n lung_img_448 = np.full ((lung_img.shape[0], w448, w448), -2000, dtype=np.int16)\n lung_seg_448 = np.full ((lung_seg.shape[0], w448, w448), -2000, dtype=np.int16)\n nodule_mask_448 = np.zeros((nodule_mask.shape[0], w448, w448), dtype=np.int16)\n\n\n original_shape = lung_img.shape\t\n if (original_shape[1] > w448):\n ## need to crop the image to w448 size ...\n \n print(\"Warning: additional crop from ... to width of: \", original_shape, w448)\n offset = (w448 - original_shape[1])\n \n y_min = abs(offset // 2 ) ## we use the same diff order as for offset below to ensure correct cala of new_origin (if we ever neeed i)\n y_max = y_min + w448\n lung_img = lung_img[:,y_min:y_max,:]\n lung_seg = lung_seg[:,y_min:y_max,:]\n nodule_mask = nodule_mask[:,y_min:y_max,:]\n \n upper_offset = offset// 2\n lower_offset = offset - upper_offset\n \n new_origin = voxel_2_world([-upper_offset,-lower_offset,0],origin,new_spacing)\n origin = new_origin\n original_shape = lung_img.shape\n \n if (original_shape[2] > w448):\n x_min = (original_shape[2] - w448) // 2\n x_max = x_min + w448\n lung_img = lung_img[:,:,x_min:x_max]\n lung_seg = lung_seg[:,:,x_min:x_max]\n nodule_mask = nodule_mask[:,:,x_min:x_max]\n original_shape = lung_img.shape\n \n offset = (w448 - original_shape[1])\n upper_offset = offset// 2\n lower_offset = offset - upper_offset \n new_origin = voxel_2_world([-upper_offset,-lower_offset,0],origin,new_spacing)\n\n if offset > 0: # \n for z in range(lung_img.shape[0]):\n \n ### if new_origin is used check the impact of the above crop for instance for:\n ### path = \"'../luna/original_lungs/subset0/1.3.6.1.4.1.14519.5.2.1.6279.6001.430109407146633213496148200410'\n \n lung_img_448[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = lung_img[z,:,:]\n lung_seg_448[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = lung_seg[z,:,:]\n nodule_mask_448[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = nodule_mask[z,:,:]\n else:\n lung_img_448 = lung_img # equal dimensiona, just copy all (no nee to add the originals withion a frame)\n lung_seg_448 = lung_seg\n nodule_mask_448 = nodule_mask\n \n\n nodule_mask_448_sum = np.sum(nodule_mask_448, axis=0) \n if useTestPlot: \n lung_img_448.shape\n lung_seg_448.shape\n #lung_seg_crop.shape\n nodule_mask_448.shape\n \n img_sel_i = 146 # 36\n \n plt.imshow(lung_img_448[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n \n plt.imshow(lung_seg_448[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n \n plt.imshow(nodule_mask_448[img_sel_i], cmap='gray')\n plt.show()\n \n \n for i in range (141, 153):\n print (\"Slice: \", i) \n plt.imshow(lung_seg_448[i], cmap='gray') \n plt.show()\n #plt.imshow(nodule_mask[i], cmap='gray')\n #plt.show()\n \n useSummaryPlot = True\n if useSummaryPlot:\n mask_sum_mean_x100 = 100 * np.mean(nodule_mask_448_sum) \n \n axis = 1\n lung_projections = []\n mask_projections = []\n for axis in range(3):\n #sxm_projection = np.max(sxm, axis = axis)\n lung_projections.append(np.mean(lung_seg_448, axis=axis))\n mask_projections.append(np.max(nodule_mask_448, axis=axis))\n\n\n \n f, ax = plt.subplots(1, 3, figsize=(15,5))\n ax[0].imshow(lung_projections[0],cmap=plt.cm.gray)\n ax[1].imshow(lung_projections[1],cmap=plt.cm.gray)\n ax[2].imshow(lung_projections[2],cmap=plt.cm.gray)\n plt.show()\n f, ax = plt.subplots(1, 3, figsize=(15,5))\n ax[0].imshow(mask_projections[0],cmap=plt.cm.gray)\n ax[1].imshow(mask_projections[1],cmap=plt.cm.gray)\n ax[2].imshow(mask_projections[2],cmap=plt.cm.gray)\n plt.show()\n \n print (\"Mask_sum_mean_x100: \", mask_sum_mean_x100)\n\n\n\n # save images. \n path = imagePath[:len(imagePath)-len(\".mhd\")] # cut out the suffix to get the uid\n \n if DO_NOT_SEGMENT:\n path_segmented = path.replace(\"original_lungs\", \"lungs_2x2x2\", 1) # data removed from the second part on AWS\n else:\n path_segmented = path.replace(\"original_lungs\", \"segmented_2x2x2\", 1)\n \n if DO_NOT_SEGMENT:\n np.savez_compressed(path_segmented + '_lung', lung_seg_448) \n else:\n np.savez_compressed(path_segmented + '_lung_seg', lung_seg_448)\n \n np.savez_compressed(path_segmented + '_nodule_mask', nodule_mask_448)\n\n return\n\ndef find_lungs_range(y, noise):\n n = len(y)\n mid = n // 2\n \n new_start = 0\n for i in range(mid, 0, -1):\n if y[i] < noise:\n new_start = i\n break\n new_end = n\n for i in range(mid, n, 1):\n if y[i] < noise:\n new_end = i\n break\n return new_start, new_end\n\n\ndef update_nodule_mask_or_blank (imagePath, cands, true_mask=True):\n #if os.path.isfile(imagePath.replace('original',SAVE_FOLDER_image)) == False:\n # load the old one and copy across\n path = imagePath[:len(imagePath)-len(\".mhd\")] # cut out the suffix to get the uid\n \n if DO_NOT_SEGMENT:\n path_segmented = path.replace(\"original_lungs\", \"lungs_2x2x2\", 1)\n \n else:\n path_segmented = path.replace(\"original_lungs\", \"segmented_2x2x2\", 1)\n \n if true_mask:\n # nothing to update reload and copy over\n mask_img_z = np.load(''.join((path_segmented + '_nodule_mask' + '.npz'))) \n nodule_mask_448 = mask_img_z['arr_0']\n print(\"Loading and saving _nodule_mask as _nodule_mask_wblanks for: \", path_segmented) \n \n else:\n \n img, origin, spacing = load_itk(imagePath)\n \n #calculate resize factor\n resize_factor = spacing / RESIZE_SPACING\n new_real_shape = img.shape * resize_factor\n new_shape = np.round(new_real_shape)\n real_resize = new_shape / img.shape\n new_spacing = spacing / real_resize \n \t\n # loading of the image/images to sync with the update -- DOES NOT WORK\n attempt_through_reloading = False ## this has failed\n if attempt_through_reloading:\n if DO_NOT_SEGMENT:\n lung_img_z = np.load(''.join((path_segmented + '_lung' + '.npz'))) \n else:\n lung_img_z = np.load(''.join((path_segmented + '_lung_seg' + '.npz'))) \n \n lung_img = lung_img_z['arr_0']\n \n else:\n ## have to redo the calculations\n start = time.time()\n #resize image \n lung_img = scipy.ndimage.interpolation.zoom(img, real_resize, mode='nearest') # Andre mode added\n if DO_NOT_SEGMENT:\n lung_seg = lung_img\n lung_seg_crop = lung_img\n print(\"Rescale time, and path: \", ((time.time() - start)), imagePath )\n \n else:\n lung_seg, lung_seg_crop = segment_one(lung_img)\n print(\"Rescale & Seg time, and path: \", ((time.time() - start)), imagePath )\n \n \n nodule_mask = draw_circles(lung_img,cands,origin,new_spacing)\n \n if not true_mask:\n nodule_mask = -1 * nodule_mask # mark it as invalid to be zeroed later on (needed to get the blanks)\n \n useTestPlot = False\n if useTestPlot: \n lung_img.shape\n lung_seg.shape\n lung_seg_crop.shape\n nodule_mask.shape\n \n #mask0 = np.load(''.join((path_segmented + '_module_mask' + '.npz')))\n\n \n for i in range(nodule_mask.shape[0]):\n print (\"Slice: \", i) \n plt.imshow(nodule_mask[i], cmap='gray')\n plt.show()\n \n \n w448 = int(448 // RESIZE_SPACING[1]) # we use 448 as this would be not enough just for 3 out of 1595 patients giving the pixels resolution ...:\n nodule_mask_448 = np.zeros((nodule_mask.shape[0], w448, w448), dtype=np.int16)\n \n \n original_shape = lung_img.shape\t\n if (original_shape[1] > w448):\n ## need to crop the image to w448 size ...\n \n print(\"Warning: additional crop from ... to width of: \", original_shape, w448)\n offset = (w448 - original_shape[1])\n \n y_min = abs(offset // 2 ) ## we use the same diff order as for offset below to ensure correct calculations of new_origin (if we ever neeed i)\n y_max = y_min + w448\n nodule_mask = nodule_mask[:,y_min:y_max,:]\n \n upper_offset = offset// 2\n lower_offset = offset - upper_offset\n \n new_origin = voxel_2_world([-upper_offset,-lower_offset,0],origin,new_spacing)\n origin = new_origin\n original_shape = lung_img.shape\n \n if (original_shape[2] > w448):\n x_min = (original_shape[2] - w448) // 2\n x_max = x_min + w448\n nodule_mask = nodule_mask[:,:,x_min:x_max]\n original_shape = lung_img.shape\n \n offset = (w448 - original_shape[1])\n upper_offset = offset// 2\n lower_offset = offset - upper_offset \n new_origin = voxel_2_world([-upper_offset,-lower_offset,0],origin,new_spacing)\n \n if offset > 0: # \n for z in range(lung_img.shape[0]):\n \n nodule_mask_448[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = nodule_mask[z,:,:]\n else:\n nodule_mask_448 = nodule_mask\n \n \n nodule_mask_448_sum = np.sum(nodule_mask_448, axis=0)\n \n if useTestPlot: \n nodule_mask_448.shape\n img_sel_i = 146 # 36\n \n plt.imshow(nodule_mask_448[img_sel_i], cmap='gray')\n plt.show()\n \n \n \n useSummaryPlot = False\n if useSummaryPlot:\n mask_sum_mean_x100 = 100 * np.mean(nodule_mask_448_sum) \n count_blanks = np.sum(nodule_mask_448 < 0)\n \n axis = 1\n lung_projections = []\n mask_projections = []\n for axis in range(3):\n #sxm_projection = np.max(sxm, axis = axis)\n #lung_projections.append(np.mean(lung_seg_448, axis=axis))\n mask_projections.append(np.max(nodule_mask_448, axis=axis))\n \n #f, ax = plt.subplots(1, 3, figsize=(15,5))\n #ax[0].imshow(lung_projections[0],cmap=plt.cm.gray)\n #ax[1].imshow(lung_projections[1],cmap=plt.cm.gray)\n #ax[2].imshow(lung_projections[2],cmap=plt.cm.gray)\n #plt.show()\n f, ax = plt.subplots(1, 3, figsize=(15,5))\n ax[0].imshow(mask_projections[0],cmap=plt.cm.gray)\n ax[1].imshow(mask_projections[1],cmap=plt.cm.gray)\n ax[2].imshow(mask_projections[2],cmap=plt.cm.gray)\n plt.show()\n \n print (\"Mask_sum_mean_x100, blanks built-in: \", mask_sum_mean_x100, count_blanks)\n \n np.savez_compressed(path_segmented + '_nodule_mask_wblanks', nodule_mask_448)\n\n return \n\ndef create_nodule_mask_or_blank (imagePath, cands, true_mask=True):\n #if os.path.isfile(imagePath.replace('original',SAVE_FOLDER_image)) == False:\n img, origin, spacing = load_itk(imagePath)\n\n #calculate resize factor\n resize_factor = spacing / RESIZE_SPACING # was [1, 1, 1]\n new_real_shape = img.shape * resize_factor\n new_shape = np.round(new_real_shape)\n real_resize = new_shape / img.shape\n new_spacing = spacing / real_resize \n\t\n start = time.time()\n #resize image \n lung_img = scipy.ndimage.interpolation.zoom(img, real_resize, mode='nearest') # Andre mode added\n if DO_NOT_SEGMENT:\n lung_seg = lung_img\n lung_seg_crop = lung_img\n print(\"Rescale time, and path: \", ((time.time() - start)), imagePath )\n\n else:\n lung_seg, lung_seg_crop = segment_one(lung_img)\n print(\"Rescale & Seg time, and path: \", ((time.time() - start)), imagePath )\n \n useTestPlot = False\n if useTestPlot:\n plt.hist(img.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n \n plt.hist(lung_img.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n\n plt.hist(lung_seg.flatten(), bins=80, color='c')\n plt.xlabel(\"Hounsfield Units (HU)\")\n plt.ylabel(\"Frequency\")\n plt.show()\n \n \n img_sel_i = img.shape[0] // 2\n # Show some slice in the middle\n plt.imshow(img[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n\n\n img_sel_i = lung_img.shape[0] // 2\n # Show some slice in the middle\n plt.imshow(lung_img[img_sel_i], cmap='gray')\n plt.show()\n \n \n # Show some slice in the middle\n plt.imshow(lung_img[:, 4* lung_img.shape[1] // 6], cmap='gray')\n plt.show()\n \n HU_LUNGS_MIN = -900 # the algo is sensitive to this value -- keep it 900 unless retested\n HU_LUNGS_MAX = -400\n jsteps = 10\n for j in range(jsteps):\n # Show some slice in the middle\n \n img_sel_i = j * lung_img.shape[1] // jsteps\n img_cut = lung_img[:, img_sel_i]\n lix = (img_cut > HU_LUNGS_MIN) & (img_cut < HU_LUNGS_MAX)\n lix_y = np.sum(lix, axis=1)\n print (\"Cut & ratio, lix_y (min, mean, max): \", j, j/jsteps, np.min(lix_y),np.mean(lix_y), np.max(lix_y) )\n noise = 3 * np.min(lix_y)\n noise = 0.05 * np.max(lix_y)\n noise = max([3 * np.min(lix_y), 0.05 * np.max(lix_y)])\n print (\"Lungs range: \", find_lungs_range(lix_y, noise))\n \n plt.imshow(img_cut, cmap='gray')\n plt.show()\n \n plt.imshow(lix, cmap='gray')\n plt.show()\n \n plt.plot (lix_y)\n plt.show()\n\n ymin = int(0.4 * lung_img.shape[1])\n ymax = int(0.6 * lung_img.shape[1])\n zmin_new = lung_img.shape[0] // 2\n zmax_new = lung_img.shape[0] // 2\n j = ymin\n for j in range(ymin, ymax+1):\n img_cut = lung_img[:, j]\n img_cut_lungs = (img_cut > HU_LUNGS_MIN) & (img_cut < HU_LUNGS_MAX)\n lungs_across = np.sum(img_cut_lungs, axis = 1)\n #noise_bottom_some = np.mean(lungs_across[0:5])\n noise = np.max([3*np.min(lungs_across), 0.05 * np.max(lungs_across)]) # experimanetal -- could fail is scan has only central part of lungs and no borders at all -- CHECK\n zmin, zmax = find_lungs_range(lungs_across, noise)\n if zmin < zmin_new:\n zmin_new = zmin\n if zmax > zmax_new:\n print (\"j, zmax: \", j, zmax)\n zmax_new = zmax\n \n \n plt.imshow(img_cut, cmap='gray')\n plt.show()\n \n plt.imshow(img_cut_lungs, cmap='gray')\n plt.show()\n \n plt.plot (lungs_across)\n plt.show()\n\n \n HU_LUNGS_MIN = -950\n HU_LUNGS_MAX = -400\n ling = img #lung_img # lung_img # for our testing here\n step = 400\n for HU_LUNGS_MIN in range(-1000, 1000, step):\n HU_LUNGS_MAX = HU_LUNGS_MIN + step\n print (\"HU_LUNGS_MIN, HU_LUNGS_MAX: \", HU_LUNGS_MIN, HU_LUNGS_MAX)\n \n \n lix = (ling > HU_LUNGS_MIN) & (ling < HU_LUNGS_MAX)\n lix_z = np.max(lix, axis=0).astype(np.int16)\n \n plt.imshow(lix_z, cmap='gray')\n plt.show()\n\n HU_LUNGS_MIN = -900\n HU_LUNGS_MAX = -500\n ling = img #lung_img # lung_img # for our testing here\n print (\"HU_LUNGS_MIN, HU_LUNGS_MAX: \", HU_LUNGS_MIN, HU_LUNGS_MAX)\n \n lix = (ling > HU_LUNGS_MIN) & (ling < HU_LUNGS_MAX)\n \n lix_z = np.max(lix, axis=0).astype(np.int16)\n lix_z_x = np.sum(lix_z, axis=0)\n lix_z_y = np.sum(lix_z, axis=1)\n \n plt.imshow(lix_z, cmap='gray')\n plt.show()\n plt.plot (lix_z_x)\n plt.show()\n\n plt.plot (lix_z_y)\n plt.show()\n \n for i in range(0,lung_img.shape[0], 10):\n print(\"section: \", i)\n plt.imshow(lung_img[i], cmap='gray')\n plt.show()\n \n\n img_sel_i = lung_seg.shape[0] // 2\n # Show some slice in the middle\n plt.imshow(lung_seg[img_sel_i], cmap='gray')\n plt.show()\n \n # Show some slice in the middle\n plt.imshow(lung_seg_crop[img_sel_i], cmap='gray')\n plt.show()\n\n\t#create nodule mask\n #cands.diameter_mm = 3.2\n \n nodule_mask = draw_circles(lung_img,cands,origin,new_spacing)\n \n if not true_mask:\n nodule_mask = -1 * nodule_mask # mark it as invalid to be zeroed later on (needed to get the blanks)\n #np.sum(nodule_mask)\n if useTestPlot: \n lung_img.shape\n lung_seg.shape\n lung_seg_crop.shape\n nodule_mask.shape\n \n for i in range(nodule_mask.shape[0]):\n print (\"Slice: \", i) \n plt.imshow(nodule_mask[i], cmap='gray')\n plt.show()\n \n \n img_sel_i = 146 # 36\n plt.imshow(lung_seg[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n \n plt.imshow(nodule_mask[img_sel_i], cmap='gray')\n plt.show()\n \n \n for i in range (141, 153):\n print (\"Slice: \", i) \n plt.imshow(lung_seg[i], cmap='gray') \n plt.show()\n #plt.imshow(nodule_mask[i], cmap='gray')\n #plt.show()\n\n\n\n w448 = int(448 // RESIZE_SPACING[1]) # we use 448 as this would be not enough just for 3 out of 1595 patients giving the pixels resolution ...:\n #lung_img_448, lung_seg_448, nodule_mask_448 = np.zeros((lung_img.shape[0], w448, w448)), np.zeros((lung_seg.shape[0], w448, w448)), np.zeros((nodule_mask.shape[0], w448, w448))\n lung_img_448 = np.full ((lung_img.shape[0], w448, w448), -2000, dtype=np.int16)\n lung_seg_448 = np.full ((lung_seg.shape[0], w448, w448), -2000, dtype=np.int16)\n nodule_mask_448 = np.zeros((nodule_mask.shape[0], w448, w448), dtype=np.int16)\n\n\n original_shape = lung_img.shape\t\n if (original_shape[1] > w448):\n ## need to crop the image to w448 size ...\n \n print(\"Warning: additional crop from ... to width of: \", original_shape, w448)\n offset = (w448 - original_shape[1])\n \n y_min = abs(offset // 2 ) ## we use the same diff order as for offset below to ensure correct cala of new_origin (if we ever neeed i)\n y_max = y_min + w448\n lung_img = lung_img[:,y_min:y_max,:]\n lung_seg = lung_seg[:,y_min:y_max,:]\n nodule_mask = nodule_mask[:,y_min:y_max,:]\n \n upper_offset = offset// 2\n lower_offset = offset - upper_offset\n \n new_origin = voxel_2_world([-upper_offset,-lower_offset,0],origin,new_spacing)\n origin = new_origin\n original_shape = lung_img.shape\n \n if (original_shape[2] > w448):\n x_min = (original_shape[2] - w448) // 2\n x_max = x_min + w448\n lung_img = lung_img[:,:,x_min:x_max]\n lung_seg = lung_seg[:,:,x_min:x_max]\n nodule_mask = nodule_mask[:,:,x_min:x_max]\n original_shape = lung_img.shape\n \n offset = (w448 - original_shape[1])\n upper_offset = offset// 2\n lower_offset = offset - upper_offset \n new_origin = voxel_2_world([-upper_offset,-lower_offset,0],origin,new_spacing)\n\n if offset > 0: # \n for z in range(lung_img.shape[0]):\n \n ### if new_origin is used check the impact of the above crop for instance for:\n ### path = \"'../luna/original_lungs/subset0/1.3.6.1.4.1.14519.5.2.1.6279.6001.430109407146633213496148200410'\n \n lung_img_448[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = lung_img[z,:,:]\n lung_seg_448[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = lung_seg[z,:,:]\n nodule_mask_448[z, upper_offset:-lower_offset,upper_offset:-lower_offset] = nodule_mask[z,:,:]\n else:\n lung_img_448 = lung_img # equal dimensiona, just copy all (no nee to add the originals withion a frame)\n lung_seg_448 = lung_seg\n nodule_mask_448 = nodule_mask\n \n\n nodule_mask_448_sum = np.sum(nodule_mask_448, axis=0)\n #lung_seg_448_mean = np.mean(lung_seg_448, axis=0)\n \n if useTestPlot: \n lung_img_448.shape\n lung_seg_448.shape\n #lung_seg_crop.shape\n nodule_mask_448.shape\n \n \n img_sel_i = 146 # 36\n \n plt.imshow(lung_img_448[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n \n plt.imshow(lung_seg_448[img_sel_i], cmap=plt.cm.gray)\n plt.show()\n \n plt.imshow(nodule_mask_448[img_sel_i], cmap='gray')\n plt.show()\n \n \n for i in range (141, 153):\n print (\"Slice: \", i) \n plt.imshow(lung_seg_448[i], cmap='gray') \n plt.show()\n #plt.imshow(nodule_mask[i], cmap='gray')\n #plt.show()\n \n useSummaryPlot = True\n if useSummaryPlot:\n mask_sum_mean_x100 = 100 * np.mean(nodule_mask_448_sum) \n \n axis = 1\n lung_projections = []\n mask_projections = []\n for axis in range(3):\n #sxm_projection = np.max(sxm, axis = axis)\n lung_projections.append(np.mean(lung_seg_448, axis=axis))\n mask_projections.append(np.max(nodule_mask_448, axis=axis))\n \n f, ax = plt.subplots(1, 3, figsize=(15,5))\n ax[0].imshow(lung_projections[0],cmap=plt.cm.gray)\n ax[1].imshow(lung_projections[1],cmap=plt.cm.gray)\n ax[2].imshow(lung_projections[2],cmap=plt.cm.gray)\n plt.show()\n f, ax = plt.subplots(1, 3, figsize=(15,5))\n ax[0].imshow(mask_projections[0],cmap=plt.cm.gray)\n ax[1].imshow(mask_projections[1],cmap=plt.cm.gray)\n ax[2].imshow(mask_projections[2],cmap=plt.cm.gray)\n plt.show()\n \n print (\"Mask_sum_mean_x100: \", mask_sum_mean_x100)\n\n # save images. \n\n path = imagePath[:len(imagePath)-len(\".mhd\")] # cut out the suffix to get the uid\n \n if DO_NOT_SEGMENT:\n path_segmented = path.replace(\"original_lungs\", \"lungs_2x2x2\", 1)\n else:\n path_segmented = path.replace(\"original_lungs\", \"segmented_2x2x2\", 1)\n \n #np.save(imageName + '_lung_img.npz', lung_img_448)\n if DO_NOT_SEGMENT:\n np.savez_compressed(path_segmented + '_lung', lung_seg_448) \n else:\n np.savez_compressed(path_segmented + '_lung_seg', lung_seg_448)\n \n np.savez_compressed(path_segmented + '_nodule_mask', nodule_mask_448)\n\n return\n \n\ndef create_nodule_mask_subset(luna_subset):\n\n LUNA_DIR = LUNA_BASE_DIR % luna_subset\n files = glob.glob(''.join([LUNA_DIR,'*.mhd']))\n annotations = pd.read_csv(LUNA_ANNOTATIONS)\n annotations.head()\n \n file = \"../luna/original_lungs/subset0/1.3.6.1.4.1.14519.5.2.1.6279.6001.564534197011295112247542153557.mhd\"\n for file in files:\n imagePath = file\n seriesuid = file[file.rindex('/')+1:] # everything after the last slash\n seriesuid = seriesuid[:len(seriesuid)-len(\".mhd\")] # cut out the suffix to get the uid\n \n cands = annotations[seriesuid == annotations.seriesuid] # select the annotations for the current series\n #print (cands)\n create_nodule_mask (imagePath, cands)\n\ndef create_nodule_mask_or_blank_subset(luna_subset, create_wblanks_mask_only=False):\n\n LUNA_DIR = LUNA_BASE_DIR % luna_subset\n files = glob.glob(''.join([LUNA_DIR,'*.mhd']))\n annotations = pd.read_csv(LUNA_ANNOTATIONS)\n annotations.head()\n \n candidates = pd.read_csv(LUNA_CANDIDATES)\n print (\"Luna subset(s) and candidates count: \", (luna_subset, len(candidates)))\n candidates_false = pd.DataFrame(candidates[candidates[\"class\"] == 0]) # only select the false candidates\n candidates_true = candidates[candidates[\"class\"] == 1] # only select the false candidates\n print (\"False & true candidates: \", len(candidates_false), len(candidates_true))\n #candidates.head()\n \n use_all_blanks = True\n if use_all_blanks:\n aggregatez = 1 # from version unseg_blanks\n else: # orginal aggregation\n aggregatez = int(4 * RESIZE_SPACING[0]) # originally it was 4 -- for tjhe blanks version do NOT aggregate by Z\n candidates_false[\"coordZ_8\"] = candidates_false[\"coordZ\"].round(0) // aggregatez * aggregatez\n\n \n file = \"../luna/original_lungs/subset0/1.3.6.1.4.1.14519.5.2.1.6279.6001.564534197011295112247542153557.mhd\"\n for file in files:\n imagePath = file\n seriesuid = file[file.rindex('/')+1:] # everything after the last slash\n seriesuid = seriesuid[:len(seriesuid)-len(\".mhd\")] # cut out the suffix to get the uid\n \n cands = annotations[seriesuid == annotations.seriesuid] # select the annotations for the current series\n ctrue = candidates_true[seriesuid == candidates_true.seriesuid] \n cfalse = candidates_false[seriesuid == candidates_false.seriesuid] \n \n if len(cands) == 0 and len(ctrue) == 0 and len(cfalse) > 0:\n if use_all_blanks:\n print (\"annonations and false candidates count (using all): \", len(cands), len(cfalse))\n cfalse_sel_all = pd.DataFrame(cfalse)\n cfalse_sel_all[\"diameter_mm\"] = 1.6 *RESIZE_SPACING[0] \n cfalse_sel_all = cfalse_sel_all.drop([\"class\", \"coordZ_8\"], 1)\n if create_wblanks_mask_only:\n update_nodule_mask_or_blank(imagePath, cfalse_sel_all, False)\n else:\n create_nodule_mask_or_blank (imagePath, cfalse_sel_all, False)\n \n else: # original version \n \n vals, counts = np.unique(cfalse[\"coordZ_8\"], return_counts=True)\n ## take the coordZ_8 that has most entries\n val_sel = vals[np.argmax(counts)]\n # as hook calculate the average x and y coordinates\n id_sel = cfalse[\"coordZ_8\"] == val_sel\n xc = np.mean(cfalse[id_sel][\"coordX\"])\n yc = np.mean(cfalse[id_sel][\"coordY\"])\n zc = np.mean(cfalse[id_sel][\"coordZ\"])\n \n cfalse_sel = pd.DataFrame(cfalse[id_sel][:1])\n cfalse_sel[\"coordX\"] = xc\n cfalse_sel[\"coordY\"] = yc\n cfalse_sel[\"coordZ\"] = zc\n cfalse_sel[\"diameter_mm\"] = 1.6 *RESIZE_SPACING[0] # add the diameter and drop all other columns\n cfalse_sel = cfalse_sel.drop([\"class\", \"coordZ_8\"], 1)\n \n print (\"annonations and false candidates count, using average at the most frequent z: \", len(cands), len(cfalse), cfalse_sel)\n if create_wblanks_mask_only:\n update_nodule_mask_or_blank(imagePath, cfalse_sel, False)\n else:\n create_nodule_mask_or_blank (imagePath, cfalse_sel, False)\n \n elif len(cands) > 0:\n if create_wblanks_mask_only:\n update_nodule_mask_or_blank(imagePath, cands, True)\n else:\n create_nodule_mask_or_blank (imagePath, cands, True)\n return\n\nif __name__ == '__main__':\n \n \n #### STEP 1\n start = time.time()\n print (\"Starting creating nodule masks ...\")\n \n create_nodule_mask_or_blank_subset(\"[0-7]\", create_wblanks_mask_only = False)\n create_nodule_mask_or_blank_subset(\"[8-9]\", create_wblanks_mask_only = False)\n\n print(\"Total time for create_nodule_mask_or_blank_subset: \", ((time.time() - start))) #6551 sec\n \n \n start = time.time()\n print (\"Creaing wblanks masks ...\")\n create_nodule_mask_or_blank_subset(\"[0-7]\", create_wblanks_mask_only = True) # only updates the masks; False creates all\n print(\"Total time for create wblanks masks: \", ((time.time() - start)))\n \n start = time.time()\n print (\"Creaing wblanks masks ...\")\n create_nodule_mask_or_blank_subset(\"[8-9]\", create_wblanks_mask_only = True) # only updates the masks; False creates all\n print(\"Total time for create wblanks masks: \", ((time.time() - start)))\n "
]
| [
[
"numpy.dot",
"matplotlib.pyplot.imshow",
"scipy.ndimage.sobel",
"pandas.DataFrame",
"numpy.round",
"numpy.max",
"matplotlib.pyplot.plot",
"numpy.mean",
"numpy.cross",
"numpy.hypot",
"pandas.read_csv",
"numpy.unique",
"scipy.ndimage.generate_binary_structure",
"numpy.full",
"scipy.ndimage.morphological_gradient",
"numpy.copy",
"numpy.argmax",
"scipy.ndimage.iterate_structure",
"numpy.zeros",
"numpy.bitwise_or",
"numpy.min",
"scipy.ndimage.morphology.binary_closing",
"scipy.ndimage.binary_dilation",
"matplotlib.pyplot.show",
"numpy.array",
"numpy.sum",
"matplotlib.pyplot.ylabel",
"numpy.absolute",
"scipy.ndimage.black_tophat",
"matplotlib.pyplot.subplots",
"numpy.linalg.norm",
"numpy.ones",
"numpy.savez_compressed",
"matplotlib.pyplot.xlabel"
]
]
|
allenai/elastic | [
"57345c600c63fbde163c41929d6d6dd894d408ce"
]
| [
"utils.py"
]
| [
"from __future__ import print_function\nimport math\nimport random\nimport torchvision.transforms as transforms\nimport warnings\nfrom torch.nn import functional as F\nimport shutil\nimport torch.utils.data as data\nimport os\nfrom PIL import Image\nimport torch\nimport numpy as np\n\n\ndef accuracy(output, target, topk=(1,)):\n \"\"\"Computes the precision@k for the specified values of k\"\"\"\n maxk = max(topk)\n batch_size = target.size(0)\n\n _, pred = output.topk(maxk, 1, True, True)\n pred = pred.t()\n correct = pred.eq(target.view(1, -1).expand_as(pred))\n\n res = []\n for k in topk:\n correct_k = correct[:k].view(-1).float().sum(0, keepdim=True)\n res.append(correct_k.mul_(100.0 / batch_size))\n return res\n\n\ndef save_checkpoint(state, is_best, filename='checkpoint.pth.tar'):\n torch.save(state, filename)\n if is_best:\n shutil.copyfile(filename, 'model_best.pth.tar')\n\n\nclass AverageMeter(object):\n def __init__(self):\n self.val = None\n self.sum = None\n self.cnt = None\n self.avg = None\n self.ema = None\n self.initialized = False\n\n def update(self, val, n=1):\n if not self.initialized:\n self.initialize(val, n)\n else:\n self.add(val, n)\n\n def initialize(self, val, n):\n self.val = val\n self.sum = val * n\n self.cnt = n\n self.avg = val\n self.ema = val\n self.initialized = True\n\n def add(self, val, n):\n self.val = val\n self.sum += val * n\n self.cnt += n\n self.avg = self.sum / self.cnt\n self.ema = self.ema * 0.99 + self.val * 0.01\n\n\ndef inter_and_union(pred, mask, num_class):\n pred = np.asarray(pred, dtype=np.uint8).copy()\n mask = np.asarray(mask, dtype=np.uint8).copy()\n\n # 255 -> 0\n pred += 1\n mask += 1\n pred = pred * (mask > 0)\n\n inter = pred * (pred == mask)\n (area_inter, _) = np.histogram(inter, bins=num_class, range=(1, num_class))\n (area_pred, _) = np.histogram(pred, bins=num_class, range=(1, num_class))\n (area_mask, _) = np.histogram(mask, bins=num_class, range=(1, num_class))\n area_union = area_pred + area_mask - area_inter\n\n return (area_inter, area_union)\n\n\ndef preprocess(image, mask, flip=False, scale=None, crop=None):\n if flip:\n if random.random() < 0.5:\n image = image.transpose(Image.FLIP_LEFT_RIGHT)\n mask = mask.transpose(Image.FLIP_LEFT_RIGHT)\n if scale:\n w, h = image.size\n rand_log_scale = math.log(scale[0], 2) + random.random() * (math.log(scale[1], 2) - math.log(scale[0], 2))\n random_scale = math.pow(2, rand_log_scale)\n new_size = (int(round(w * random_scale)), int(round(h * random_scale)))\n image = image.resize(new_size, Image.ANTIALIAS)\n mask = mask.resize(new_size, Image.NEAREST)\n\n data_transforms = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n image = data_transforms(image)\n mask = torch.LongTensor(np.array(mask).astype(np.int64))\n\n if crop:\n h, w = image.shape[1], image.shape[2]\n ori_h, ori_w = image.shape[1], image.shape[2]\n\n pad_tb = max(0, int((1 + crop[0] - h) / 2))\n pad_lr = max(0, int((1 + crop[1] - w) / 2))\n image = torch.nn.ZeroPad2d((pad_lr, pad_lr, pad_tb, pad_tb))(image)\n mask = torch.nn.ConstantPad2d((pad_lr, pad_lr, pad_tb, pad_tb), 255)(mask)\n\n h, w = image.shape[1], image.shape[2]\n i = random.randint(0, h - crop[0])\n j = random.randint(0, w - crop[1])\n image = image[:, i:i + crop[0], j:j + crop[1]]\n mask = mask[i:i + crop[0], j:j + crop[1]]\n\n return image, mask, pad_tb - j, pad_lr - i, ori_h, ori_w\n\n\n# pascal dataloader\nclass VOCSegmentation(data.Dataset):\n CLASSES = [\n 'background', 'aeroplane', 'bicycle', 'bird', 'boat', 'bottle', 'bus',\n 'car', 'cat', 'chair', 'cow', 'diningtable', 'dog', 'horse',\n 'motorbike', 'person', 'potted-plant', 'sheep', 'sofa', 'train',\n 'tv/monitor'\n ]\n\n def __init__(self, root, train=True, transform=None, target_transform=None, download=False, crop_size=None):\n self.root = root\n _voc_root = os.path.join(self.root, 'VOC2012')\n _list_dir = os.path.join(_voc_root, 'list')\n self.transform = transform\n self.target_transform = target_transform\n self.train = train\n self.crop_size = crop_size\n\n if download:\n self.download()\n\n if self.train:\n _list_f = os.path.join(_list_dir, 'train_aug.txt')\n else:\n _list_f = os.path.join(_list_dir, 'val.txt')\n self.images = []\n self.masks = []\n with open(_list_f, 'r') as lines:\n for line in lines:\n _image = _voc_root + line.split()[0]\n _mask = _voc_root + line.split()[1]\n assert os.path.isfile(_image)\n assert os.path.isfile(_mask)\n self.images.append(_image)\n self.masks.append(_mask)\n\n def __getitem__(self, index):\n _img = Image.open(self.images[index]).convert('RGB')\n _target = Image.open(self.masks[index])\n\n _img, _target, a, b, h, w = preprocess(_img, _target,\n flip=True if self.train else False,\n scale=(0.5, 2.0) if self.train else None,\n crop=(self.crop_size, self.crop_size))\n\n if self.transform is not None:\n _img = self.transform(_img)\n\n if self.target_transform is not None:\n _target = self.target_transform(_target)\n\n return _img, _target, a, b, h, w # used for visualizing\n\n def __len__(self):\n return len(self.images)\n\n def download(self):\n raise NotImplementedError('Automatic download not yet implemented.')\n\n\n# flops counter\ndef add_flops_counting_methods(net_main_module):\n \"\"\"Adds flops counting functions to an existing model. After that\n the flops count should be activated and the model should be run on an input\n image.\n\n Example:\n\n fcn = add_flops_counting_methods(fcn)\n fcn = fcn.cuda().train()\n fcn.start_flops_count()\n\n\n _ = fcn(batch)\n\n fcn.compute_average_flops_cost() / 1e9 / 2 # Result in GFLOPs per image in batch\n\n Important: dividing by 2 only works for resnet models -- see below for the details\n of flops computation.\n\n Attention: we are counting multiply-add as two flops in this work, because in\n most resnet models convolutions are bias-free (BN layers act as bias there)\n and it makes sense to count muliply and add as separate flops therefore.\n This is why in the above example we divide by 2 in order to be consistent with\n most modern benchmarks. For example in \"Spatially Adaptive Computatin Time for Residual\n Networks\" by Figurnov et al multiply-add was counted as two flops.\n\n This module computes the average flops which is necessary for dynamic networks which\n have different number of executed layers. For static networks it is enough to run the network\n once and get statistics (above example).\n\n Implementation:\n The module works by adding batch_count to the main module which tracks the sum\n of all batch sizes that were run through the network.\n\n Also each convolutional layer of the network tracks the overall number of flops\n performed.\n\n The parameters are updated with the help of registered hook-functions which\n are being called each time the respective layer is executed.\n\n Parameters\n ----------\n net_main_module : torch.nn.Module\n Main module containing network\n\n Returns\n -------\n net_main_module : torch.nn.Module\n Updated main module with new methods/attributes that are used\n to compute flops.\n \"\"\"\n\n # adding additional methods to the existing module object,\n # this is done this way so that each function has access to self object\n net_main_module.start_flops_count = start_flops_count.__get__(net_main_module)\n net_main_module.stop_flops_count = stop_flops_count.__get__(net_main_module)\n net_main_module.reset_flops_count = reset_flops_count.__get__(net_main_module)\n net_main_module.compute_average_flops_cost = compute_average_flops_cost.__get__(net_main_module)\n\n net_main_module.reset_flops_count()\n\n # Adding variables necessary for masked flops computation\n net_main_module.apply(add_flops_mask_variable_or_reset)\n\n return net_main_module\n\n\ndef compute_average_flops_cost(self):\n \"\"\"\n A method that will be available after add_flops_counting_methods() is called\n on a desired net object.\n\n Returns current mean flops consumption per image.\n\n \"\"\"\n\n batches_count = self.__batch_counter__\n flops_sum = 0\n for module in self.modules():\n if hasattr(module, '__flops__'): # is_supported_instance(module)\n flops_sum += module.__flops__\n\n return flops_sum / batches_count\n\n\ndef start_flops_count(self):\n \"\"\"\n A method that will be available after add_flops_counting_methods() is called\n on a desired net object.\n\n Activates the computation of mean flops consumption per image.\n Call it before you run the network.\n\n \"\"\"\n add_batch_counter_hook_function(self)\n self.apply(add_flops_counter_hook_function)\n\n\ndef stop_flops_count(self):\n \"\"\"\n A method that will be available after add_flops_counting_methods() is called\n on a desired net object.\n\n Stops computing the mean flops consumption per image.\n Call whenever you want to pause the computation.\n\n \"\"\"\n remove_batch_counter_hook_function(self)\n self.apply(remove_flops_counter_hook_function)\n\n\ndef reset_flops_count(self):\n \"\"\"\n A method that will be available after add_flops_counting_methods() is called\n on a desired net object.\n\n Resets statistics computed so far.\n\n \"\"\"\n add_batch_counter_variables_or_reset(self)\n self.apply(add_flops_counter_variable_or_reset)\n\n\ndef add_flops_mask(module, mask):\n def add_flops_mask_func(module):\n if isinstance(module, torch.nn.Conv2d):\n module.__mask__ = mask\n module.apply(add_flops_mask_func)\n\n\ndef remove_flops_mask(module):\n module.apply(add_flops_mask_variable_or_reset)\n\n\n# ---- Internal functions\ndef is_supported_instance(module):\n if isinstance(module, torch.nn.Conv2d) or isinstance(module, torch.nn.ReLU) \\\n or isinstance(module, torch.nn.PReLU) or isinstance(module, torch.nn.ELU) \\\n or isinstance(module, torch.nn.LeakyReLU) or isinstance(module, torch.nn.ReLU6) \\\n or isinstance(module, torch.nn.Linear) or isinstance(module, torch.nn.MaxPool2d) \\\n or isinstance(module, torch.nn.AvgPool2d) or isinstance(module, torch.nn.BatchNorm2d):\n return True\n\n return False\n\n\ndef empty_flops_counter_hook(module, input, output):\n module.__flops__ += 0\n\n\ndef relu_flops_counter_hook(module, input, output):\n input = input[0]\n batch_size = input.shape[0]\n active_elements_count = batch_size\n for val in input.shape[1:]:\n active_elements_count *= val\n\n module.__flops__ += active_elements_count\n\n\ndef linear_flops_counter_hook(module, input, output):\n input = input[0]\n batch_size = input.shape[0]\n module.__flops__ += batch_size * input.shape[1] * output.shape[1]\n\n\ndef pool_flops_counter_hook(module, input, output):\n input = input[0]\n module.__flops__ += np.prod(input.shape)\n\ndef bn_flops_counter_hook(module, input, output):\n module.affine\n input = input[0]\n\n batch_flops = np.prod(input.shape)\n if module.affine:\n batch_flops *= 2\n module.__flops__ += batch_flops\n\ndef conv_flops_counter_hook(conv_module, input, output):\n # Can have multiple inputs, getting the first one\n input = input[0]\n\n batch_size = input.shape[0]\n output_height, output_width = output.shape[2:]\n\n kernel_height, kernel_width = conv_module.kernel_size\n in_channels = conv_module.in_channels\n out_channels = conv_module.out_channels\n groups = conv_module.groups\n\n filters_per_channel = out_channels // groups\n conv_per_position_flops = kernel_height * kernel_width * in_channels * filters_per_channel\n\n active_elements_count = batch_size * output_height * output_width\n\n if conv_module.__mask__ is not None:\n # (b, 1, h, w)\n flops_mask = conv_module.__mask__.expand(batch_size, 1, output_height, output_width)\n active_elements_count = flops_mask.sum()\n\n overall_conv_flops = conv_per_position_flops * active_elements_count\n\n bias_flops = 0\n\n if conv_module.bias is not None:\n\n bias_flops = out_channels * active_elements_count\n\n overall_flops = overall_conv_flops + bias_flops\n\n conv_module.__flops__ += overall_flops\n\n\ndef batch_counter_hook(module, input, output):\n # Can have multiple inputs, getting the first one\n input = input[0]\n batch_size = input.shape[0]\n module.__batch_counter__ += batch_size\n\n\ndef add_batch_counter_variables_or_reset(module):\n\n module.__batch_counter__ = 0\n\n\ndef add_batch_counter_hook_function(module):\n if hasattr(module, '__batch_counter_handle__'):\n return\n\n handle = module.register_forward_hook(batch_counter_hook)\n module.__batch_counter_handle__ = handle\n\n\ndef remove_batch_counter_hook_function(module):\n if hasattr(module, '__batch_counter_handle__'):\n module.__batch_counter_handle__.remove()\n del module.__batch_counter_handle__\n\n\ndef add_flops_counter_variable_or_reset(module):\n if is_supported_instance(module):\n module.__flops__ = 0\n\n\ndef add_flops_counter_hook_function(module):\n if is_supported_instance(module):\n if hasattr(module, '__flops_handle__'):\n return\n\n if isinstance(module, torch.nn.Conv2d):\n handle = module.register_forward_hook(conv_flops_counter_hook)\n elif isinstance(module, torch.nn.ReLU) or isinstance(module, torch.nn.PReLU) \\\n or isinstance(module, torch.nn.ELU) or isinstance(module, torch.nn.LeakyReLU) \\\n or isinstance(module, torch.nn.ReLU6):\n handle = module.register_forward_hook(relu_flops_counter_hook)\n elif isinstance(module, torch.nn.Linear):\n handle = module.register_forward_hook(linear_flops_counter_hook)\n elif isinstance(module, torch.nn.AvgPool2d) or isinstance(module, torch.nn.MaxPool2d):\n handle = module.register_forward_hook(pool_flops_counter_hook)\n elif isinstance(module, torch.nn.BatchNorm2d):\n handle = module.register_forward_hook(bn_flops_counter_hook)\n else:\n handle = module.register_forward_hook(empty_flops_counter_hook)\n module.__flops_handle__ = handle\n\n\ndef remove_flops_counter_hook_function(module):\n if is_supported_instance(module):\n if hasattr(module, '__flops_handle__'):\n module.__flops_handle__.remove()\n del module.__flops_handle__\n# --- Masked flops counting\n\n\n# Also being run in the initialization\ndef add_flops_mask_variable_or_reset(module):\n if is_supported_instance(module):\n module.__mask__ = None\n"
]
| [
[
"numpy.asarray",
"torch.nn.ConstantPad2d",
"numpy.prod",
"torch.nn.ZeroPad2d",
"numpy.array",
"numpy.histogram",
"torch.save"
]
]
|
Martynas-P/pandas | [
"c79fc046c8dcb6810202b6dbb5ff41e0e56d685e"
]
| [
"pandas/core/base.py"
]
| [
"\"\"\"\nBase and utility classes for pandas objects.\n\"\"\"\nimport builtins\nfrom collections import OrderedDict\nimport textwrap\nfrom typing import Dict, FrozenSet, List, Optional\nimport warnings\n\nimport numpy as np\n\nimport pandas._libs.lib as lib\nfrom pandas.compat import PYPY\nfrom pandas.compat.numpy import function as nv\nfrom pandas.errors import AbstractMethodError\nfrom pandas.util._decorators import Appender, Substitution, cache_readonly\nfrom pandas.util._validators import validate_bool_kwarg\n\nfrom pandas.core.dtypes.cast import is_nested_object\nfrom pandas.core.dtypes.common import (\n is_categorical_dtype,\n is_datetime64_ns_dtype,\n is_datetime64tz_dtype,\n is_extension_array_dtype,\n is_list_like,\n is_object_dtype,\n is_scalar,\n is_timedelta64_ns_dtype,\n)\nfrom pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries\nfrom pandas.core.dtypes.missing import isna\n\nfrom pandas.core import algorithms, common as com\nfrom pandas.core.accessor import DirNamesMixin\nfrom pandas.core.algorithms import duplicated, unique1d, value_counts\nfrom pandas.core.arrays import ExtensionArray\nimport pandas.core.nanops as nanops\n\n_shared_docs = dict() # type: Dict[str, str]\n_indexops_doc_kwargs = dict(\n klass=\"IndexOpsMixin\",\n inplace=\"\",\n unique=\"IndexOpsMixin\",\n duplicated=\"IndexOpsMixin\",\n)\n\n\nclass PandasObject(DirNamesMixin):\n \"\"\"baseclass for various pandas objects\"\"\"\n\n @property\n def _constructor(self):\n \"\"\"class constructor (for this class it's just `__class__`\"\"\"\n return self.__class__\n\n def __repr__(self) -> str:\n \"\"\"\n Return a string representation for a particular object.\n \"\"\"\n # Should be overwritten by base classes\n return object.__repr__(self)\n\n def _reset_cache(self, key=None):\n \"\"\"\n Reset cached properties. If ``key`` is passed, only clears that key.\n \"\"\"\n if getattr(self, \"_cache\", None) is None:\n return\n if key is None:\n self._cache.clear()\n else:\n self._cache.pop(key, None)\n\n def __sizeof__(self):\n \"\"\"\n Generates the total memory usage for an object that returns\n either a value or Series of values\n \"\"\"\n if hasattr(self, \"memory_usage\"):\n mem = self.memory_usage(deep=True)\n if not is_scalar(mem):\n mem = mem.sum()\n return int(mem)\n\n # no memory_usage attribute, so fall back to\n # object's 'sizeof'\n return super().__sizeof__()\n\n\nclass NoNewAttributesMixin:\n \"\"\"Mixin which prevents adding new attributes.\n\n Prevents additional attributes via xxx.attribute = \"something\" after a\n call to `self.__freeze()`. Mainly used to prevent the user from using\n wrong attributes on a accessor (`Series.cat/.str/.dt`).\n\n If you really want to add a new attribute at a later time, you need to use\n `object.__setattr__(self, key, value)`.\n \"\"\"\n\n def _freeze(self):\n \"\"\"Prevents setting additional attributes\"\"\"\n object.__setattr__(self, \"__frozen\", True)\n\n # prevent adding any attribute via s.xxx.new_attribute = ...\n def __setattr__(self, key, value):\n # _cache is used by a decorator\n # We need to check both 1.) cls.__dict__ and 2.) getattr(self, key)\n # because\n # 1.) getattr is false for attributes that raise errors\n # 2.) cls.__dict__ doesn't traverse into base classes\n if getattr(self, \"__frozen\", False) and not (\n key == \"_cache\"\n or key in type(self).__dict__\n or getattr(self, key, None) is not None\n ):\n raise AttributeError(\n \"You cannot add any new attribute '{key}'\".format(key=key)\n )\n object.__setattr__(self, key, value)\n\n\nclass GroupByError(Exception):\n pass\n\n\nclass DataError(GroupByError):\n pass\n\n\nclass SpecificationError(GroupByError):\n pass\n\n\nclass SelectionMixin:\n \"\"\"\n mixin implementing the selection & aggregation interface on a group-like\n object sub-classes need to define: obj, exclusions\n \"\"\"\n\n _selection = None\n _internal_names = [\"_cache\", \"__setstate__\"]\n _internal_names_set = set(_internal_names)\n\n _builtin_table = OrderedDict(\n ((builtins.sum, np.sum), (builtins.max, np.max), (builtins.min, np.min))\n )\n\n _cython_table = OrderedDict(\n (\n (builtins.sum, \"sum\"),\n (builtins.max, \"max\"),\n (builtins.min, \"min\"),\n (np.all, \"all\"),\n (np.any, \"any\"),\n (np.sum, \"sum\"),\n (np.nansum, \"sum\"),\n (np.mean, \"mean\"),\n (np.nanmean, \"mean\"),\n (np.prod, \"prod\"),\n (np.nanprod, \"prod\"),\n (np.std, \"std\"),\n (np.nanstd, \"std\"),\n (np.var, \"var\"),\n (np.nanvar, \"var\"),\n (np.median, \"median\"),\n (np.nanmedian, \"median\"),\n (np.max, \"max\"),\n (np.nanmax, \"max\"),\n (np.min, \"min\"),\n (np.nanmin, \"min\"),\n (np.cumprod, \"cumprod\"),\n (np.nancumprod, \"cumprod\"),\n (np.cumsum, \"cumsum\"),\n (np.nancumsum, \"cumsum\"),\n )\n )\n\n @property\n def _selection_name(self):\n \"\"\"\n return a name for myself; this would ideally be called\n the 'name' property, but we cannot conflict with the\n Series.name property which can be set\n \"\"\"\n if self._selection is None:\n return None # 'result'\n else:\n return self._selection\n\n @property\n def _selection_list(self):\n if not isinstance(\n self._selection, (list, tuple, ABCSeries, ABCIndexClass, np.ndarray)\n ):\n return [self._selection]\n return self._selection\n\n @cache_readonly\n def _selected_obj(self):\n\n if self._selection is None or isinstance(self.obj, ABCSeries):\n return self.obj\n else:\n return self.obj[self._selection]\n\n @cache_readonly\n def ndim(self) -> int:\n return self._selected_obj.ndim\n\n @cache_readonly\n def _obj_with_exclusions(self):\n if self._selection is not None and isinstance(self.obj, ABCDataFrame):\n return self.obj.reindex(columns=self._selection_list)\n\n if len(self.exclusions) > 0:\n return self.obj.drop(self.exclusions, axis=1)\n else:\n return self.obj\n\n def __getitem__(self, key):\n if self._selection is not None:\n raise IndexError(\n \"Column(s) {selection} already selected\".format(\n selection=self._selection\n )\n )\n\n if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass, np.ndarray)):\n if len(self.obj.columns.intersection(key)) != len(key):\n bad_keys = list(set(key).difference(self.obj.columns))\n raise KeyError(\n \"Columns not found: {missing}\".format(missing=str(bad_keys)[1:-1])\n )\n return self._gotitem(list(key), ndim=2)\n\n elif not getattr(self, \"as_index\", False):\n if key not in self.obj.columns:\n raise KeyError(\"Column not found: {key}\".format(key=key))\n return self._gotitem(key, ndim=2)\n\n else:\n if key not in self.obj:\n raise KeyError(\"Column not found: {key}\".format(key=key))\n return self._gotitem(key, ndim=1)\n\n def _gotitem(self, key, ndim, subset=None):\n \"\"\"\n sub-classes to define\n return a sliced object\n\n Parameters\n ----------\n key : string / list of selections\n ndim : 1,2\n requested ndim of result\n subset : object, default None\n subset to act on\n\n \"\"\"\n raise AbstractMethodError(self)\n\n def aggregate(self, func, *args, **kwargs):\n raise AbstractMethodError(self)\n\n agg = aggregate\n\n def _try_aggregate_string_function(self, arg: str, *args, **kwargs):\n \"\"\"\n if arg is a string, then try to operate on it:\n - try to find a function (or attribute) on ourselves\n - try to find a numpy function\n - raise\n\n \"\"\"\n assert isinstance(arg, str)\n\n f = getattr(self, arg, None)\n if f is not None:\n if callable(f):\n return f(*args, **kwargs)\n\n # people may try to aggregate on a non-callable attribute\n # but don't let them think they can pass args to it\n assert len(args) == 0\n assert (\n len([kwarg for kwarg in kwargs if kwarg not in [\"axis\", \"_level\"]]) == 0\n )\n return f\n\n f = getattr(np, arg, None)\n if f is not None:\n if hasattr(self, \"__array__\"):\n # in particular exclude Window\n return f(self, *args, **kwargs)\n\n raise AttributeError(\n \"'{arg}' is not a valid function for \"\n \"'{cls}' object\".format(arg=arg, cls=type(self).__name__)\n )\n\n def _aggregate(self, arg, *args, **kwargs):\n \"\"\"\n provide an implementation for the aggregators\n\n Parameters\n ----------\n arg : string, dict, function\n *args : args to pass on to the function\n **kwargs : kwargs to pass on to the function\n\n Returns\n -------\n tuple of result, how\n\n Notes\n -----\n how can be a string describe the required post-processing, or\n None if not required\n \"\"\"\n is_aggregator = lambda x: isinstance(x, (list, tuple, dict))\n is_nested_renamer = False\n\n _axis = kwargs.pop(\"_axis\", None)\n if _axis is None:\n _axis = getattr(self, \"axis\", 0)\n _level = kwargs.pop(\"_level\", None)\n\n if isinstance(arg, str):\n return self._try_aggregate_string_function(arg, *args, **kwargs), None\n\n if isinstance(arg, dict):\n\n # aggregate based on the passed dict\n if _axis != 0: # pragma: no cover\n raise ValueError(\"Can only pass dict with axis=0\")\n\n obj = self._selected_obj\n\n def nested_renaming_depr(level: int = 4):\n # deprecation of nested renaming\n # GH 15931\n msg = textwrap.dedent(\n \"\"\"\\\n using a dict with renaming is deprecated and will be removed\n in a future version.\n\n For column-specific groupby renaming, use named aggregation\n\n >>> df.groupby(...).agg(name=('column', aggfunc))\n \"\"\"\n )\n warnings.warn(msg, FutureWarning, stacklevel=level)\n\n # if we have a dict of any non-scalars\n # eg. {'A' : ['mean']}, normalize all to\n # be list-likes\n if any(is_aggregator(x) for x in arg.values()):\n new_arg = OrderedDict()\n for k, v in arg.items():\n if not isinstance(v, (tuple, list, dict)):\n new_arg[k] = [v]\n else:\n new_arg[k] = v\n\n # the keys must be in the columns\n # for ndim=2, or renamers for ndim=1\n\n # ok for now, but deprecated\n # {'A': { 'ra': 'mean' }}\n # {'A': { 'ra': ['mean'] }}\n # {'ra': ['mean']}\n\n # not ok\n # {'ra' : { 'A' : 'mean' }}\n if isinstance(v, dict):\n is_nested_renamer = True\n\n if k not in obj.columns:\n msg = (\n \"cannot perform renaming for {key} with a \"\n \"nested dictionary\"\n ).format(key=k)\n raise SpecificationError(msg)\n nested_renaming_depr(4 + (_level or 0))\n\n elif isinstance(obj, ABCSeries):\n nested_renaming_depr()\n elif isinstance(obj, ABCDataFrame) and k not in obj.columns:\n raise KeyError(\"Column '{col}' does not exist!\".format(col=k))\n\n arg = new_arg\n\n else:\n # deprecation of renaming keys\n # GH 15931\n keys = list(arg.keys())\n if isinstance(obj, ABCDataFrame) and len(\n obj.columns.intersection(keys)\n ) != len(keys):\n nested_renaming_depr()\n\n from pandas.core.reshape.concat import concat\n\n def _agg_1dim(name, how, subset=None):\n \"\"\"\n aggregate a 1-dim with how\n \"\"\"\n colg = self._gotitem(name, ndim=1, subset=subset)\n if colg.ndim != 1:\n raise SpecificationError(\n \"nested dictionary is ambiguous in aggregation\"\n )\n return colg.aggregate(how, _level=(_level or 0) + 1)\n\n def _agg_2dim(name, how):\n \"\"\"\n aggregate a 2-dim with how\n \"\"\"\n colg = self._gotitem(self._selection, ndim=2, subset=obj)\n return colg.aggregate(how, _level=None)\n\n def _agg(arg, func):\n \"\"\"\n run the aggregations over the arg with func\n return an OrderedDict\n \"\"\"\n result = OrderedDict()\n for fname, agg_how in arg.items():\n result[fname] = func(fname, agg_how)\n return result\n\n # set the final keys\n keys = list(arg.keys())\n result = OrderedDict()\n\n # nested renamer\n if is_nested_renamer:\n result = list(_agg(arg, _agg_1dim).values())\n\n if all(isinstance(r, dict) for r in result):\n\n result, results = OrderedDict(), result\n for r in results:\n result.update(r)\n keys = list(result.keys())\n\n else:\n\n if self._selection is not None:\n keys = None\n\n # some selection on the object\n elif self._selection is not None:\n\n sl = set(self._selection_list)\n\n # we are a Series like object,\n # but may have multiple aggregations\n if len(sl) == 1:\n\n result = _agg(\n arg, lambda fname, agg_how: _agg_1dim(self._selection, agg_how)\n )\n\n # we are selecting the same set as we are aggregating\n elif not len(sl - set(keys)):\n\n result = _agg(arg, _agg_1dim)\n\n # we are a DataFrame, with possibly multiple aggregations\n else:\n\n result = _agg(arg, _agg_2dim)\n\n # no selection\n else:\n\n try:\n result = _agg(arg, _agg_1dim)\n except SpecificationError:\n\n # we are aggregating expecting all 1d-returns\n # but we have 2d\n result = _agg(arg, _agg_2dim)\n\n # combine results\n\n def is_any_series() -> bool:\n # return a boolean if we have *any* nested series\n return any(isinstance(r, ABCSeries) for r in result.values())\n\n def is_any_frame() -> bool:\n # return a boolean if we have *any* nested series\n return any(isinstance(r, ABCDataFrame) for r in result.values())\n\n if isinstance(result, list):\n return concat(result, keys=keys, axis=1, sort=True), True\n\n elif is_any_frame():\n # we have a dict of DataFrames\n # return a MI DataFrame\n\n return concat([result[k] for k in keys], keys=keys, axis=1), True\n\n elif isinstance(self, ABCSeries) and is_any_series():\n\n # we have a dict of Series\n # return a MI Series\n try:\n result = concat(result)\n except TypeError:\n # we want to give a nice error here if\n # we have non-same sized objects, so\n # we don't automatically broadcast\n\n raise ValueError(\n \"cannot perform both aggregation \"\n \"and transformation operations \"\n \"simultaneously\"\n )\n\n return result, True\n\n # fall thru\n from pandas import DataFrame, Series\n\n try:\n result = DataFrame(result)\n except ValueError:\n\n # we have a dict of scalars\n result = Series(result, name=getattr(self, \"name\", None))\n\n return result, True\n elif is_list_like(arg):\n # we require a list, but not an 'str'\n return self._aggregate_multiple_funcs(arg, _level=_level, _axis=_axis), None\n else:\n result = None\n\n f = self._get_cython_func(arg)\n if f and not args and not kwargs:\n return getattr(self, f)(), None\n\n # caller can react\n return result, True\n\n def _aggregate_multiple_funcs(self, arg, _level, _axis):\n from pandas.core.reshape.concat import concat\n\n if _axis != 0:\n raise NotImplementedError(\"axis other than 0 is not supported\")\n\n if self._selected_obj.ndim == 1:\n obj = self._selected_obj\n else:\n obj = self._obj_with_exclusions\n\n results = []\n keys = []\n\n # degenerate case\n if obj.ndim == 1:\n for a in arg:\n colg = self._gotitem(obj.name, ndim=1, subset=obj)\n try:\n new_res = colg.aggregate(a)\n\n except TypeError:\n pass\n else:\n results.append(new_res)\n\n # make sure we find a good name\n name = com.get_callable_name(a) or a\n keys.append(name)\n\n # multiples\n else:\n for index, col in enumerate(obj):\n colg = self._gotitem(col, ndim=1, subset=obj.iloc[:, index])\n try:\n new_res = colg.aggregate(arg)\n except (TypeError, DataError):\n pass\n except ValueError as err:\n # cannot aggregate\n if \"Must produce aggregated value\" in str(err):\n # raised directly in _aggregate_named\n pass\n elif \"no results\" in str(err):\n # raised direcly in _aggregate_multiple_funcs\n pass\n else:\n raise\n else:\n results.append(new_res)\n keys.append(col)\n\n # if we are empty\n if not len(results):\n raise ValueError(\"no results\")\n\n if all(np.ndim(x) > 0 for x in results):\n return concat(results, keys=keys, axis=1, sort=False)\n else:\n\n # we are concatting non-NDFrame objects,\n # e.g. a list of scalars\n\n from pandas import Series\n\n result = Series(results, index=keys, name=self.name)\n if is_nested_object(result):\n raise ValueError(\"cannot combine transform and aggregation operations\")\n return result\n\n def _get_cython_func(self, arg: str) -> Optional[str]:\n \"\"\"\n if we define an internal function for this argument, return it\n \"\"\"\n return self._cython_table.get(arg)\n\n def _is_builtin_func(self, arg):\n \"\"\"\n if we define an builtin function for this argument, return it,\n otherwise return the arg\n \"\"\"\n return self._builtin_table.get(arg, arg)\n\n\nclass ShallowMixin:\n _attributes = [] # type: List[str]\n\n def _shallow_copy(self, obj=None, **kwargs):\n \"\"\"\n return a new object with the replacement attributes\n \"\"\"\n if obj is None:\n obj = self._selected_obj.copy()\n\n if isinstance(obj, self._constructor):\n obj = obj.obj\n for attr in self._attributes:\n if attr not in kwargs:\n kwargs[attr] = getattr(self, attr)\n return self._constructor(obj, **kwargs)\n\n\nclass IndexOpsMixin:\n \"\"\"\n Common ops mixin to support a unified interface / docs for Series / Index\n \"\"\"\n\n # ndarray compatibility\n __array_priority__ = 1000\n _deprecations = frozenset(\n [\n \"tolist\", # tolist is not deprecated, just suppressed in the __dir__\n \"base\",\n \"data\",\n \"item\",\n \"itemsize\",\n \"flags\",\n \"strides\",\n ]\n ) # type: FrozenSet[str]\n\n def transpose(self, *args, **kwargs):\n \"\"\"\n Return the transpose, which is by definition self.\n\n Returns\n -------\n %(klass)s\n \"\"\"\n nv.validate_transpose(args, kwargs)\n return self\n\n T = property(\n transpose,\n doc=\"\"\"\n Return the transpose, which is by definition self.\n \"\"\",\n )\n\n @property\n def _is_homogeneous_type(self) -> bool:\n \"\"\"\n Whether the object has a single dtype.\n\n By definition, Series and Index are always considered homogeneous.\n A MultiIndex may or may not be homogeneous, depending on the\n dtypes of the levels.\n\n See Also\n --------\n DataFrame._is_homogeneous_type : Whether all the columns in a\n DataFrame have the same dtype.\n MultiIndex._is_homogeneous_type : Whether all the levels of a\n MultiIndex have the same dtype.\n \"\"\"\n return True\n\n @property\n def shape(self):\n \"\"\"\n Return a tuple of the shape of the underlying data.\n \"\"\"\n return self._values.shape\n\n @property\n def ndim(self) -> int:\n \"\"\"\n Number of dimensions of the underlying data, by definition 1.\n \"\"\"\n return 1\n\n def item(self):\n \"\"\"\n Return the first element of the underlying data as a python scalar.\n\n .. deprecated:: 0.25.0\n\n Returns\n -------\n scalar\n The first element of %(klass)s.\n \"\"\"\n warnings.warn(\n \"`item` has been deprecated and will be removed in a future version\",\n FutureWarning,\n stacklevel=2,\n )\n return self.values.item()\n\n @property\n def data(self):\n \"\"\"\n Return the data pointer of the underlying data.\n\n .. deprecated:: 0.23.0\n \"\"\"\n warnings.warn(\n \"{obj}.data is deprecated and will be removed \"\n \"in a future version\".format(obj=type(self).__name__),\n FutureWarning,\n stacklevel=2,\n )\n return self.values.data\n\n @property\n def itemsize(self):\n \"\"\"\n Return the size of the dtype of the item of the underlying data.\n\n .. deprecated:: 0.23.0\n \"\"\"\n warnings.warn(\n \"{obj}.itemsize is deprecated and will be removed \"\n \"in a future version\".format(obj=type(self).__name__),\n FutureWarning,\n stacklevel=2,\n )\n return self._ndarray_values.itemsize\n\n @property\n def nbytes(self):\n \"\"\"\n Return the number of bytes in the underlying data.\n \"\"\"\n return self._values.nbytes\n\n @property\n def strides(self):\n \"\"\"\n Return the strides of the underlying data.\n\n .. deprecated:: 0.23.0\n \"\"\"\n warnings.warn(\n \"{obj}.strides is deprecated and will be removed \"\n \"in a future version\".format(obj=type(self).__name__),\n FutureWarning,\n stacklevel=2,\n )\n return self._ndarray_values.strides\n\n @property\n def size(self):\n \"\"\"\n Return the number of elements in the underlying data.\n \"\"\"\n return len(self._values)\n\n @property\n def flags(self):\n \"\"\"\n Return the ndarray.flags for the underlying data.\n\n .. deprecated:: 0.23.0\n \"\"\"\n warnings.warn(\n \"{obj}.flags is deprecated and will be removed \"\n \"in a future version\".format(obj=type(self).__name__),\n FutureWarning,\n stacklevel=2,\n )\n return self.values.flags\n\n @property\n def base(self):\n \"\"\"\n Return the base object if the memory of the underlying data is shared.\n\n .. deprecated:: 0.23.0\n \"\"\"\n warnings.warn(\n \"{obj}.base is deprecated and will be removed \"\n \"in a future version\".format(obj=type(self).__name__),\n FutureWarning,\n stacklevel=2,\n )\n return self.values.base\n\n @property\n def array(self) -> ExtensionArray:\n \"\"\"\n The ExtensionArray of the data backing this Series or Index.\n\n .. versionadded:: 0.24.0\n\n Returns\n -------\n ExtensionArray\n An ExtensionArray of the values stored within. For extension\n types, this is the actual array. For NumPy native types, this\n is a thin (no copy) wrapper around :class:`numpy.ndarray`.\n\n ``.array`` differs ``.values`` which may require converting the\n data to a different form.\n\n See Also\n --------\n Index.to_numpy : Similar method that always returns a NumPy array.\n Series.to_numpy : Similar method that always returns a NumPy array.\n\n Notes\n -----\n This table lays out the different array types for each extension\n dtype within pandas.\n\n ================== =============================\n dtype array type\n ================== =============================\n category Categorical\n period PeriodArray\n interval IntervalArray\n IntegerNA IntegerArray\n datetime64[ns, tz] DatetimeArray\n ================== =============================\n\n For any 3rd-party extension types, the array type will be an\n ExtensionArray.\n\n For all remaining dtypes ``.array`` will be a\n :class:`arrays.NumpyExtensionArray` wrapping the actual ndarray\n stored within. If you absolutely need a NumPy array (possibly with\n copying / coercing data), then use :meth:`Series.to_numpy` instead.\n\n Examples\n --------\n\n For regular NumPy types like int, and float, a PandasArray\n is returned.\n\n >>> pd.Series([1, 2, 3]).array\n <PandasArray>\n [1, 2, 3]\n Length: 3, dtype: int64\n\n For extension types, like Categorical, the actual ExtensionArray\n is returned\n\n >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))\n >>> ser.array\n [a, b, a]\n Categories (2, object): [a, b]\n \"\"\"\n # As a mixin, we depend on the mixing class having _values.\n # Special mixin syntax may be developed in the future:\n # https://github.com/python/typing/issues/246\n result = self._values # type: ignore\n\n if is_datetime64_ns_dtype(result.dtype):\n from pandas.arrays import DatetimeArray\n\n result = DatetimeArray(result)\n elif is_timedelta64_ns_dtype(result.dtype):\n from pandas.arrays import TimedeltaArray\n\n result = TimedeltaArray(result)\n\n elif not is_extension_array_dtype(result.dtype):\n from pandas.core.arrays.numpy_ import PandasArray\n\n result = PandasArray(result)\n\n return result\n\n def to_numpy(self, dtype=None, copy=False):\n \"\"\"\n A NumPy ndarray representing the values in this Series or Index.\n\n .. versionadded:: 0.24.0\n\n Parameters\n ----------\n dtype : str or numpy.dtype, optional\n The dtype to pass to :meth:`numpy.asarray`.\n copy : bool, default False\n Whether to ensure that the returned value is a not a view on\n another array. Note that ``copy=False`` does not *ensure* that\n ``to_numpy()`` is no-copy. Rather, ``copy=True`` ensure that\n a copy is made, even if not strictly necessary.\n\n Returns\n -------\n numpy.ndarray\n\n See Also\n --------\n Series.array : Get the actual data stored within.\n Index.array : Get the actual data stored within.\n DataFrame.to_numpy : Similar method for DataFrame.\n\n Notes\n -----\n The returned array will be the same up to equality (values equal\n in `self` will be equal in the returned array; likewise for values\n that are not equal). When `self` contains an ExtensionArray, the\n dtype may be different. For example, for a category-dtype Series,\n ``to_numpy()`` will return a NumPy array and the categorical dtype\n will be lost.\n\n For NumPy dtypes, this will be a reference to the actual data stored\n in this Series or Index (assuming ``copy=False``). Modifying the result\n in place will modify the data stored in the Series or Index (not that\n we recommend doing that).\n\n For extension types, ``to_numpy()`` *may* require copying data and\n coercing the result to a NumPy type (possibly object), which may be\n expensive. When you need a no-copy reference to the underlying data,\n :attr:`Series.array` should be used instead.\n\n This table lays out the different dtypes and default return types of\n ``to_numpy()`` for various dtypes within pandas.\n\n ================== ================================\n dtype array type\n ================== ================================\n category[T] ndarray[T] (same dtype as input)\n period ndarray[object] (Periods)\n interval ndarray[object] (Intervals)\n IntegerNA ndarray[object]\n datetime64[ns] datetime64[ns]\n datetime64[ns, tz] ndarray[object] (Timestamps)\n ================== ================================\n\n Examples\n --------\n >>> ser = pd.Series(pd.Categorical(['a', 'b', 'a']))\n >>> ser.to_numpy()\n array(['a', 'b', 'a'], dtype=object)\n\n Specify the `dtype` to control how datetime-aware data is represented.\n Use ``dtype=object`` to return an ndarray of pandas :class:`Timestamp`\n objects, each with the correct ``tz``.\n\n >>> ser = pd.Series(pd.date_range('2000', periods=2, tz=\"CET\"))\n >>> ser.to_numpy(dtype=object)\n array([Timestamp('2000-01-01 00:00:00+0100', tz='CET', freq='D'),\n Timestamp('2000-01-02 00:00:00+0100', tz='CET', freq='D')],\n dtype=object)\n\n Or ``dtype='datetime64[ns]'`` to return an ndarray of native\n datetime64 values. The values are converted to UTC and the timezone\n info is dropped.\n\n >>> ser.to_numpy(dtype=\"datetime64[ns]\")\n ... # doctest: +ELLIPSIS\n array(['1999-12-31T23:00:00.000000000', '2000-01-01T23:00:00...'],\n dtype='datetime64[ns]')\n \"\"\"\n if is_datetime64tz_dtype(self.dtype) and dtype is None:\n # note: this is going to change very soon.\n # I have a WIP PR making this unnecessary, but it's\n # a bit out of scope for the DatetimeArray PR.\n dtype = \"object\"\n\n result = np.asarray(self._values, dtype=dtype)\n # TODO(GH-24345): Avoid potential double copy\n if copy:\n result = result.copy()\n return result\n\n @property\n def _ndarray_values(self) -> np.ndarray:\n \"\"\"\n The data as an ndarray, possibly losing information.\n\n The expectation is that this is cheap to compute, and is primarily\n used for interacting with our indexers.\n\n - categorical -> codes\n \"\"\"\n if is_extension_array_dtype(self):\n return self.array._ndarray_values\n # As a mixin, we depend on the mixing class having values.\n # Special mixin syntax may be developed in the future:\n # https://github.com/python/typing/issues/246\n return self.values # type: ignore\n\n @property\n def empty(self):\n return not self.size\n\n def max(self, axis=None, skipna=True, *args, **kwargs):\n \"\"\"\n Return the maximum value of the Index.\n\n Parameters\n ----------\n axis : int, optional\n For compatibility with NumPy. Only 0 or None are allowed.\n skipna : bool, default True\n\n Returns\n -------\n scalar\n Maximum value.\n\n See Also\n --------\n Index.min : Return the minimum value in an Index.\n Series.max : Return the maximum value in a Series.\n DataFrame.max : Return the maximum values in a DataFrame.\n\n Examples\n --------\n >>> idx = pd.Index([3, 2, 1])\n >>> idx.max()\n 3\n\n >>> idx = pd.Index(['c', 'b', 'a'])\n >>> idx.max()\n 'c'\n\n For a MultiIndex, the maximum is determined lexicographically.\n\n >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])\n >>> idx.max()\n ('b', 2)\n \"\"\"\n nv.validate_minmax_axis(axis)\n nv.validate_max(args, kwargs)\n return nanops.nanmax(self._values, skipna=skipna)\n\n def argmax(self, axis=None, skipna=True, *args, **kwargs):\n \"\"\"\n Return an ndarray of the maximum argument indexer.\n\n Parameters\n ----------\n axis : {None}\n Dummy argument for consistency with Series.\n skipna : bool, default True\n\n Returns\n -------\n numpy.ndarray\n Indices of the maximum values.\n\n See Also\n --------\n numpy.ndarray.argmax\n \"\"\"\n nv.validate_minmax_axis(axis)\n nv.validate_argmax_with_skipna(skipna, args, kwargs)\n return nanops.nanargmax(self._values, skipna=skipna)\n\n def min(self, axis=None, skipna=True, *args, **kwargs):\n \"\"\"\n Return the minimum value of the Index.\n\n Parameters\n ----------\n axis : {None}\n Dummy argument for consistency with Series.\n skipna : bool, default True\n\n Returns\n -------\n scalar\n Minimum value.\n\n See Also\n --------\n Index.max : Return the maximum value of the object.\n Series.min : Return the minimum value in a Series.\n DataFrame.min : Return the minimum values in a DataFrame.\n\n Examples\n --------\n >>> idx = pd.Index([3, 2, 1])\n >>> idx.min()\n 1\n\n >>> idx = pd.Index(['c', 'b', 'a'])\n >>> idx.min()\n 'a'\n\n For a MultiIndex, the minimum is determined lexicographically.\n\n >>> idx = pd.MultiIndex.from_product([('a', 'b'), (2, 1)])\n >>> idx.min()\n ('a', 1)\n \"\"\"\n nv.validate_minmax_axis(axis)\n nv.validate_min(args, kwargs)\n return nanops.nanmin(self._values, skipna=skipna)\n\n def argmin(self, axis=None, skipna=True, *args, **kwargs):\n \"\"\"\n Return a ndarray of the minimum argument indexer.\n\n Parameters\n ----------\n axis : {None}\n Dummy argument for consistency with Series.\n skipna : bool, default True\n\n Returns\n -------\n numpy.ndarray\n\n See Also\n --------\n numpy.ndarray.argmin\n \"\"\"\n nv.validate_minmax_axis(axis)\n nv.validate_argmax_with_skipna(skipna, args, kwargs)\n return nanops.nanargmin(self._values, skipna=skipna)\n\n def tolist(self):\n \"\"\"\n Return a list of the values.\n\n These are each a scalar type, which is a Python scalar\n (for str, int, float) or a pandas scalar\n (for Timestamp/Timedelta/Interval/Period)\n\n Returns\n -------\n list\n\n See Also\n --------\n numpy.ndarray.tolist\n \"\"\"\n if self.dtype.kind in [\"m\", \"M\"]:\n return [com.maybe_box_datetimelike(x) for x in self._values]\n elif is_extension_array_dtype(self._values):\n return list(self._values)\n else:\n return self._values.tolist()\n\n to_list = tolist\n\n def __iter__(self):\n \"\"\"\n Return an iterator of the values.\n\n These are each a scalar type, which is a Python scalar\n (for str, int, float) or a pandas scalar\n (for Timestamp/Timedelta/Interval/Period)\n\n Returns\n -------\n iterator\n \"\"\"\n # We are explicitly making element iterators.\n if self.dtype.kind in [\"m\", \"M\"]:\n return map(com.maybe_box_datetimelike, self._values)\n elif is_extension_array_dtype(self._values):\n return iter(self._values)\n else:\n return map(self._values.item, range(self._values.size))\n\n @cache_readonly\n def hasnans(self):\n \"\"\"\n Return if I have any nans; enables various perf speedups.\n \"\"\"\n return bool(isna(self).any())\n\n def _reduce(\n self, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds\n ):\n \"\"\" perform the reduction type operation if we can \"\"\"\n func = getattr(self, name, None)\n if func is None:\n raise TypeError(\n \"{klass} cannot perform the operation {op}\".format(\n klass=self.__class__.__name__, op=name\n )\n )\n return func(skipna=skipna, **kwds)\n\n def _map_values(self, mapper, na_action=None):\n \"\"\"\n An internal function that maps values using the input\n correspondence (which can be a dict, Series, or function).\n\n Parameters\n ----------\n mapper : function, dict, or Series\n The input correspondence object\n na_action : {None, 'ignore'}\n If 'ignore', propagate NA values, without passing them to the\n mapping function\n\n Returns\n -------\n Union[Index, MultiIndex], inferred\n The output of the mapping function applied to the index.\n If the function returns a tuple with more than one element\n a MultiIndex will be returned.\n\n \"\"\"\n\n # we can fastpath dict/Series to an efficient map\n # as we know that we are not going to have to yield\n # python types\n if isinstance(mapper, dict):\n if hasattr(mapper, \"__missing__\"):\n # If a dictionary subclass defines a default value method,\n # convert mapper to a lookup function (GH #15999).\n dict_with_default = mapper\n mapper = lambda x: dict_with_default[x]\n else:\n # Dictionary does not have a default. Thus it's safe to\n # convert to an Series for efficiency.\n # we specify the keys here to handle the\n # possibility that they are tuples\n from pandas import Series\n\n mapper = Series(mapper)\n\n if isinstance(mapper, ABCSeries):\n # Since values were input this means we came from either\n # a dict or a series and mapper should be an index\n if is_categorical_dtype(self._values):\n # use the built in categorical series mapper which saves\n # time by mapping the categories instead of all values\n return self._values.map(mapper)\n if is_extension_array_dtype(self.dtype):\n values = self._values\n else:\n values = self.values\n\n indexer = mapper.index.get_indexer(values)\n new_values = algorithms.take_1d(mapper._values, indexer)\n\n return new_values\n\n # we must convert to python types\n if is_extension_array_dtype(self.dtype) and hasattr(self._values, \"map\"):\n # GH#23179 some EAs do not have `map`\n values = self._values\n if na_action is not None:\n raise NotImplementedError\n map_f = lambda values, f: values.map(f)\n else:\n values = self.astype(object)\n values = getattr(values, \"values\", values)\n if na_action == \"ignore\":\n\n def map_f(values, f):\n return lib.map_infer_mask(values, f, isna(values).view(np.uint8))\n\n else:\n map_f = lib.map_infer\n\n # mapper is a function\n new_values = map_f(values, mapper)\n\n return new_values\n\n def value_counts(\n self, normalize=False, sort=True, ascending=False, bins=None, dropna=True\n ):\n \"\"\"\n Return a Series containing counts of unique values.\n\n The resulting object will be in descending order so that the\n first element is the most frequently-occurring element.\n Excludes NA values by default.\n\n Parameters\n ----------\n normalize : bool, default False\n If True then the object returned will contain the relative\n frequencies of the unique values.\n sort : bool, default True\n Sort by frequencies.\n ascending : bool, default False\n Sort in ascending order.\n bins : int, optional\n Rather than count values, group them into half-open bins,\n a convenience for ``pd.cut``, only works with numeric data.\n dropna : bool, default True\n Don't include counts of NaN.\n\n Returns\n -------\n Series\n\n See Also\n --------\n Series.count: Number of non-NA elements in a Series.\n DataFrame.count: Number of non-NA elements in a DataFrame.\n\n Examples\n --------\n >>> index = pd.Index([3, 1, 2, 3, 4, np.nan])\n >>> index.value_counts()\n 3.0 2\n 4.0 1\n 2.0 1\n 1.0 1\n dtype: int64\n\n With `normalize` set to `True`, returns the relative frequency by\n dividing all values by the sum of values.\n\n >>> s = pd.Series([3, 1, 2, 3, 4, np.nan])\n >>> s.value_counts(normalize=True)\n 3.0 0.4\n 4.0 0.2\n 2.0 0.2\n 1.0 0.2\n dtype: float64\n\n **bins**\n\n Bins can be useful for going from a continuous variable to a\n categorical variable; instead of counting unique\n apparitions of values, divide the index in the specified\n number of half-open bins.\n\n >>> s.value_counts(bins=3)\n (2.0, 3.0] 2\n (0.996, 2.0] 2\n (3.0, 4.0] 1\n dtype: int64\n\n **dropna**\n\n With `dropna` set to `False` we can also see NaN index values.\n\n >>> s.value_counts(dropna=False)\n 3.0 2\n NaN 1\n 4.0 1\n 2.0 1\n 1.0 1\n dtype: int64\n \"\"\"\n result = value_counts(\n self,\n sort=sort,\n ascending=ascending,\n normalize=normalize,\n bins=bins,\n dropna=dropna,\n )\n return result\n\n def unique(self):\n values = self._values\n\n if hasattr(values, \"unique\"):\n\n result = values.unique()\n else:\n result = unique1d(values)\n\n return result\n\n def nunique(self, dropna=True):\n \"\"\"\n Return number of unique elements in the object.\n\n Excludes NA values by default.\n\n Parameters\n ----------\n dropna : bool, default True\n Don't include NaN in the count.\n\n Returns\n -------\n int\n\n See Also\n --------\n DataFrame.nunique: Method nunique for DataFrame.\n Series.count: Count non-NA/null observations in the Series.\n\n Examples\n --------\n >>> s = pd.Series([1, 3, 5, 7, 7])\n >>> s\n 0 1\n 1 3\n 2 5\n 3 7\n 4 7\n dtype: int64\n\n >>> s.nunique()\n 4\n \"\"\"\n uniqs = self.unique()\n n = len(uniqs)\n if dropna and isna(uniqs).any():\n n -= 1\n return n\n\n @property\n def is_unique(self):\n \"\"\"\n Return boolean if values in the object are unique.\n\n Returns\n -------\n bool\n \"\"\"\n return self.nunique(dropna=False) == len(self)\n\n @property\n def is_monotonic(self):\n \"\"\"\n Return boolean if values in the object are\n monotonic_increasing.\n\n Returns\n -------\n bool\n \"\"\"\n from pandas import Index\n\n return Index(self).is_monotonic\n\n is_monotonic_increasing = is_monotonic\n\n @property\n def is_monotonic_decreasing(self) -> bool:\n \"\"\"\n Return boolean if values in the object are\n monotonic_decreasing.\n\n Returns\n -------\n bool\n \"\"\"\n from pandas import Index\n\n return Index(self).is_monotonic_decreasing\n\n def memory_usage(self, deep=False):\n \"\"\"\n Memory usage of the values.\n\n Parameters\n ----------\n deep : bool\n Introspect the data deeply, interrogate\n `object` dtypes for system-level memory consumption.\n\n Returns\n -------\n bytes used\n\n See Also\n --------\n numpy.ndarray.nbytes\n\n Notes\n -----\n Memory usage does not include memory consumed by elements that\n are not components of the array if deep=False or if used on PyPy\n \"\"\"\n if hasattr(self.array, \"memory_usage\"):\n return self.array.memory_usage(deep=deep)\n\n v = self.array.nbytes\n if deep and is_object_dtype(self) and not PYPY:\n v += lib.memory_usage_of_objects(self.array)\n return v\n\n @Substitution(\n values=\"\",\n order=\"\",\n size_hint=\"\",\n sort=textwrap.dedent(\n \"\"\"\\\n sort : bool, default False\n Sort `uniques` and shuffle `codes` to maintain the\n relationship.\n \"\"\"\n ),\n )\n @Appender(algorithms._shared_docs[\"factorize\"])\n def factorize(self, sort=False, na_sentinel=-1):\n return algorithms.factorize(self, sort=sort, na_sentinel=na_sentinel)\n\n _shared_docs[\n \"searchsorted\"\n ] = \"\"\"\n Find indices where elements should be inserted to maintain order.\n\n Find the indices into a sorted %(klass)s `self` such that, if the\n corresponding elements in `value` were inserted before the indices,\n the order of `self` would be preserved.\n\n .. note::\n\n The %(klass)s *must* be monotonically sorted, otherwise\n wrong locations will likely be returned. Pandas does *not*\n check this for you.\n\n Parameters\n ----------\n value : array_like\n Values to insert into `self`.\n side : {'left', 'right'}, optional\n If 'left', the index of the first suitable location found is given.\n If 'right', return the last such index. If there is no suitable\n index, return either 0 or N (where N is the length of `self`).\n sorter : 1-D array_like, optional\n Optional array of integer indices that sort `self` into ascending\n order. They are typically the result of ``np.argsort``.\n\n Returns\n -------\n int or array of int\n A scalar or array of insertion points with the\n same shape as `value`.\n\n .. versionchanged:: 0.24.0\n If `value` is a scalar, an int is now always returned.\n Previously, scalar inputs returned an 1-item array for\n :class:`Series` and :class:`Categorical`.\n\n See Also\n --------\n sort_values\n numpy.searchsorted\n\n Notes\n -----\n Binary search is used to find the required insertion points.\n\n Examples\n --------\n\n >>> x = pd.Series([1, 2, 3])\n >>> x\n 0 1\n 1 2\n 2 3\n dtype: int64\n\n >>> x.searchsorted(4)\n 3\n\n >>> x.searchsorted([0, 4])\n array([0, 3])\n\n >>> x.searchsorted([1, 3], side='left')\n array([0, 2])\n\n >>> x.searchsorted([1, 3], side='right')\n array([1, 3])\n\n >>> x = pd.Categorical(['apple', 'bread', 'bread',\n 'cheese', 'milk'], ordered=True)\n [apple, bread, bread, cheese, milk]\n Categories (4, object): [apple < bread < cheese < milk]\n\n >>> x.searchsorted('bread')\n 1\n\n >>> x.searchsorted(['bread'], side='right')\n array([3])\n\n If the values are not monotonically sorted, wrong locations\n may be returned:\n\n >>> x = pd.Series([2, 1, 3])\n >>> x.searchsorted(1)\n 0 # wrong result, correct would be 1\n \"\"\"\n\n @Substitution(klass=\"Index\")\n @Appender(_shared_docs[\"searchsorted\"])\n def searchsorted(self, value, side=\"left\", sorter=None):\n return algorithms.searchsorted(self._values, value, side=side, sorter=sorter)\n\n def drop_duplicates(self, keep=\"first\", inplace=False):\n inplace = validate_bool_kwarg(inplace, \"inplace\")\n if isinstance(self, ABCIndexClass):\n if self.is_unique:\n return self._shallow_copy()\n\n duplicated = self.duplicated(keep=keep)\n result = self[np.logical_not(duplicated)]\n if inplace:\n return self._update_inplace(result)\n else:\n return result\n\n def duplicated(self, keep=\"first\"):\n if isinstance(self, ABCIndexClass):\n if self.is_unique:\n return np.zeros(len(self), dtype=np.bool)\n return duplicated(self, keep=keep)\n else:\n return self._constructor(\n duplicated(self, keep=keep), index=self.index\n ).__finalize__(self)\n\n # ----------------------------------------------------------------------\n # abstracts\n\n def _update_inplace(self, result, verify_is_copy=True, **kwargs):\n raise AbstractMethodError(self)\n"
]
| [
[
"pandas.arrays.DatetimeArray",
"pandas.core.dtypes.common.is_datetime64_ns_dtype",
"pandas.util._validators.validate_bool_kwarg",
"pandas.Series",
"pandas.core.common.get_callable_name",
"numpy.asarray",
"pandas.core.dtypes.common.is_extension_array_dtype",
"pandas.core.dtypes.common.is_datetime64tz_dtype",
"pandas.DataFrame",
"pandas.core.nanops.nanmin",
"pandas.core.dtypes.common.is_timedelta64_ns_dtype",
"pandas.util._decorators.Substitution",
"pandas.errors.AbstractMethodError",
"pandas.Index",
"pandas.core.algorithms.factorize",
"pandas.core.nanops.nanargmin",
"pandas.core.arrays.numpy_.PandasArray",
"pandas.core.algorithms.searchsorted",
"pandas.core.dtypes.cast.is_nested_object",
"pandas.core.dtypes.common.is_categorical_dtype",
"numpy.logical_not",
"pandas.core.dtypes.common.is_list_like",
"pandas.util._decorators.Appender",
"pandas.core.common.maybe_box_datetimelike",
"pandas.compat.numpy.function.validate_transpose",
"numpy.ndim",
"pandas.core.reshape.concat.concat",
"pandas.core.nanops.nanargmax",
"pandas.compat.numpy.function.validate_argmax_with_skipna",
"pandas.compat.numpy.function.validate_minmax_axis",
"pandas.core.algorithms.take_1d",
"pandas.core.dtypes.common.is_scalar",
"pandas.compat.numpy.function.validate_max",
"pandas.arrays.TimedeltaArray",
"pandas.core.algorithms.unique1d",
"pandas.core.algorithms.value_counts",
"pandas.compat.numpy.function.validate_min",
"pandas.core.dtypes.common.is_object_dtype",
"pandas._libs.lib.memory_usage_of_objects",
"pandas.core.dtypes.missing.isna",
"pandas.core.nanops.nanmax"
]
]
|
sheride/bcml4pheno | [
"c9629dafcdbee0a4c28ceb7b28c9862de8479a24"
]
| [
"bcml4pheno/bcml_model.py"
]
| [
"# AUTOGENERATED! DO NOT EDIT! File to edit: bcml_model.ipynb (unless otherwise specified).\n\n__all__ = ['bcml_model', 'refresh_model']\n\n# Cell\nimport numpy as np\nimport sklearn.metrics as skm\nimport scipy.interpolate\nimport scipy.optimize\nimport pandas as pd\nimport joblib\n\n# Cell\nclass bcml_model:\n \"\"\"\n Represents a machine learning (ML) binary classification (BC) model.\n \"\"\"\n\n def __init__(self, model):\n self.model = model\n\n def fit(self, preds, labels):\n r\"\"\"\n Fits `model` to data.\n\n `preds` should be ? $\\times$ $m$ for model with $m$ features. `labels` should\n be ? $\\times$ 1 and take values in $\\{0,1\\}$.\n \"\"\"\n self.model.fit(preds, labels)\n\n def predict_proba(self, preds):\n r\"\"\"\n Predicts signal probability for each element of a dataset ($? \\times m$ `numpy` array).\n\n Returns `numpy` array of with values in $[0,1]$ giving predicted signal probabilities for\n each data point.\n \"\"\"\n try:\n return self.model.predict_proba(preds)[:,1]\n except:\n print(\"self.model doesn't have a predict_proba function\")\n\n def predict(self, preds, threshold=None):\n r\"\"\"\n Predicts signal ($1$) or background ($0$) for each element of a dataset ($? \\times m$ `numpy` array).\n\n Returns `numpy` array of length with values in $\\{0,1\\}$ giving predicted classifications.\n\n Uses the `predict` method built into `scikit-learn` models.\n \"\"\"\n if threshold is not None:\n probs = self.model.predict_proba(preds)[:,1]\n return np.where(probs > threshold, np.ones_like(probs), np.zeros_like(probs))\n else:\n try:\n return self.model.predict(preds)\n except:\n print(\"self.model doesn't have a predict function\")\n\n def predict_hist(self, preds, labels, num_bins=100, sepbg=False, sig_norm=1, bg_norm=1, dataframe=False):\n r\"\"\"\n Constructs a histogram of predicted signal probabilities for signal and background constituents of\n a dataset ($? \\times M$ `numpy` array).\n\n If `sepbg` is `False` (the default), labels are assumed to take values in $\\{0,1\\}$. Backgrounds are treated in combination:\n a list of $3$ $?_i \\times m$ `numpy` arrays are returned, containing bin edges (partitioning $[0,1]$),\n signal bin contents, and background bin contents.\n\n If `sepbg` is `True`, labels are assumed to take values in $\\{-n,\\dots,-1,1\\}$ (if there are $n$ backgrounds) while\n `bg_norm` should be a list of length $n$. Backgrounds are then differentiated: a list of $2 + n$ `numpy` arrays of shape\n $?_i \\times m$ are returned, containing bin edges (partitioning $[0,1]$), signal bin contents, and\n $n$ background bin contents.\n \"\"\"\n predictions = self.predict_proba(preds)\n labels = np.array(labels)\n sig_bins, bin_edges = np.histogram(predictions[labels==1], bins=num_bins, density=True)\n sig_bins *= sig_norm\n if sepbg:\n bg_norms = bg_norm\n bg_binss = [\n bg_norm * np.histogram(predictions[labels==-(i+1)], bins=num_bins, density=True)[0]\n for i, bg_norm in enumerate(bg_norms)]\n if dataframe:\n return pd.DataFrame(data=[bin_edges, sig_bins] + bg_binss, columns=['Bin Edges', 'Signal'] + ['Background {}'.format(i) for i in range(1, self.num_bgs+1)])\n else:\n return [bin_edges, sig_bins] + bg_binss\n else:\n bg_bins = np.histogram(predictions[labels!=1], bins=num_bins, density=True)[0]\n if dataframe:\n return pd.DataFrame(data=[bin_edges, sig_bins, bg_bins], columns=['Bin Edges', 'Signal', 'Background'])\n else:\n return [bin_edges, sig_bins, bg_bins]\n\n def feature_importance(self):\n \"\"\"\n Returns the importance of the $M$ features used to train `self.model`.\n \"\"\"\n try:\n return self.model.feature_importances_\n except:\n try:\n return self.model[-1].feature_importances_\n except:\n print(\"It looks like self.model doesn't have an attribute 'feature_importances_'\")\n\n def sorted_feature_importance(self, features):\n r\"\"\"\n Returns list of features sorted by importance.\n\n Given arguments `features` and `importances`, lists of length $M$, returns list of size $M \\times 2$ where\n the first column gives features and the second their associated importances, sorted by importance.\n \"\"\"\n importances = self.feature_importance()\n ranked_indices = np.argsort(-np.abs(importances))\n return [[features[i], importances[i]] for i in ranked_indices]\n\n def accuracy(self, preds, labels, threshold=None):\n r\"\"\"\n Computes model accuracy on a dataset ($? x m$ predictors, length $?$ labels).\n\n Returns value in $[0,1]$ giving model accuracy on the provided predictors and labels.\n \"\"\"\n predictions = self.predict(preds=preds, threshold=threshold)\n return len(preds) - np.sum(np.abs(predictions - labels)) / len(preds)\n\n def conf_matrix(self, labels, predictions=None, preds=None):\n r\"\"\"\n Computes the confusion matrix of the trained model on a dataset ($? x M$ predictors, length $?$ labels).\n\n Returns $2 \\times 2$ confusion matrix using `sklearn.metrics.confusion_matrix`.\n\n If predictors `preds` aren't provided, `self.test_preds` is used.\n If `labels` aren't provided, `self.test_labels` is used.\n \"\"\"\n if predictions is not None:\n return skm.confusion_matrix(labels, predictions, labels=[0,1])\n elif preds is not None:\n return skm.confusion_matrix(labels, self.predict(preds), labels=[0,1])\n else:\n raise ValueError('Either predictions or preds must be passed.')\n\n\n def tpr_cm(self, conf_matrix):\n \"\"\"\n Computes the true positive rate (tpr; correctly identified signal/total signal)\n of a trained model given a confusion matrix.\n\n Returns value in $[0,1]$.\n \"\"\"\n return conf_matrix[1,1]/np.sum(conf_matrix[1])\n\n def fpr_cm(self, conf_matrix):\n \"\"\"\n Computes the false positive rate (fpr; misidentified background/total background)\n of a trained model given a confusion matrix.\n\n Returns value in $[0,1]$.\n \"\"\"\n return conf_matrix[0,1]/np.sum(conf_matrix[0])\n\n def tpr(self, labels, predictions=None, preds=None):\n r\"\"\"\n Computes the true positive rate (tpr; correctly identified signal/total signal)\n of a trained model given predictions and labels (both `numpy` array of length $?$ with values in $\\{0,1\\}$)\n\n Returns value in $[0,1]$.\n \"\"\"\n return self.tpr_cm(self.conf_matrix(labels, predictions=predictions, preds=preds))\n\n def fpr(self, labels, predictions=None, preds=None):\n r\"\"\"\n Computes the false positive rate (fpr; misidentified background/total background)\n of a trained model given predictions and labels (both `numpy` array of length $?$ with values in $\\{0,1\\}$)\n\n Returns value in $[0,1]$.\n \"\"\"\n return self.fpr_cm(self.conf_matrix(labels, predictions=predictions, preds=preds))\n\n def significance(self, signal, background, tpr, fpr, sepbg=False):\n r\"\"\"\n Computes signal significance of a trained model given signal and background yield.\n\n Returns a positive real number computed by\n $$\\frac{S \\cdot TPR}{\\sqrt{S \\cdot TPR + B \\cdot FPR}}$$\n which corresponds to signal significance after selecting only datapoints the model identifies as signal.\n\n If `sepbg` is `False`, `background` should be a single real number and is multiplied by `fpr`. If `sepbg` is `True`,\n `background` should be a list of length `self.num_bgs` where the $i$th element contains background yield of the $i$th\n background type. `fpr`, if passed, is then also a list of length `self.num_bgs` giving false positive rates for each\n of the background types.\n \"\"\"\n if sepbg:\n backgrounds = background\n fprs = fpr\n fprXbackground = np.sum(np.multiply(fprs, backgrounds), axis=-1)\n return (signal * tpr) / np.sqrt(signal * tpr + fprXbackground + 1e-10)\n else:\n return (signal * tpr) / np.sqrt(signal * tpr + background * fpr + 1e-10)\n\n def newvar2thresh(self, newvar):\n r\"\"\"\n Helper method for `bcml.max_allowable_threshold()`, `bcml.get_tprs_fprs()`, and `bcml.best_threshold()`,\n performing change of variables from `newvar` to `threshold`\n\n In particular, threshold $= 1 - 10^{\\text{newvar}}$\n \"\"\"\n return 1 - np.power(10, newvar)\n\n def thresh2newvar(self, thresh):\n r\"\"\"\n Helper method for `bcml.max_allowable_threshold()`, `bcml.get_tprs_fprs()`, and `bcml.best_threshold()`,\n performing change of variables from `threshold` to `newvar`\n\n In particular, newvar $= \\log_{10}(1 - \\text{threhold})$\n \"\"\"\n return np.log10(1 - thresh)\n\n def max_allowable_threshold(self, preds, labels, sigYield):\n \"\"\"\n Returns the highest threshold such that only labelling elements of `self.test_pred` with predicted\n probabilities higher than that threshold as signal still yields 25 signal.\n\n To achieve a discovery potential of $5\\sigma$, even in the best case scenario ($TPR = 1, FPR = 0$) we still\n require $5^2 = 25$ signal events, hence we cannot chose a threshold so high that we do not keep at least\n 25 signal events.\n \"\"\"\n\n sig_indx = np.where(np.array(labels)==1)[0]\n preds = np.array(preds)[sig_indx]\n probs = self.predict_proba(preds)\n num_predicts = np.array(\n [np.sum(np.where(probs > self.newvar2thresh(newvar),np.ones_like(probs), np.zeros_like(probs)))\n for newvar in newvars])\n num_sig_yields = (num_predicts / len(preds)) * sigYield\n return [newvars, num_sig_yields]\n# f = scipy.interpolate.interp1d(num_sig_yield, newvars, kind='cubic')\n# return self.newvar2thresh(f(25))\n\n def get_tprs_fprs(self, preds, labels, sepbg=False):\n \"\"\"\n Produces (true positive rate, false positive rate) pairs for various thresholds\n for the trained model on data sets.\n\n If `sepbg` is `True`, labels should take values in $\\{-n,\\dots,-1,1\\}$. Background is combined and a list of length $4$\n is returned containing a list of $L$ sampled newvars (a convenient change of variable to approach arbitrarily close to 1:\n related to thresholds by `bcml_model.newvar2thresh()`), an $L$-list of tprs associated to those thresholds, an $L$-list of fprs\n related to those thresholds, and an $L$-list of length $?$ `numpy` arrays giving the predicted signal probabilities\n for the given data set.\n\n If `sepbg` is `Frue`, labels should take values in $\\{0,1\\}$. Background is split and a list of length $4$ `self.num_bgs`\n is returned containing a list of $L$ sampled newvars, an $L$-list of tprs associated to those thresholds, an $L$-list of lists of length\n $n$ (number of backgrounds) containing fprs for each background type for each threshold, and an $L$-list of length $?$\n \"\"\"\n # setting up variables\n min_newvar, max_newvar = [-10, 0]\n newvars = np.concatenate((np.linspace(min_newvar, -2, 10, endpoint=False), np.linspace(-2, max_newvar, 15, endpoint=False)))\n\n # computing tprs, fprs\n if sepbg:\n num_bgs = len(np.unique(labels)) - 1\n labelTypes = [1] + [-(i+1) for i in range(num_bgs)]\n labelsIndices = [np.where(np.array(labels)==i)[0] for i in labelTypes]\n# print(np.array(labelsIndices).shape)\n predss = [preds[indices] for indices in labelsIndices]\n# print(predss[0][:10])\n probss = [self.predict_proba(preds) for preds in predss]\n# print(probsss[0][:10])\n predictionsss = np.array(\n [[np.where(probs > self.newvar2thresh(newvar),\n np.ones_like(probs), np.zeros_like(probs)) for probs in probss] for newvar in newvars])\n sig_conf_matrices = [\n self.conf_matrix(labels=np.ones_like(predictionss[0]), predictions=predictionss[0]) for predictionss in predictionsss]\n bg_conf_matricess = [\n [self.conf_matrix(labels=np.zeros_like(predictions), predictions=predictions) for i, predictions in enumerate(predictionss[1:])] for predictionss in predictionsss]\n tprs = np.array([self.tpr_cm(conf_matrix) for conf_matrix in sig_conf_matrices])\n fprss = np.array([[self.fpr_cm(conf_matrix) for conf_matrix in conf_matrices] for conf_matrices in bg_conf_matricess])\n sums = tprs + np.sum(fprss, axis=1)\n cutoff = len(sums) - np.argmax(np.flip(sums)==0) + 1 if 0 in sums else 0\n return [newvars[cutoff:], tprs[cutoff:], fprss[cutoff:], probss]\n else:\n probs = self.predict_proba(preds)\n predictionss = np.array(\n [np.where(probs > self.newvar2thresh(newvar),\n np.ones_like(probs), np.zeros_like(probs)) for newvar in newvars])\n conf_matrices = [self.conf_matrix(labels=labels, predictions=predictions) for predictions in predictionss]\n tprs = np.array([self.tpr_cm(conf_matrix) for conf_matrix in conf_matrices])\n fprs = np.array([self.fpr_cm(conf_matrix) for conf_matrix in conf_matrices])\n sums = tprs + fprs\n cutoff = len(sums) - np.argmax(np.flip(sums)==0) + 1 if 0 in sums else 0\n return [newvars[cutoff:], tprs[cutoff:], fprs[cutoff:], probs]\n\n def best_threshold(self, signal, background, preds, labels, sepbg=False):\n \"\"\"\n Optimizes the threshold on a given data set ($? x M$ predictors, length $?$ labels).\n \"\"\"\n newvars, tprs, fprs, probs = self.get_tprs_fprs(preds, labels, sepbg)\n significances = -self.significance(signal, background, tprs, fprs, sepbg=sepbg)\n\n # interpolating significance as a function of threshold, then maximizing\n max_sig = np.amin(significances)\n significances_list = list(significances)\n i = significances_list.index(max_sig)\n min_i, max_i = [max(0,i-4),min(len(significances),i+5)]\n f = scipy.interpolate.interp1d(newvars[min_i:max_i], significances[min_i:max_i], kind='cubic')\n res = scipy.optimize.minimize(f, [0.5 * (newvars[min_i] + newvars[max_i-1])], bounds=[(newvars[min_i] + 1e-1, newvars[max_i-1] - 1e-1)])\n\n # computing significance, tpr, fpr for optimized threshold\n best_threshold = self.newvar2thresh(res.x[0])\n if sepbg:\n probss = probs\n fprss = fprs\n best_predictss = [np.where(probs > best_threshold, np.ones_like(probs), np.zeros_like(probs)) for probs in probss]\n sig_conf_matrix = self.conf_matrix(labels=np.ones_like(best_predictss[0]), predictions=best_predictss[0])\n bg_conf_matrices = [self.conf_matrix(labels=np.zeros_like(best_predicts), predictions=best_predicts) for i, best_predicts in enumerate(best_predictss[1:])]\n tpr = self.tpr_cm(sig_conf_matrix)\n fprs = [self.fpr_cm(conf_matrix) for conf_matrix in bg_conf_matrices]\n best_sig = self.significance(signal, background, tpr, fprs, sepbg=sepbg)\n return [best_threshold, best_sig, tpr, fprs, tprs, fprss]\n else:\n best_predicts = np.where(probs > best_threshold, np.ones_like(probs), np.zeros_like(probs))\n conf_matrix = self.conf_matrix(labels=labels, predictions=best_predicts)\n tpr = self.tpr_cm(conf_matrix)\n fpr = self.fpr_cm(conf_matrix)\n best_sig = self.significance(signal, background, tpr, fpr, sepbg=sepbg)\n return [best_threshold, best_sig, tpr, fpr, tprs, fprs]\n\n def req_sig_cs(self, lumi, bg_cs, tpr, fpr, sig=5, sepbg=False):\n \"\"\"\n Given a luminosity (in fb$^{-1}$), a background cross section (in pb), a true positive rate, a false positive rate,\n and a signal significance, computes the signal cross section required for the signal significance to be achieved.\n\n If `sepbg` is False, background is combined and a single FPR is used; if `sepbg` is True, it is assumed that\n `bg_cs`, `fpr` are each lists of length $n$ (number of backgrounds) and their vector dot product is used for background yield.\n \"\"\"\n conv = 10**15 / 10**12\n if sepbg:\n bg = np.sum(np.multiply(bg_cs, fpr))\n coef = [-tpr**2 * lumi * conv**2, sig**2 * tpr * conv, sig**2 * bg * conv]\n else:\n coef = [-tpr**2 * lumi * conv**2, sig**2 * tpr * conv, sig**2 * fpr * bg_cs * conv]\n return np.amax(np.roots(coef))\n\n def save_model(self, filename):\n \"\"\"\n Saves the model to `filename.joblib`\n \"\"\"\n joblib.dump(self.model, filename + '.joblib')\n\n# Cell\ndef refresh_model(model):\n \"\"\"\n If this class gets updated, run this function on your already trained model to have it reflect the updated\n class without retraining being necessary.\n \"\"\"\n return bcml_model(model.model)"
]
| [
[
"numpy.ones_like",
"numpy.abs",
"numpy.multiply",
"numpy.power",
"numpy.amin",
"numpy.sqrt",
"numpy.linspace",
"numpy.unique",
"sklearn.metrics.confusion_matrix",
"pandas.DataFrame",
"numpy.roots",
"numpy.log10",
"numpy.zeros_like",
"numpy.flip",
"numpy.array",
"numpy.histogram",
"numpy.sum"
]
]
|
a97001/merge-csv | [
"d8cd11c55e8a8a383c003151ec37fa751ca02e85"
]
| [
"join_by_columns.py"
]
| [
"import json\nimport pandas as pd\nimport os\nimport time\n\nconfigPath = os.path.join(os.getcwd(), 'config.json')\nwith open(configPath, 'r') as f:\n config = json.load(f)\n\n\nfiles = []\nfor (dirpath, dirnames, filenames) in os.walk(config['csvFolder']):\n for f in filenames:\n if f.lower().endswith(('.csv')):\n files.append({ 'uri': os.path.join(dirpath, f), 'filename': f })\n\nresultFile = None\n\nbaseCSV = pd.read_csv(\"/home/kelvin/Desktop/WCC-1.csv\", skip_blank_lines=True)\nbaseCSV['Date'] = baseCSV['Date'] + ' ' + baseCSV['Time']\nbaseCSV['Date'] = pd.to_datetime(baseCSV['Date'])\nbaseCSV = baseCSV.set_index('Date')\n\n# print(baseCSV)\nresultFile = baseCSV\nfor csv in files:\n print(csv)\n csvConfig = config['defaultSettings']\n if csv['filename'] in config['csvFiles']:\n csvConfig = config['csvFiles'][csv['filename']]\n df = pd.read_csv(csv['uri'], skip_blank_lines=True)\n df['Date'] = df['Report Timings:'] + ' ' + df['All Hours']\n df['Date'] = pd.to_datetime(df['Date'], format='%d/%m/%Y %H:%M:%S')\n df = df.set_index('Date')\n df.index = df.index.map(lambda x: x.replace(second=0))\n # print(df)\n # if resultFile is None:\n # resultFile = df\n # else:\n # resultFile = resultFile.append(df, ignore_index=True, sort=False)\n baseCSV[csv['filename']] = df['Unnamed: 2']\n\n# print(resultFile)\nresultFile.to_csv(os.path.join(config['exportFolder'], \"exported-\"+str(int(time.time())) +\".csv\"), index=True, na_rep='')\nprint('file exported ' + os.path.join(config['exportFolder'], \"exported-\"+str(int(time.time())) +\".csv\"))"
]
| [
[
"pandas.read_csv",
"pandas.to_datetime"
]
]
|
lelange/memilio | [
"e90aa96a3494899c54cd6326a31687d37f5505c8"
]
| [
"pycode/memilio-epidata/memilio/epidata_test/test_epidata_get_RKI_Data.py"
]
| [
"#############################################################################\n# Copyright (C) 2020-2021 German Aerospace Center (DLR-SC)\n#\n# Authors: \n#\n# Contact: Martin J. Kuehn <[email protected]>\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#############################################################################\nimport unittest\nfrom pyfakefs import fake_filesystem_unittest\n\nimport os\nimport json\nimport pandas as pd\nimport numpy as np\n\nfrom memilio.epidata import getRKIData as grki\nfrom memilio.epidata import getDataIntoPandasDataFrame as gd\nfrom unittest.mock import patch\n\n\nclass test_get_RKI_Data(fake_filesystem_unittest.TestCase):\n path = '/home/RKI_Data'\n\n # strings for read, download and update data\n # be careful: not completely realistic data\n # Get a file object with write permission.\n here = os.path.dirname(os.path.abspath(__file__))\n filename = os.path.join(here, 'test_epidata_get_RKI_Data_data.json')\n file_object = open(filename, 'r')\n # Load JSON file data to a python dict object.\n dict_object = json.load(file_object)\n\n # Add aldo test data to new data with every county to reduce changes in tests to an minimum\n # With new data there are three additional cases with 1 case and 1 recovered for\n # 15.04.2020 (male, A0-A4), 15.03.2020 (male, A05-A14), 15.06.2020 (female, A15-A34)\n # All three cases are recovered\n test_string_all_federal_states_and_counties = json.dumps(dict_object)[:-1] +\\\n (\"\"\",{\"IdBundesland\":1,\"Bundesland\":\"Schleswig-Holstein\",\"Landkreis\":\"SK Kiel\",\n \"Altersgruppe\":\"A60-A79\" ,\"Geschlecht\":\"M\",\"AnzahlFall\":1,\"AnzahlTodesfall\":0,\"ObjectId\":1,\n \"Meldedatum\":\"2020\\/08\\/11 00:00:00+00\", \"IdLandkreis\":1002,\"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0,\n \"NeuerTodesfall\":-9, \"Refdatum\":\"2020\\/08\\/07 00:00:00+00\",\"NeuGenesen\":0,\"AnzahlGenesen\":1,\n \"IstErkrankungsbeginn\":1, \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"},\n {\"IdBundesland\":1,\n \"Bundesland\":\"Schleswig-Holstein\",\"Landkreis\":\"SK Flensburg\",\"Altersgruppe\":\"A60-A79\", \"Geschlecht\":\"M\",\n \"AnzahlFall\":1,\"AnzahlTodesfall\":1,\"ObjectId\":617,\"Meldedatum\":\"2020\\/03\\/24 00:00:00+00\", \"IdLandkreis\":1001,\n \"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0,\"NeuerTodesfall\":0, \"Refdatum\":\"2020\\/08\\/07 00:00:00+00\",\n \"NeuGenesen\":-9,\"AnzahlGenesen\":0,\"IstErkrankungsbeginn\":1, \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"},\n {\"IdBundesland\":2,\"Bundesland\":\"Hamburg\", \"Landkreis\":\"SK Hamburg\",\"Altersgruppe\":\"A15-A34\",\"Geschlecht\":\"W\",\n \"AnzahlFall\":1,\"AnzahlTodesfall\":0, \"ObjectId\":26489,\"Meldedatum\":\"2020\\/08\\/13 00:00:00+00\",\"IdLandkreis\":2000,\n \"Datenstand\":\"25.01.2021, 00:00 Uhr\", \"NeuerFall\":0,\"NeuerTodesfall\":-9,\"Refdatum\":\"2020\\/08\\/07 00:00:00+00\",\n \"NeuGenesen\":0,\"AnzahlGenesen\":1, \"IstErkrankungsbeginn\":1,\"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"},\n {\"IdBundesland\":3, \"Bundesland\":\"Niedersachsen\",\"Landkreis\":\"LK Wittmund\",\"Altersgruppe\":\"A60-A79\",\n \"Geschlecht\":\"M\",\"AnzahlFall\":1, \"AnzahlTodesfall\":0,\"ObjectId\":121122,\"Meldedatum\":\"2020\\/08\\/07 00:00:00+00\",\n \"IdLandkreis\":3462, \"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0,\"NeuerTodesfall\":-9,\n \"Refdatum\":\"2021\\/01\\/09 00:00:00+00\", \"NeuGenesen\":0,\"AnzahlGenesen\":1,\"IstErkrankungsbeginn\":0,\n \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":4,\"Bundesland\":\"Bremen\",\"Landkreis\":\"SK Bremen\",\n \"Altersgruppe\":\"A15-A34\",\"Geschlecht\":\"W\", \"AnzahlFall\":1,\"AnzahlTodesfall\":0,\"ObjectId\":123459,\n \"Meldedatum\":\"2021\\/04\\/04 00:00:00+00\",\"IdLandkreis\":4011, \"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0,\n \"NeuerTodesfall\":-9,\"Refdatum\":\"2020\\/08\\/07 00:00:00+00\", \"NeuGenesen\":0,\"AnzahlGenesen\":1,\n \"IstErkrankungsbeginn\":1,\"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":5,\n \"Bundesland\":\"Nordrhein-Westfalen\",\"Landkreis\":\"SK D\\\\u00fcsseldorf\",\"Altersgruppe\":\"A15-A34\", \"Geschlecht\":\"M\",\n \"AnzahlFall\":1,\"AnzahlTodesfall\":0,\"ObjectId\":125996,\"Meldedatum\":\"2020\\/08\\/07 00:00:00+00\", \"IdLandkreis\":5111,\n \"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0,\"NeuerTodesfall\":-9, \"Refdatum\":\"2020\\/06\\/22 00:00:00+00\",\n \"NeuGenesen\":0,\"AnzahlGenesen\":1,\"IstErkrankungsbeginn\":0, \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"},\n {\"IdBundesland\":6,\"Bundesland\":\"Hessen\", \"Landkreis\":\"LK Gie\\\\u00dfen\", \"Altersgruppe\":\"A60-A79\",\n \"Geschlecht\":\"W\", \"AnzahlFall\":1,\"AnzahlTodesfall\":1, \"ObjectId\":408175, \"Meldedatum\":\"2020\\/04\\/21 00:00:00+00\",\n \"IdLandkreis\":6531, \"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0, \"NeuerTodesfall\":0,\n \"Refdatum\":\"2020\\/04\\/13 00:00:00+00\", \"NeuGenesen\":0, \"AnzahlGenesen\":1, \"IstErkrankungsbeginn\":1,\n \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":7, \"Bundesland\":\"Rheinland-Pfalz\",\"Landkreis\":\\\n \"LK Bernkastel-Wittlich\",\"Altersgruppe\":\"A35-A59\", \"Geschlecht\":\"W\", \"AnzahlFall\":1,\"AnzahlTodesfall\":0,\n \"ObjectId\":453169,\"Meldedatum\":\"2020\\/08\\/08 00:00:00+00\", \"IdLandkreis\":7231, \"Datenstand\":\"25.01.2021,\n 00:00 Uhr\",\"NeuerFall\":0,\"NeuerTodesfall\":-9,\"Refdatum\": \"2020\\/08\\/08 00:00:00+00\", \"NeuGenesen\":-9,\n \"AnzahlGenesen\":0,\"IstErkrankungsbeginn\":1, \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":8,\n \"Bundesland\":\"Baden-W\\\\u00fcrttemberg\", \"Landkreis\":\"LK Ludwigsburg\",\"Altersgruppe\":\"A15-A34\", \"Geschlecht\":\"W\",\n \"AnzahlFall\":2,\"AnzahlTodesfall\":0, \"ObjectId\":512433,\"Meldedatum\":\"2020\\/03\\/25 00:00:00+00\",\n \"IdLandkreis\":8118,\"Datenstand\":\"25.01.2021, 00:00 Uhr\", \"NeuerFall\":0,\"NeuerTodesfall\":-9,\n \"Refdatum\":\"2020\\/03\\/25 00:00:00+00\",\"NeuGenesen\":0,\"AnzahlGenesen\":2, \"IstErkrankungsbeginn\":0,\n \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":9, \"Bundesland\":\"Bayern\",\"Landkreis\":\\\n \"LK Pfaffenhofen a.d.Ilm\", \"Altersgruppe\":\"A35-A59\", \"Geschlecht\":\"M\", \"AnzahlFall\":1,\"AnzahlTodesfall\":0,\n \"ObjectId\":694772, \"Meldedatum\":\"2020\\/08\\/11 00:00:00+00\", \"IdLandkreis\":9186, \"Datenstand\":\"25.01.2021, 00:00 Uhr\"\n ,\"NeuerFall\":0, \"NeuerTodesfall\":-9,\"Refdatum\": \"2020\\/08\\/11 00:00:00+00\", \"NeuGenesen\":0,\"AnzahlGenesen\":1,\n \"IstErkrankungsbeginn\":1,\"Altersgruppe2\": \"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":10,\"Bundesland\":\"Saarland\",\n \"Landkreis\":\"LK Merzig-Wadern\",\"Altersgruppe\":\"A60-A79\",\"Geschlecht\":\"W\", \"AnzahlFall\":1,\"AnzahlTodesfall\":0,\n \"ObjectId\":853265,\"Meldedatum\":\"2020\\/06\\/10 00:00:00+00\",\"IdLandkreis\":10042, \"Datenstand\":\"25.01.2021,\n 00:00 Uhr\", \"NeuerFall\":0,\"NeuerTodesfall\":-9,\"Refdatum\":\"2020\\/06\\/10 00:00:00+00\", \"NeuGenesen\":0,\n \"AnzahlGenesen\":1,\"IstErkrankungsbeginn\":0,\"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":11,\n \"Bundesland\":\"Berlin\",\"Landkreis\":\"SK Berlin Charlottenburg-Wilmersdorf\", \"Altersgruppe\": \"A60-A79\",\n \"Geschlecht\":\"M\",\"AnzahlFall\":1,\"AnzahlTodesfall\":0,\"ObjectId\":879504,\"Meldedatum\": \"2020\\/06\\/04 00:00:00+00\",\n \"IdLandkreis\":11004,\"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0, \"NeuerTodesfall\" :-9,\n \"Refdatum\":\"2020\\/06\\/04 00:00:00+00\",\"NeuGenesen\":0,\"AnzahlGenesen\":1, \"IstErkrankungsbeginn\":1,\n \"Altersgruppe2\": \"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":11, \"Bundesland\":\"Berlin\", \"Landkreis\":\\\n \"SK Berlin Lichtenberg\",\"Altersgruppe\":\"A60-A79\", \"Geschlecht\": \"M\",\"AnzahlFall\":1, \"AnzahlTodesfall\":0,\\\n \"ObjectId\":907757, \"Meldedatum\":\"2020\\/06\\/04 00:00:00+00\", \"IdLandkreis\":11011 , \"Datenstand\":\\\n \"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0, \"NeuerTodesfall\":-9, \"Refdatum\":\"2020\\/06\\/04 00:00:00+00\", \"NeuGenesen\":0,\\\n \"AnzahlGenesen\":1, \"IstErkrankungsbeginn\":0, \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":12,\n \"Bundesland\":\"Brandenburg\",\"Landkreis\":\"LK Oberspreewald-Lausitz\",\"Altersgruppe\":\"A35-A59\", \"Geschlecht\":\"M\",\n \"AnzahlFall\":5,\"AnzahlTodesfall\":3,\"ObjectId\":941060,\"Meldedatum\":\"2020\\/08\\/10 00:00:00+00\",\n \"IdLandkreis\":12066, \"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0,\"NeuerTodesfall\":3,\"Refdatum\":\n \"2020\\/08\\/10 00:00:00+00\", \"NeuGenesen\":0,\"AnzahlGenesen\":2,\"IstErkrankungsbeginn\":1,\"Altersgruppe2\":\n \"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":13,\"Bundesland\":\"Mecklenburg-Vorpommern\",\"Landkreis\":\n \"LK Nordwestmecklenburg\", \"Altersgruppe\": \"A35-A59\",\"Geschlecht\":\"M\",\"AnzahlFall\":2,\"AnzahlTodesfall\":0,\n \"ObjectId\":962502,\"Meldedatum\": \"2021\\/01\\/12 00:00:00+00\",\"IdLandkreis\":13074,\"Datenstand\":\"25.01.2021,\n 00:00 Uhr\",\"NeuerFall\":0,\"NeuerTodesfall\" :-9, \"Refdatum\":\"2020\\/08\\/09 00:00:00+00\",\"NeuGenesen\":0,\n \"AnzahlGenesen\":2,\"IstErkrankungsbeginn\":1, \"Altersgruppe2\": \"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":14,\n \"Bundesland\":\"Sachsen\",\"Landkreis\":\"SK Chemnitz\", \"Altersgruppe\":\"A05-A14\",\"Geschlecht\":\"M\", \"AnzahlFall\":4,\n \"AnzahlTodesfall\":0,\"ObjectId\":967744, \"Meldedatum\":\"2020\\/08\\/09 00:00:00+00\", \"IdLandkreis\":14511,\n \"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0, \"NeuerTodesfall\":-9,\"Refdatum\": \"2020\\/12\\/10 00:00:00+00\",\n \"NeuGenesen\":0,\"AnzahlGenesen\":4, \"IstErkrankungsbeginn\":0,\"Altersgruppe2\": \"Nicht \\\\u00fcbermittelt\"},\n {\"IdBundesland\":15, \"Bundesland\":\"Sachsen-Anhalt\",\"Landkreis\":\"SK Magdeburg\",\"Altersgruppe\":\"A05-A14\",\n \"Geschlecht\": \"M\", \"AnzahlFall\":1,\"AnzahlTodesfall\":0,\"ObjectId\":1032741,\"Meldedatum\":\"2020\\/08\\/09 00:00:00+00\",\n \"IdLandkreis\":15003,\"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0,\"NeuerTodesfall\":-9,\n \"Refdatum\":\"2020\\/08\\/09 00:00:00+00\",\"NeuGenesen\":0,\"AnzahlGenesen\":1,\"IstErkrankungsbeginn\":1,\n \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":16, \"Bundesland\":\"Th\\\\u00fcringen\",\"Landkreis\":\\\n \"LK Eichsfeld\",\"Altersgruppe\":\"A35-A59\",\"Geschlecht\" :\"M\", \"AnzahlFall\":1,\"AnzahlTodesfall\":0,\"ObjectId\":1066020,\n \"Meldedatum\":\"2020\\/08\\/09 00:00:00+00\", \"IdLandkreis\" :16061,\"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0,\n \"NeuerTodesfall\":-9, \"Refdatum\": \"2020\\/08\\/09 00:00:00+00\",\"NeuGenesen\":0,\"AnzahlGenesen\":1,\n \"IstErkrankungsbeginn\":1, \"Altersgruppe2\": \"Nicht \\\\u00fcbermittelt\"}, {\"IdBundesland\":16,\n \"Bundesland\":\"Th\\\\u00fcringen\",\"Landkreis\":\"LK Eichsfeld\",\"Altersgruppe\":\"A35-A59\",\"Geschlecht\" :\"M\",\n \"AnzahlFall\":1,\"AnzahlTodesfall\":1,\"ObjectId\":1066020, \"Meldedatum\":\"2021\\/01\\/21 00:00:00+00\", \"IdLandkreis\"\n :16061,\"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0, \"NeuerTodesfall\":0, \"Refdatum\": \"2021\\/01\\/21\n 00:00:00+00\",\"NeuGenesen\":0,\"AnzahlGenesen\":1, \"IstErkrankungsbeginn\":1, \"Altersgruppe2\":\n \"Nicht \\\\u00fcbermittelt\"}]\"\"\")\n\n string_not_all_states = (\"\"\"[{\"IdBundesland\":1,\"Bundesland\":\"Schleswig-Holstein\",\"Landkreis\":\"SK Kiel\", \n \"Altersgruppe\":\"A60-A79\" ,\"Geschlecht\":\"M\",\"AnzahlFall\":1,\"AnzahlTodesfall\":0,\"ObjectId\":1, \n \"Meldedatum\":\"2020\\/08\\/11 00:00:00+00\", \"IdLandkreis\":1002,\"Datenstand\":\"25.01.2021, 00:00 Uhr\",\"NeuerFall\":0, \n \"NeuerTodesfall\":-9, \"Refdatum\":\"2020\\/08\\/07 00:00:00+00\",\"NeuGenesen\":0,\"AnzahlGenesen\":1, \n \"IstErkrankungsbeginn\":1, \"Altersgruppe2\":\"Nicht \\\\u00fcbermittelt\"}]\"\"\")\n\n def setUp(self):\n self.setUpPyfakefs()\n \n def write_rki_data(self, out_folder):\n file_rki = \"FullDataRKI.json\"\n file_rki_with_path = os.path.join(out_folder, file_rki)\n with open(file_rki_with_path, 'w') as f:\n f.write(self.test_string_all_federal_states_and_counties)\n\n def write_rki_data_not_all_states(self, out_folder):\n file_rki = \"notFullDataRKI.json\"\n file_rki_with_path = os.path.join(out_folder, file_rki)\n with open(file_rki_with_path, 'w') as f:\n f.write(self.string_not_all_states)\n\n def test_get_rki_data_read(self):\n # Test without downloading data\n read_data = True\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = False\n impute_dates = False\n make_plot = False\n moving_average = 0\n split_berlin = False\n rep_date = False\n\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n # Test case where file does not exist\n file = \"FullDataRKI.json\"\n file_with_path = os.path.join(directory, file)\n\n with self.assertRaises(FileNotFoundError) as error:\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, \n impute_dates, make_plot, moving_average,\n split_berlin,rep_date)\n\n self.assertEqual(str(error.exception), \"Error: The file: \" + file_with_path +\n \" does not exist. Call program without -r flag to get it.\")\n\n # Test case where file exists\n self.write_rki_data(directory)\n # check if expected file is written\n self.assertEqual(len(os.listdir(directory)), 1)\n\n grki.get_rki_data(read_data, file_format, out_folder, impute_dates, make_plot, moving_average, no_raw,\n split_berlin, rep_date)\n\n # check if expected files are written\n self.assertEqual(len(os.listdir(directory)), 14)\n\n # test output files\n file = \"all_germany_rki.json\"\n f_read = os.path.join(directory, file)\n df = pd.read_json(f_read)\n\n file = 'infected_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n\n file = 'deaths_rki.json'\n f_read = os.path.join(directory, file)\n df_deaths = pd.read_json(f_read)\n\n data_list = df.columns.values.tolist()\n self.assertEqual(data_list, [\"Date\", \"Confirmed\", \"Deaths\", \"Recovered\"])\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(),\n df_infected[(df_infected['Date'] == \"2020-08-07\")]['Confirmed'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(), 15)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(),\n df_deaths[(df_deaths['Date'] == \"2020-08-07\")]['Deaths'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(), 2)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")][\"Recovered\"].item(), 14)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Confirmed'].item(), 8)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Deaths'].item(), 1)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")][\"Recovered\"].item(), 8)\n\n file = 'all_age_rki.json'\n f_read = os.path.join(directory, file)\n df_age = pd.read_json(f_read)\n self.assertEqual(\n df_age[(df_age['Date'] == \"2020-08-07\") & (df_age[\"Age_RKI\"] == \"A60-A79\")][\"Recovered\"].item(), 6)\n self.assertEqual(\n df_age[(df_age['Date'] == \"2020-08-07\") & (df_age[\"Age_RKI\"] == \"A60-A79\")]['Deaths'].item(), 2)\n self.assertEqual(\n df_age[(df_age['Date'] == \"2020-08-07\") & (df_age[\"Age_RKI\"] == \"A60-A79\")]['Confirmed'].item(), 7)\n\n file = 'all_gender_rki.json'\n f_read = os.path.join(directory, file)\n df_gender = pd.read_json(f_read)\n self.assertEqual(\n df_gender[(df_gender['Date'] == \"2020-08-07\") & (df_gender[\"Gender\"] == \"male\")][\"Recovered\"].item(), 7)\n self.assertEqual(\n df_gender[(df_gender['Date'] == \"2020-08-07\") & (df_gender[\"Gender\"] == \"female\")]['Deaths'].item(), 1)\n self.assertEqual(\n df_gender[(df_gender['Date'] == \"2020-08-07\") & (df_gender[\"Gender\"] == \"male\")]['Deaths'].item(), 1)\n self.assertEqual(\n df_gender[(df_gender['Date'] == \"2020-08-07\") & (df_gender[\"Gender\"] == \"female\")]['Confirmed'].item(), 7)\n\n file = 'all_county_gender_rki.json'\n f_read = os.path.join(directory, file)\n df_gender = pd.read_json(f_read)\n self.assertEqual(df_gender.shape[0], 18+412)\n # checks if Berlins districts are concatenated\n\n self.assertEqual(\n df_gender[(df_gender['County'] == \"Berlin\") & (df_gender['Gender'] == 'male')]['Confirmed'].shape[0], 10)\n\n file = 'infected_county_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n self.assertEqual(df_infected[(df_infected['County'] == \"LK Ludwigsburg\")]['Confirmed'].shape[0], 2)\n\n file = 'all_state_age_rki.json'\n f_read = os.path.join(directory, file)\n df_state = pd.read_json(f_read)\n # for every state one line + state 16 has two dates in string\n self.assertEqual(df_state.shape[0], 362)\n self.assertEqual(df_state[(df_state[\"ID_State\"] == 1) &\n (df_state['Date'] == \"2020-08-07\")]['Confirmed'].item(), 2)\n\n file = 'infected_state_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n self.assertEqual(df_state[(df_state[\"ID_State\"] == 1) & (df_state['Date'] == \"2020-08-07\")]['Confirmed'].item(),\n df_infected[(df_infected[\"ID_State\"] == 1) &\n (df_infected['Date'] == \"2020-08-07\")]['Confirmed'].item())\n\n @patch('memilio.epidata.getRKIData.gd.loadGeojson')\n @patch('memilio.epidata.getRKIData.gd.loadCsv')\n def test_get_rki_data_dowload(self, mock_loadCsv, mock_loadGeojson):\n # Test with downloading data\n read_data = False\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = False\n impute_dates = False\n make_plot = False\n moving_average = 0\n split_berlin = False\n rep_date = False\n\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n self.write_rki_data(directory)\n self.write_rki_data_not_all_states(directory)\n # check if expected files are written\n self.assertEqual(len(os.listdir(directory)), 2)\n\n # test case where all files are incomplete\n mock_loadCsv.return_value = pd.read_json(os.path.join(directory, \"notFullDataRKI.json\"))\n mock_loadGeojson.return_value = pd.read_json(os.path.join(directory, \"notFullDataRKI.json\"))\n with self.assertRaises(FileNotFoundError) as error:\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average,\n split_berlin, rep_date)\n self.assertEqual(str(error.exception), \n \"Something went wrong, dataframe is empty for csv and geojson!\")\n\n mock_loadGeojson.assert_called_once()\n mock_loadCsv.assert_called()\n\n # test case where csv files are incorrect\n mock_loadCsv.side_effect = [pd.DataFrame(), pd.read_json(os.path.join(directory, \"notFullDataRKI.json\"))]\n mock_loadGeojson.return_value = pd.read_json(os.path.join(directory, \"FullDataRKI.json\"))\n\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average,\n split_berlin, rep_date)\n\n mock_loadGeojson.assert_called()\n mock_loadCsv.assert_called()\n\n # check if expected files are written\n # now 15 because file notFullDataRKI is written\n self.assertEqual(len(os.listdir(directory)), 15)\n\n # test output files\n file = \"all_germany_rki.json\"\n f_read = os.path.join(directory, file)\n df = pd.read_json(f_read)\n\n file = 'infected_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n\n file = 'deaths_rki.json'\n f_read = os.path.join(directory, file)\n df_deaths = pd.read_json(f_read)\n\n data_list = df.columns.values.tolist()\n self.assertEqual(data_list, [\"Date\", \"Confirmed\", \"Deaths\", \"Recovered\"])\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(),\n df_infected[(df_infected['Date'] == \"2020-08-07\")]['Confirmed'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(), 15)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(),\n df_deaths[(df_deaths['Date'] == \"2020-08-07\")]['Deaths'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(), 2)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")][\"Recovered\"].item(), 14)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Confirmed'].item(), 8)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Deaths'].item(), 1)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")][\"Recovered\"].item(), 8)\n\n # do not test all cases tested above because same input dataframe is used -> if test without downloading pass,\n # these files are correct too\n\n @patch('memilio.epidata.getRKIData.gd.loadGeojson')\n @patch('memilio.epidata.getRKIData.gd.loadCsv')\n def test_get_rki_data_dowload_split_berlin(self, mock_loadCsv, mock_loadGeojson):\n # Test case with downloading data where first csv-source is incomplete and second one is used\n # and split_berlin = True\n read_data = False\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = False\n impute_dates = False\n make_plot = False\n moving_average = 0\n split_berlin = True\n rep_date = False\n\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n # write file\n self.write_rki_data(directory)\n # check if expected file is written\n self.assertEqual(len(os.listdir(directory)), 1)\n\n # test case where first csv file is empty and second one is complete\n mock_loadCsv.side_effect = [pd.DataFrame(), pd.read_json(os.path.join(directory, \"FullDataRKI.json\"))]\n mock_loadGeojson.return_value = pd.DataFrame()\n\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average,\n split_berlin, rep_date)\n\n mock_loadGeojson.assert_not_called()\n mock_loadCsv.assert_called()\n\n # check if expected files are written\n self.assertEqual(len(os.listdir(directory)), 14)\n\n # test output files (if all_germany is the same as without splitting Berlin)\n file = \"all_germany_rki.json\"\n f_read = os.path.join(directory, file)\n df = pd.read_json(f_read)\n\n file = 'infected_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n\n file = 'deaths_rki.json'\n f_read = os.path.join(directory, file)\n df_deaths = pd.read_json(f_read)\n\n data_list = df.columns.values.tolist()\n self.assertEqual(data_list, [\"Date\", \"Confirmed\", \"Deaths\", \"Recovered\"])\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(),\n df_infected[(df_infected['Date'] == \"2020-08-07\")]['Confirmed'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(), 15)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(),\n df_deaths[(df_deaths['Date'] == \"2020-08-07\")]['Deaths'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(), 2)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")][\"Recovered\"].item(), 14)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Confirmed'].item(), 8)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Deaths'].item(), 1)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")][\"Recovered\"].item(), 8)\n\n # test files that should be different as in other cases\n file = 'all_county_split_berlin_rki.json'\n f_read = os.path.join(directory, file)\n df_county = pd.read_json(f_read)\n\n file = 'infected_county_split_berlin_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n\n self.assertEqual(df_county.shape[0], 19+412)\n\n self.assertEqual(\n df_county[df_county['County'] == \"SK Berlin Charlottenburg-Wilmersdorf\"]['Recovered'].shape[0], 2)\n self.assertEqual(df_county[df_county['County'] == \"SK Berlin Lichtenberg\"]['Recovered'].shape[0], 2)\n\n file = 'all_county_gender_split_berlin_rki.json'\n f_read = os.path.join(directory, file)\n df_gender = pd.read_json(f_read)\n\n self.assertEqual(df_gender[(df_gender['Date'] == \"2020-06-04\") & (df_gender['Gender'] == \"male\")].shape[0], 2)\n\n # check if in state file the counties of Berlin are not splitted\n file = 'all_state_rki.json'\n f_read = os.path.join(directory, file)\n df_state = pd.read_json(f_read)\n # last state has 2 different dates -> two rows\n self.assertEqual(df_state.shape[0], 304)\n\n def test_get_rki_data_read_moving_average(self):\n # Test without downloading data\n \n read_data = True\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = False\n impute_dates = False\n make_plot = False\n moving_average = 7\n split_berlin = False\n rep_date = False\n\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n # write file\n self.write_rki_data(directory)\n # check if expected file is written\n self.assertEqual(len(os.listdir(directory)), 1)\n\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average,\n split_berlin, rep_date)\n\n # check if expected files are written\n self.assertEqual(len(os.listdir(directory)), 27)\n\n # test if normal file os the same\n file = \"all_germany_rki.json\"\n f_read = os.path.join(directory, file)\n df = pd.read_json(f_read)\n\n file = 'infected_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n\n file = 'deaths_rki.json'\n f_read = os.path.join(directory, file)\n df_deaths = pd.read_json(f_read)\n\n data_list = df.columns.values.tolist()\n self.assertEqual(data_list, [\"Date\", \"Confirmed\", \"Deaths\", \"Recovered\"])\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(),\n df_infected[(df_infected['Date'] == \"2020-08-07\")]['Confirmed'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(), 15)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(),\n df_deaths[(df_deaths['Date'] == \"2020-08-07\")]['Deaths'].item())\n # one deaths on 2020-04-13 + one on 2020-08-07\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(), 2)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")][\"Recovered\"].item(), 14)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Confirmed'].item(), 8)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Deaths'].item(), 1)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")][\"Recovered\"].item(), 8)\n\n self.assertEqual(df[(df['Date'] == \"2020-08-10\")]['Deaths'].item(), 5)\n\n # test _ma files\n file = 'all_germany_ma7_rki.json'\n f_read = os.path.join(directory, file)\n df_ma = pd.read_json(f_read)\n\n data_list = df_ma.columns.values.tolist()\n self.assertEqual(data_list, [\"Date\", \"Confirmed\", \"Deaths\", \"Recovered\"])\n # test if 7 day average moving is calculated correctly\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-08-07\")]['Confirmed'].item(), 15 + 6 / 7)\n self.assertEqual(df_ma[(df_ma['Date'] == \"2020-08-07\")]['Deaths'].item(), 2)\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-08-07\")][\"Recovered\"].item(), 14 + 3 / 7)\n\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-08-08\")]['Confirmed'].item(), 18 + 6 /7)\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-08-08\")]['Deaths'].item(), 2 + 4/7)\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-08-08\")][\"Recovered\"].item(), 16 + 5/7)\n\n self.assertEqual(df_ma[(df_ma['Date'] == \"2020-08-11\")]['Confirmed'].item(), 27)\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-08-11\")]['Deaths'].item(), 4 + 1/7)\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-08-11\")][\"Recovered\"].item(),\n 22 + 6/7)\n\n self.assertEqual(df_ma[(df_ma['Date'] == \"2020-08-20\")]['Confirmed'].item(), 30)\n self.assertEqual(df_ma[(df_ma['Date'] == \"2020-08-20\")]['Deaths'].item(), 5)\n self.assertEqual(df_ma[(df_ma['Date'] == \"2020-08-20\")][\"Recovered\"].item(), 25)\n\n file = 'infected_ma7_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n \n file = 'deaths_ma7_rki.json'\n f_read = os.path.join(directory, file)\n df_deaths = pd.read_json(f_read)\n\n self.assertEqual(df_ma[(df_ma['Date'] == \"2020-08-11\")]['Confirmed'].item(),\n df_infected[(df_infected['Date'] == \"2020-08-11\")]['Confirmed'].item())\n self.assertEqual(df_ma[(df_ma['Date'] == \"2020-08-11\")]['Deaths'].item(),\n df_deaths[(df_deaths['Date'] == \"2020-08-11\")]['Deaths'].item())\n # Attention: deaths_rki_ma file and all_germany_rki_ma deaths-column are not identical in the first six days\n # after first death. This is the case because in all_germany file, zeros before the first death are included\n # in the calculation of the moving average and in deaths_rki-file first data are just cumulative deaths.\n self.assertEqual(df_deaths[df_deaths['Date'] == \"2020-04-13\"]['Deaths'].item(), 1.0)\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-04-13\")]['Deaths'].item(), 4/7)\n self.assertNotEqual(df_deaths[df_deaths['Date'] == \"2020-04-13\"]['Deaths'].items(),\n df_ma[(df_ma['Date'] == \"2020-04-13\")]['Deaths'].items())\n self.assertEqual(df_deaths[df_deaths['Date'] == \"2020-04-14\"]['Deaths'].item(), 1.0)\n self.assertAlmostEqual(df_ma[(df_ma['Date'] == \"2020-04-14\")]['Deaths'].item(), 5/7)\n\n file = 'all_state_ma7_rki.json'\n f_read = os.path.join(directory, file)\n df_state = pd.read_json(f_read)\n self.assertAlmostEqual(\n df_state[(df_state['Date'] == \"2020-08-07\") & (df_state['ID_State'] == 1)]['Confirmed'].item(),\n 1+ 1/7 )\n self.assertAlmostEqual(\n df_state[(df_state['Date'] == \"2020-08-08\") & (df_state['ID_State'] == 1)]['Confirmed'].item(),\n 1+3/7)\n self.assertEqual(\n df_state[(df_state['Date'] == \"2020-08-11\") & (df_state['ID_State'] == 1)]['Confirmed'].item(),\n 2.0)\n self.assertEqual(\n df_state[(df_state['Date'] == \"2020-08-20\") & (df_state['ID_State'] == 1)]['Confirmed'].item(),\n 2.0)\n self.assertEqual(\n df_state[(df_state['Date'] == \"2020-08-11\") & (df_state['ID_State'] == 1)]['Deaths'].item(),\n 1.0)\n\n def test_get_rki_data_read_impute_dates(self):\n # Test without downloading data\n read_data = True\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = False\n impute_dates = True\n make_plot = False\n moving_average = 0\n split_berlin = False\n rep_date = False\n\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n # write file\n self.write_rki_data(directory)\n # check if expected file is written\n self.assertEqual(len(os.listdir(directory)), 1)\n\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average,\n split_berlin, rep_date)\n\n # check if expected files are written\n self.assertEqual(len(os.listdir(directory)), 27)\n\n files = ['infected_all_dates_rki.json', 'deaths_all_dates_rki.json', 'all_state_all_dates_rki.json',\n \"infected_state_all_dates_rki.json\", \"all_state_all_dates_rki.json\",\n \"infected_county_all_dates_rki.json\", \"all_county_all_dates_rki.json\",\n \"all_gender_all_dates_rki.json\", \"all_state_gender_all_dates_rki.json\",\n \"all_county_gender_all_dates_rki.json\", \"all_age_all_dates_rki.json\",\n \"all_state_age_all_dates_rki.json\", \"all_county_age_all_dates_rki.json\"]\n for file in files:\n self.assertTrue(file in os.listdir(directory))\n\n\n # test if normal file os the same\n file = \"all_germany_rki.json\"\n f_read = os.path.join(directory, file)\n df = pd.read_json(f_read)\n\n file = 'infected_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n\n file = 'deaths_rki.json'\n f_read = os.path.join(directory, file)\n df_deaths = pd.read_json(f_read)\n\n data_list = df.columns.values.tolist()\n self.assertEqual(data_list, [\"Date\", \"Confirmed\", \"Deaths\", \"Recovered\"])\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(),\n df_infected[(df_infected['Date'] == \"2020-08-07\")]['Confirmed'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(), 15)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(),\n df_deaths[(df_deaths['Date'] == \"2020-08-07\")]['Deaths'].item())\n # one deaths on 2020-04-13 + one on 2020-08-07\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(), 2)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")][\"Recovered\"].item(), 14)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Confirmed'].item(), 8)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Deaths'].item(), 1)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")][\"Recovered\"].item(), 8)\n\n self.assertEqual(df[(df['Date'] == \"2020-08-10\")]['Deaths'].item(), 5)\n\n # test _all_dates files\n file = 'all_germany_all_dates_rki.json'\n self.assertTrue(file in os.listdir(directory))\n f_read = os.path.join(directory, file)\n df_ad = pd.read_json(f_read)\n\n data_list = df_ad.columns.values.tolist()\n self.assertEqual(data_list, [\"Date\", \"Confirmed\", \"Deaths\", \"Recovered\"])\n # test if 7 day average moving is calculated correctly\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-06-10\")]['Confirmed'].item(), 8)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-06-10\")]['Deaths'].item(), 1)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-06-10\")][\"Recovered\"].item(), 8)\n # Check an average date in between\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-07-08\")]['Confirmed'].item(), 9)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-07-20\")]['Deaths'].item(), 1)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-07-31\")][\"Recovered\"].item(), 9)\n\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-07\")]['Confirmed'].item(), 15)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-07\")]['Deaths'].item(), 2)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-07\")][\"Recovered\"].item(), 14)\n\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-08\")]['Confirmed'].item(), 16)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-08\")]['Deaths'].item(), 2)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-08\")][\"Recovered\"].item(), 14)\n\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-20\")]['Confirmed'].item(), 30)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-20\")]['Deaths'].item(), 5)\n self.assertEqual(df_ad[(df_ad['Date'] == \"2020-08-20\")][\"Recovered\"].item(), 25)\n\n\n def test_get_rki_data_read_moving_average_and_split_berlin(self):\n # test if split_berlin and moving_average = True are working together\n \n read_data = True\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = False\n impute_dates = False\n make_plot = False\n moving_average = 7\n split_berlin = True\n rep_date = False\n\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n # write file\n self.write_rki_data(directory)\n # check if expected file is written\n self.assertEqual(len(os.listdir(directory)), 1)\n\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average,\n split_berlin, rep_date)\n\n # check if expected files are written (27 same number as with split_berlin=False)\n self.assertEqual(len(os.listdir(directory)), 27)\n # many files are tested before, don't test them again\n file = 'all_county_split_berlin_rki.json'\n f_read = os.path.join(directory, file)\n df_county = pd.read_json(f_read)\n self.assertEqual(df_county[(df_county['County'] == \"SK Berlin Charlottenburg-Wilmersdorf\") & (\n df_county['Date'] == '2020-06-04')]['Confirmed'].item(),\n 1)\n self.assertEqual(\n df_county[(df_county['County'] == \"SK Berlin Lichtenberg\") & (df_county['Date'] == '2020-06-04')][\n 'Confirmed'].item(), 1)\n\n file = 'all_county_split_berlin_ma7_rki.json'\n f_read = os.path.join(directory, file)\n df_county = pd.read_json(f_read)\n self.assertAlmostEqual(df_county[(df_county['County'] == \"SK Berlin Charlottenburg-Wilmersdorf\") & (\n df_county['Date'] == '2020-06-04')]['Confirmed'].item(),\n 4/7 )\n self.assertAlmostEqual(\n df_county[(df_county['County'] == \"SK Berlin Lichtenberg\") & (df_county['Date'] == '2020-06-04')][\n 'Confirmed'].item(), 4/7 )\n self.assertAlmostEqual(df_county[(df_county['County'] == \"SK Berlin Charlottenburg-Wilmersdorf\") & (\n df_county['Date'] == '2020-06-09')]['Recovered'].item(),\n 1)\n self.assertEqual(\n df_county[(df_county['County'] == \"SK Berlin Lichtenberg\") & (df_county['Date'] == '2020-06-09')][\n 'Recovered'].item(), 1)\n self.assertAlmostEqual(\n df_county[(df_county['County'] == \"SK Berlin Lichtenberg\") & (df_county['Date'] == '2020-06-09')][\n 'Deaths'].item(), 0)\n\n def test_get_rki_data_read_all_dates_and_split_berlin(self):\n # test if split_berlin and moving_average = True are working together\n read_data = True\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = False\n impute_dates = True\n make_plot = False\n moving_average = 0\n split_berlin = True\n rep_date = False\n\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n # write file\n self.write_rki_data(directory)\n # check if expected file is written\n self.assertEqual(len(os.listdir(directory)), 1)\n\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average,\n split_berlin, rep_date)\n\n # check if expected files are written (27 same number as with split_berlin=False)\n self.assertEqual(len(os.listdir(directory)), 27)\n # many files are tested before, don't test them again\n files = ['all_county_split_berlin_rki.json', 'all_county_split_berlin_all_dates_rki.json',\n \"infected_county_split_berlin_rki.json\", \"infected_county_split_berlin_all_dates_rki.json\",\n \"all_county_gender_split_berlin_rki.json\", \"all_county_gender_split_berlin_all_dates_rki.json\",\n \"all_county_age_split_berlin_rki.json\", \"all_county_age_split_berlin_all_dates_rki.json\"]\n for file in files:\n self.assertTrue(file in os.listdir(directory))\n\n @patch('memilio.epidata.getRKIData.gd.loadCsv')\n def test_no_raw(self, mock_loadCsv):\n # Test with downloading data\n read_data = False\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = True\n impute_dates = False\n make_plot = False\n moving_average = 0\n split_berlin = False\n rep_date = False\n\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n # check if expected files are written\n mock_loadCsv.return_value = pd.read_json(self.test_string_all_federal_states_and_counties)\n\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average,\n split_berlin, rep_date)\n\n mock_loadCsv.assert_called()\n\n # check if expected files are written\n # 13 is one less because FullDataRKI is not written\n self.assertEqual(len(os.listdir(directory)), 13)\n\n self.assertTrue(\"FullDataRKI.json\" not in os.listdir(directory))\n\n # test output files\n file = \"all_germany_rki.json\"\n f_read = os.path.join(directory, file)\n df = pd.read_json(f_read)\n\n file = 'infected_rki.json'\n f_read = os.path.join(directory, file)\n df_infected = pd.read_json(f_read)\n\n file = 'deaths_rki.json'\n f_read = os.path.join(directory, file)\n df_deaths = pd.read_json(f_read)\n\n data_list = df.columns.values.tolist()\n self.assertEqual(data_list, [\"Date\", \"Confirmed\", \"Deaths\", \"Recovered\"])\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(),\n df_infected[(df_infected['Date'] == \"2020-08-07\")]['Confirmed'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Confirmed'].item(), 15)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(),\n df_deaths[(df_deaths['Date'] == \"2020-08-07\")]['Deaths'].item())\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")]['Deaths'].item(), 2)\n self.assertEqual(df[(df['Date'] == \"2020-08-07\")][\"Recovered\"].item(), 14)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Confirmed'].item(), 8)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")]['Deaths'].item(), 1)\n self.assertEqual(df[(df['Date'] == \"2020-06-10\")][\"Recovered\"].item(), 8)\n\n @patch('memilio.epidata.getRKIData.gd.cli')\n def test_main(self, mock_cli):\n\n\n mock_cli.return_value = {\"read_data\": True, \"file_format\": 'json_timeasstring', \"out_folder\": self.path,\n \"impute_dates\": False, \"make_plot\": False, \"moving_average\": 0,\n \"split_berlin\": False, \"no_raw\": False, \"rep_date\": False}\n\n out_folder = self.path\n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n # Test case where file does not exist\n file = \"FullDataRKI.json\"\n file_with_path = os.path.join(directory, file)\n # Test case where file exists\n self.write_rki_data(directory)\n # check if expected file is written\n self.assertEqual(len(os.listdir(directory)), 1)\n\n grki.main()\n # check if expected files are written\n self.assertEqual(len(os.listdir(directory)), 14)\n\n\n def test_check_for_completeness(self):\n empty_df = pd.DataFrame()\n self.assertEqual(grki.check_for_completeness(empty_df), False)\n \n @patch('memilio.epidata.getRKIData.gd.loadCsv')\n def test_rep_date(self, mocklcsv):\n\n mocklcsv.return_value = pd.read_json(self.test_string_all_federal_states_and_counties)\n\n read_data = False\n file_format = 'json_timeasstring'\n out_folder = self.path\n no_raw = False\n impute_dates = False\n make_plot = False\n moving_average = 7\n split_berlin = False\n rep_date = True\n \n directory = os.path.join(out_folder, 'Germany/')\n gd.check_dir(directory)\n\n grki.get_rki_data(read_data, file_format, out_folder, no_raw, impute_dates, make_plot, moving_average, split_berlin, rep_date)\n\n mocklcsv.assert_called()\n self.assertEqual(len(os.listdir(directory)), 27)\n\nif __name__ == '__main__':\n unittest.main()\n"
]
| [
[
"pandas.read_json",
"pandas.DataFrame"
]
]
|
tmunemot/eeg_seizure_forecasting | [
"15db53279ac0e3320c9ba731ce9a7aa49f97ec22"
]
| [
"utils.py"
]
| [
"#!/usr/bin/python\nimport sys, os, argparse\nimport numpy as np\nimport pandas as pd\nimport random\nimport errno\nfrom scipy import sparse\nimport time\nimport scipy.io\nimport features\n\ndef mkdir_p(path):\n \"\"\"\n a function equivalent to \"mkdir -p\" in bash scripting\n https://stackoverflow.com/questions/600268/mkdir-p-functionality-in-python\n \n Args:\n path: path to a new directry\n \n Returns:\n None\n \"\"\"\n try:\n os.makedirs(path)\n except OSError as exc: # Python >2.5\n if exc.errno == errno.EEXIST and os.path.isdir(path):\n pass\n else:\n raise\n\n\n_start_time = time.time()\n\n\ndef tic():\n \"\"\" start a timer\n Args:\n None\n \n Return:\n None\n \"\"\"\n global _start_time\n _start_time = time.time()\n\n\ndef toc():\n \"\"\" report an elapsed time since tic() is called\n Args:\n None\n \n Return:\n a string contains a reprot\n \"\"\"\n t_sec = round(time.time() - _start_time)\n (t_min, t_sec) = divmod(t_sec,60)\n (t_hour,t_min) = divmod(t_min,60)\n return \"time elapsed: {} hr, {} min, {} sec\".format(int(t_hour),int(t_min),int(t_sec))\n\n\ndef list_matfiles(path):\n \"\"\" list all files ends with .mat\n \n Args:\n path: path to a root directory\n \n Returns:\n list of file names\n \"\"\"\n return [os.path.join(path, f) for f in os.listdir(path) if os.path.isfile(os.path.join(path, f)) and f.endswith(\".mat\")]\n\n\ndef parse_matfile(path):\n \"\"\" read a .mat file and parse its contents\n \n Args:\n path: path to a file\n \n Returns:\n EEG signal, user name, class label, and file name\n \"\"\"\n data = scipy.io.loadmat(path)[\"dataStruct\"]\n eeg = data[0][0][0]\n name = os.path.basename(path)\n substr = name.replace(\"new_\", \"\").replace(\"old_\", \"\").split('.')[0].split('_')\n user = int(substr[0])\n classlabel = np.nan if len(substr) == 2 else int(substr[2])\n return eeg, user, classlabel, name\n\n\ndef generate_data(drop_signal_rate=0.0):\n \"\"\" generate an array with random numbers to emulate an EEG signal\n \n Args:\n None\n \n Returns:\n EEG signal, user name, class label, and file name\n \"\"\"\n eeg = np.random.randint(low=-100, high=100, size=(features.SIGNAL_LENGTH, 16))\n \n if drop_signal_rate > 0.0:\n # intentionally set zeros to a part of EEG signal\n len = int(features.SIGNAL_LENGTH * drop_signal_rate)\n start_index = np.random.randint(0, features.SIGNAL_LENGTH - len)\n eeg[start_index:start_index+len] = 0\n name = \"testdata\"\n substr = \"substr\"\n user = \"testuser\"\n classlabel = 1\n return eeg, user, classlabel, name\n\n"
]
| [
[
"numpy.random.randint"
]
]
|
AathmanT/cv-tricks.com | [
"7367c42d3e2d398b31ebf1b058bdbb5dc2a56253"
]
| [
"Tensorflow-tutorials/Not-Safe-For-Work-Detection/model.py"
]
| [
"import math\nimport numpy as np\nimport tensorflow as tf\nfrom enum import Enum, unique\n\n\n@unique\nclass InputType(Enum):\n TENSOR = 1\n BASE64_JPEG = 2\n\n\nclass OpenNsfwModel:\n \"\"\"Tensorflow implementation of Yahoo's Open NSFW Model\n\n Original implementation:\n https://github.com/yahoo/open_nsfw\n\n Weights have been converted using caffe-tensorflow:\n https://github.com/ethereon/caffe-tensorflow\n \"\"\"\n\n def __init__(self):\n self.weights = {}\n self.bn_epsilon = 1e-5 # Default used by Caffe\n\n def build(self, weights_path=\"open_nsfw-weights.npy\",\n input_type=InputType.TENSOR):\n\n self.weights = np.load(weights_path, encoding=\"latin1\").item()\n self.input_tensor = None\n\n if input_type == InputType.TENSOR:\n self.input = tf.placeholder(tf.float32,\n shape=[None, 224, 224, 3],\n name=\"input\")\n self.input_tensor = self.input\n elif input_type == InputType.BASE64_JPEG:\n from image_utils import load_base64_tensor\n\n self.input = tf.placeholder(tf.string, shape=(None,), name=\"input\")\n self.input_tensor = load_base64_tensor(self.input)\n else:\n raise ValueError(\"invalid input type '{}'\".format(input_type))\n\n x = self.input_tensor\n\n x = tf.pad(x, [[0, 0], [3, 3], [3, 3], [0, 0]], 'CONSTANT')\n\n x = self.__conv2d(\"conv_1\", x, filter_depth=64,\n kernel_size=7, stride=2, padding='valid')\n\n x = self.__batch_norm(\"bn_1\", x)\n x = tf.nn.relu(x)\n\n x = tf.keras.layers.MaxPool2D(pool_size = 3, strides = 2, padding = 'same')(x)\n\n x = self.__conv_block(stage=0, block=0, inputs=x,\n filter_depths=[32, 32, 128],\n kernel_size=3, stride=1)\n\n x = self.__identity_block(stage=0, block=1, inputs=x,\n filter_depths=[32, 32, 128], kernel_size=3)\n x = self.__identity_block(stage=0, block=2, inputs=x,\n filter_depths=[32, 32, 128], kernel_size=3)\n\n x = self.__conv_block(stage=1, block=0, inputs=x,\n filter_depths=[64, 64, 256],\n kernel_size=3, stride=2)\n x = self.__identity_block(stage=1, block=1, inputs=x,\n filter_depths=[64, 64, 256], kernel_size=3)\n x = self.__identity_block(stage=1, block=2, inputs=x,\n filter_depths=[64, 64, 256], kernel_size=3)\n x = self.__identity_block(stage=1, block=3, inputs=x,\n filter_depths=[64, 64, 256], kernel_size=3)\n\n x = self.__conv_block(stage=2, block=0, inputs=x,\n filter_depths=[128, 128, 512],\n kernel_size=3, stride=2)\n x = self.__identity_block(stage=2, block=1, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n x = self.__identity_block(stage=2, block=2, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n x = self.__identity_block(stage=2, block=3, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n x = self.__identity_block(stage=2, block=4, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n x = self.__identity_block(stage=2, block=5, inputs=x,\n filter_depths=[128, 128, 512], kernel_size=3)\n\n x = self.__conv_block(stage=3, block=0, inputs=x,\n filter_depths=[256, 256, 1024], kernel_size=3,\n stride=2)\n x = self.__identity_block(stage=3, block=1, inputs=x,\n filter_depths=[256, 256, 1024],\n kernel_size=3)\n x = self.__identity_block(stage=3, block=2, inputs=x,\n filter_depths=[256, 256, 1024],\n kernel_size=3)\n\n x = tf.keras.layers.AveragePooling2D(pool_size=7, strides=1,\n padding=\"valid\", name=\"pool\")(x)\n\n x = tf.reshape(x, shape=(-1, 1024))\n\n self.logits = self.__fully_connected(name=\"fc_nsfw\",\n inputs=x, num_outputs=2)\n self.predictions = tf.nn.softmax(self.logits, name=\"predictions\")\n\n \"\"\"Get weights for layer with given name\n \"\"\"\n def __get_weights(self, layer_name, field_name):\n if not layer_name in self.weights:\n raise ValueError(\"No weights for layer named '{}' found\"\n .format(layer_name))\n\n w = self.weights[layer_name]\n if not field_name in w:\n raise (ValueError(\"No entry for field '{}' in layer named '{}'\"\n .format(field_name, layer_name)))\n\n return w[field_name]\n\n \"\"\"Layer creation and weight initialization\n \"\"\"\n def __fully_connected(self, name, inputs, num_outputs):\n return tf.keras.layers.Dense(\n units=num_outputs, name=name,\n kernel_initializer=tf.constant_initializer(\n self.__get_weights(name, \"weights\"), dtype=tf.float32),\n bias_initializer=tf.constant_initializer(\n self.__get_weights(name, \"biases\"), dtype=tf.float32))(inputs)\n\n def __conv2d(self, name, inputs, filter_depth, kernel_size, stride=1, padding=\"same\", trainable=False):\n if padding.lower() == 'same' and kernel_size > 1:\n #print(\"INPUT SHAPE: \", inputs.get_shape().as_list())\n #print(\"KERNEL SIZE: \", kernel_size)\n if kernel_size > 1:\n oh = inputs.get_shape().as_list()[1]\n h = inputs.get_shape().as_list()[1]\n\n p = int(math.floor(((oh - 1) * stride + kernel_size - h)//2))\n\n inputs = tf.pad(inputs,\n [[0, 0], [p, p], [p, p], [0, 0]],\n 'CONSTANT')\n #print(\"PADDED INPUT SIZE: \", inputs.get_shape().as_list())\n else:\n raise Exception('unsupported kernel size for padding: \"{}\"'\n .format(kernel_size))\n\n return tf.keras.layers.Conv2D(\n filters = filter_depth,\n kernel_size=(kernel_size, kernel_size),\n strides=(stride, stride), padding='valid',\n activation=None, trainable=trainable, name=name,\n kernel_initializer=tf.constant_initializer(\n self.__get_weights(name, \"weights\"), dtype=tf.float32),\n bias_initializer=tf.constant_initializer(\n self.__get_weights(name, \"biases\"), dtype=tf.float32))(inputs) \n\n def __batch_norm(self, name, inputs, training=False):\n return tf.keras.layers.BatchNormalization(\n trainable=training, epsilon=self.bn_epsilon,\n gamma_initializer=tf.constant_initializer(\n self.__get_weights(name, \"scale\"), dtype=tf.float32),\n beta_initializer=tf.constant_initializer(\n self.__get_weights(name, \"offset\"), dtype=tf.float32),\n moving_mean_initializer=tf.constant_initializer(\n self.__get_weights(name, \"mean\"), dtype=tf.float32),\n moving_variance_initializer=tf.constant_initializer(\n self.__get_weights(name, \"variance\"), dtype=tf.float32),\n name=name)(inputs)\n\n \"\"\"ResNet blocks\n \"\"\"\n def __conv_block(self, stage, block, inputs, filter_depths,\n kernel_size=3, stride=2):\n filter_depth1, filter_depth2, filter_depth3 = filter_depths\n\n conv_name_base = \"conv_stage{}_block{}_branch\".format(stage, block)\n bn_name_base = \"bn_stage{}_block{}_branch\".format(stage, block)\n shortcut_name_post = \"_stage{}_block{}_proj_shortcut\" \\\n .format(stage, block)\n\n shortcut = self.__conv2d(\n name=\"conv{}\".format(shortcut_name_post), stride=stride,\n inputs=inputs, filter_depth=filter_depth3, kernel_size=1,\n padding=\"same\"\n )\n\n shortcut = self.__batch_norm(\"bn{}\".format(shortcut_name_post),\n shortcut)\n\n x = self.__conv2d(\n name=\"{}2a\".format(conv_name_base),\n inputs=inputs, filter_depth=filter_depth1, kernel_size=1,\n stride=stride, padding=\"same\",\n )\n x = self.__batch_norm(\"{}2a\".format(bn_name_base), x)\n x = tf.nn.relu(x)\n\n x = self.__conv2d(\n name=\"{}2b\".format(conv_name_base),\n inputs=x, filter_depth=filter_depth2, kernel_size=kernel_size,\n padding=\"same\", stride=1\n )\n x = self.__batch_norm(\"{}2b\".format(bn_name_base), x)\n x = tf.nn.relu(x)\n\n x = self.__conv2d(\n name=\"{}2c\".format(conv_name_base),\n inputs=x, filter_depth=filter_depth3, kernel_size=1,\n padding=\"same\", stride=1\n )\n x = self.__batch_norm(\"{}2c\".format(bn_name_base), x)\n\n x = tf.add(x, shortcut)\n\n return tf.nn.relu(x)\n\n def __identity_block(self, stage, block, inputs,\n filter_depths, kernel_size):\n filter_depth1, filter_depth2, filter_depth3 = filter_depths\n conv_name_base = \"conv_stage{}_block{}_branch\".format(stage, block)\n bn_name_base = \"bn_stage{}_block{}_branch\".format(stage, block)\n\n x = self.__conv2d(\n name=\"{}2a\".format(conv_name_base),\n inputs=inputs, filter_depth=filter_depth1, kernel_size=1,\n stride=1, padding=\"same\",\n )\n\n x = self.__batch_norm(\"{}2a\".format(bn_name_base), x)\n x = tf.nn.relu(x)\n\n x = self.__conv2d(\n name=\"{}2b\".format(conv_name_base),\n inputs=x, filter_depth=filter_depth2, kernel_size=kernel_size,\n padding=\"same\", stride=1\n )\n x = self.__batch_norm(\"{}2b\".format(bn_name_base), x)\n x = tf.nn.relu(x)\n\n x = self.__conv2d(\n name=\"{}2c\".format(conv_name_base),\n inputs=x, filter_depth=filter_depth3, kernel_size=1,\n padding=\"same\", stride=1\n )\n x = self.__batch_norm(\"{}2c\".format(bn_name_base), x)\n\n x = tf.add(x, inputs)\n\n return tf.nn.relu(x)\n"
]
| [
[
"tensorflow.nn.relu",
"tensorflow.keras.layers.AveragePooling2D",
"tensorflow.nn.softmax",
"tensorflow.reshape",
"tensorflow.placeholder",
"tensorflow.keras.layers.MaxPool2D",
"tensorflow.add",
"tensorflow.pad",
"numpy.load"
]
]
|
Kdc23/video-caption-pytorch | [
"8d1aceb6455ffa6873c8081ef45430fce8eadfd9"
]
| [
"models/EncoderRNN.py"
]
| [
"import torch.nn as nn\r\n\r\n\r\nclass EncoderRNN(nn.Module):\r\n def __init__(self, dim_vid, dim_hidden, input_dropout_p=0, dropout_p=0,\r\n n_layers=1, bidirectional=False, rnn_cell='gru'):\r\n \"\"\"\r\n\r\n Args:\r\n hidden_dim (int): dim of hidden state of rnn\r\n input_dropout_p (int): dropout probability for the input sequence\r\n dropout_p (float): dropout probability for the output sequence\r\n n_layers (int): number of rnn layers\r\n rnn_cell (str): type of RNN cell ('LSTM'/'GRU')\r\n \"\"\"\r\n super().__init__()\r\n self.dim_vid = dim_vid\r\n self.dim_hidden = dim_hidden\r\n self.input_dropout_p = input_dropout_p\r\n self.dropout_p = dropout_p\r\n self.n_layers = n_layers\r\n self.bidirectional = bidirectional\r\n self.rnn_cell = rnn_cell\r\n\r\n self.vid2hid = nn.Linear(dim_vid, dim_hidden)\r\n self.input_dropout = nn.Dropout(input_dropout_p)\r\n\r\n if rnn_cell.lower() == 'lstm':\r\n self.rnn_cell = nn.LSTM\r\n elif rnn_cell.lower() == 'gru':\r\n self.rnn_cell = nn.GRU\r\n\r\n self.rnn = self.rnn_cell(dim_hidden, dim_hidden, n_layers,\r\n batch_first=True, bidirectional=bidirectional, dropout=dropout_p)\r\n\r\n def forward(self, vid_feats):\r\n \"\"\"\r\n Applies a multi-layer RNN to an input sequence.\r\n Args:\r\n input_var (batch, seq_len): tensor containing the features of the input sequence.\r\n input_lengths (list of int, optional): A list that contains the lengths of sequences\r\n in the mini-batch\r\n Returns: output, hidden\r\n - **output** (batch, seq_len, hidden_size): variable containing the encoded features of the input sequence\r\n - **hidden** (num_layers * num_directions, batch, hidden_size): variable containing the features in the hidden state h\r\n \"\"\"\r\n batch_size, seq_len, dim_vid = vid_feats.size()\r\n vid_feats = self.vid2hid(vid_feats.view(-1, dim_vid))\r\n vid_feats = self.input_dropout(vid_feats)\r\n vid_feats = vid_feats.view(batch_size, seq_len, self.dim_hidden)\r\n self.rnn.flatten_parameters()\r\n output, hidden = self.rnn(vid_feats)\r\n return output, hidden\r\n"
]
| [
[
"torch.nn.Linear",
"torch.nn.Dropout"
]
]
|
Anthonyive/DSCI-550-Assignment-3 | [
"dbc12837143406af57d2bd0128067ac0c1485b53"
]
| [
"src/vis4ForTask5.py"
]
| [
"import pandas as pd\nimport json\n\n\ndef vis4ForTask5(csvPath: str) -> None:\n \"\"\"\n csv to jsonl function for Task 5\n\n Parameters:\n csvPath (str): input csv path from the root dir\n\n Returns:\n None: output vis4data.jsonl in data/visualizations\n \"\"\"\n df = pd.read_csv(csvPath)\n with open(\"data/visualizations/vis4data.jsonl\", 'w') as outFile:\n for index, row in df.iterrows():\n json.dump({\"index\": {'_index':'vis4CalendarView', '_id': index}}, outFile)\n outFile.write('\\n')\n json.dump(row.to_dict(), outFile)\n outFile.write('\\n')\n\nif __name__ == \"__main__\":\n vis4ForTask5('data/visualizations/vis4data.csv')"
]
| [
[
"pandas.read_csv"
]
]
|
BELIEVEfxy/LightSANs | [
"94ce7e59d144dbc787153b8c486cad334790ec6e"
]
| [
"recbole/model/sequential_recommender/.ipynb_checkpoints/lightsasrec0-checkpoint.py"
]
| [
"# -*- coding: utf-8 -*-\n# @Time : 2020/11/26\n# @Author : Xinyan Fan\n# @Email : [email protected]\n\n\nimport torch\nfrom torch import nn\n\nfrom recbole.model.abstract_recommender import SequentialRecommender\nfrom recbole.model.loss import BPRLoss\nfrom recbole.model.layers import TransformerEncoder\n\n\nclass LightSASRec(SequentialRecommender):\n r\"\"\"\n SASRec is the first sequential recommender based on self-attentive mechanism.\n\n NOTE:\n In the author's implementation, the Point-Wise Feed-Forward Network (PFFN) is implemented\n by CNN with 1x1 kernel. In this implementation, we follows the original BERT implmentation\n using Fully Connected Layer to implement the PFFN.\n \"\"\"\n\n def __init__(self, config, dataset):\n super(LightSASRec, self).__init__(config, dataset)\n\n # load parameters info\n self.n_layers = config['n_layers']\n self.n_heads = config['n_heads']\n self.k_heads = config['k_heads']\n self.hidden_size = config['hidden_size'] # same as embedding_size\n self.inner_size = config['inner_size'] # the dimensionality in feed-forward layer\n self.hidden_dropout_prob = config['hidden_dropout_prob']\n self.attn_dropout_prob = config['attn_dropout_prob']\n self.hidden_act = config['hidden_act']\n self.layer_norm_eps = config['layer_norm_eps']\n\n self.initializer_range = config['initializer_range']\n self.loss_type = config['loss_type']\n\n self.seq_len = self.max_seq_length\n # define layers and loss\n self.item_embedding = nn.Embedding(self.n_items, self.hidden_size , padding_idx=0)\n self.position_embedding = nn.Embedding(self.max_seq_length, self.hidden_size)\n self.trm_encoder = TransformerEncoder(n_layers=self.n_layers, n_heads=self.n_heads, \n k_heads=self.k_heads, hidden_size=self.hidden_size, \n seq_len=self.seq_len,\n inner_size=self.inner_size,\n hidden_dropout_prob=self.hidden_dropout_prob,\n attn_dropout_prob=self.attn_dropout_prob,\n hidden_act=self.hidden_act, layer_norm_eps=self.layer_norm_eps)\n\n self.LayerNorm = nn.LayerNorm(self.hidden_size, eps=self.layer_norm_eps)\n self.dropout = nn.Dropout(self.hidden_dropout_prob)\n\n if self.loss_type == 'BPR':\n self.loss_fct = BPRLoss()\n elif self.loss_type == 'CE':\n self.loss_fct = nn.CrossEntropyLoss()\n else:\n raise NotImplementedError(\"Make sure 'loss_type' in ['BPR', 'CE']!\")\n\n # parameters initialization\n self.apply(self._init_weights)\n\n def _init_weights(self, module):\n \"\"\" Initialize the weights \"\"\"\n if isinstance(module, (nn.Linear, nn.Embedding)):\n module.weight.data.normal_(mean=0.0, std=self.initializer_range)\n elif isinstance(module, nn.LayerNorm):\n module.bias.data.zero_()\n module.weight.data.fill_(1.0)\n if isinstance(module, nn.Linear) and module.bias is not None:\n module.bias.data.zero_()\n\n def get_attention_mask(self, item_seq):\n \"\"\"Generate left-to-right uni-directional attention mask for multi-head attention.\"\"\"\n attention_mask = (item_seq > 0).long()\n extended_attention_mask = attention_mask.unsqueeze(1).unsqueeze(2) # torch.int64\n # mask for left-to-right unidirectional\n max_len = attention_mask.size(-1)\n attn_shape = (1, max_len, max_len)\n subsequent_mask = torch.triu(torch.ones(attn_shape), diagonal=1) # torch.uint8\n subsequent_mask = (subsequent_mask == 0).unsqueeze(1)\n subsequent_mask = subsequent_mask.long().to(item_seq.device)\n\n extended_attention_mask = extended_attention_mask * subsequent_mask\n extended_attention_mask = extended_attention_mask.to(dtype=next(self.parameters()).dtype) # fp16 compatibility\n extended_attention_mask = (1.0 - extended_attention_mask) * -10000.0\n return extended_attention_mask\n\n def embedding_layer(self, item_seq):\n position_ids = torch.arange(item_seq.size(1), dtype=torch.long, device=item_seq.device)\n position_ids = position_ids.unsqueeze(0).expand_as(item_seq)\n position_embedding = self.position_embedding(position_ids)\n\n item_emb = self.item_embedding(item_seq)\n #input_emb = item_emb + position_embedding\n return item_emb, position_embedding\n\n def forward(self, item_seq, item_seq_len):\n item_emb, position_embedding = self.embedding_layer(item_seq)\n item_emb = self.LayerNorm(item_emb)\n item_emb = self.dropout(item_emb)\n\n #extended_attention_mask = self.get_attention_mask(item_seq)\n\n trm_output = self.trm_encoder(item_emb,\n position_embedding,\n output_all_encoded_layers=True)\n output = trm_output[-1]\n output = self.gather_indexes(output, item_seq_len - 1)\n return output # [B H]\n\n def calculate_loss(self, interaction):\n item_seq = interaction[self.ITEM_SEQ]\n item_seq_len = interaction[self.ITEM_SEQ_LEN]\n seq_output = self.forward(item_seq, item_seq_len)\n pos_items = interaction[self.POS_ITEM_ID]\n if self.loss_type == 'BPR':\n neg_items = interaction[self.NEG_ITEM_ID]\n pos_items_emb = self.item_embedding(pos_items)\n neg_items_emb = self.item_embedding(neg_items)\n pos_score = torch.sum(seq_output * pos_items_emb, dim=-1) # [B]\n neg_score = torch.sum(seq_output * neg_items_emb, dim=-1) # [B]\n loss = self.loss_fct(pos_score, neg_score)\n return loss\n else: # self.loss_type = 'CE'\n test_item_emb = self.item_embedding.weight\n logits = torch.matmul(seq_output, test_item_emb.transpose(0, 1))\n loss = self.loss_fct(logits, pos_items)\n return loss\n\n def predict(self, interaction):\n item_seq = interaction[self.ITEM_SEQ]\n item_seq_len = interaction[self.ITEM_SEQ_LEN]\n test_item = interaction[self.ITEM_ID]\n \n seq_output = self.forward(item_seq, item_seq_len)\n test_item_emb = self.item_embedding(test_item)\n scores = torch.mul(seq_output, test_item_emb).sum(dim=1) # [B]\n return scores\n\n def full_sort_predict(self, interaction):\n item_seq = interaction[self.ITEM_SEQ]\n item_seq_len = interaction[self.ITEM_SEQ_LEN]\n seq_output = self.forward(item_seq, item_seq_len)\n test_items_emb = self.item_embedding.weight\n scores = torch.matmul(seq_output, test_items_emb.transpose(0, 1)) # [B n_items]\n return scores\n"
]
| [
[
"torch.nn.Dropout",
"torch.nn.CrossEntropyLoss",
"torch.ones",
"torch.sum",
"torch.nn.Embedding",
"torch.nn.LayerNorm",
"torch.mul"
]
]
|
greedyuser/kur | [
"ba6588ebfa5dec66d1e462c180618cc115fd38ef"
]
| [
"kur/containers/layers/squeeze.py"
]
| [
"\"\"\"\nCopyright 2017 Deepgram\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n\"\"\"\n\nfrom . import Layer, ParsingError\n\n###############################################################################\nclass Squeeze(Layer):\t\t\t\t# pylint: disable=too-few-public-methods\n\t\"\"\" A squeeze layer removes a dimension of size 1.\n\n\t\t# Usage\n\n\t\t```\n\t\tsqueeze:\n\t\t dimension: DIM\n\t\t```\n\n\t\t`DIM` must be an integer. It can be negative to count from the end.\n\t\"\"\"\n\n\t###########################################################################\n\tdef __init__(self, *args, **kwargs):\n\t\t\"\"\" Creates a new layer.\n\t\t\"\"\"\n\t\tsuper().__init__(*args, **kwargs)\n\t\tself.dimension = None\n\n\t###########################################################################\n\tdef _parse(self, engine):\n\t\t\"\"\" Parses out the layer.\n\t\t\"\"\"\n\t\tif isinstance(self.args, dict) and 'dimension' in self.args:\n\t\t\tself.dimension = engine.evaluate(self.args['dimension'])\n\t\telif isinstance(self.args, (str, int)):\n\t\t\tself.dimension = self.args\n\t\telse:\n\t\t\traise ParsingError('The arguments to the \"squeeze\" layer must be '\n\t\t\t\t'an integer, or dictionary with a \"dimension\" key and an '\n\t\t\t\t'integer value.')\n\t\ttry:\n\t\t\tself.dimension = int(self.dimension)\n\t\texcept ValueError:\n\t\t\traise ParsingError('\"dimension\" must evaluate to an integer.')\n\n\t###########################################################################\n\tdef _build(self, model):\n\t\t\"\"\" Instantiates the layer with the given backend.\n\t\t\"\"\"\n\t\tbackend = model.get_backend()\n\t\tif backend.get_name() == 'keras':\n\n\t\t\timport keras.layers as L\t\t\t# pylint: disable=import-error\n\t\t\timport keras.backend as K\t\t\t# pylint: disable=import-error\n\n\t\t\ttarget_dim = self.dimension\n\t\t\tif target_dim >= 0:\n\t\t\t\ttarget_dim += 1\n\n\t\t\tdef squeeze_shape(input_shape):\n\t\t\t\t\"\"\" Computes the new shape.\n\t\t\t\t\"\"\"\n\t\t\t\tdim = target_dim\n\t\t\t\tif dim < 0:\n\t\t\t\t\tdim += len(input_shape)\n\t\t\t\treturn input_shape[:dim] + input_shape[dim+1:]\n\n\t\t\tyield L.Lambda(\n\t\t\t\tlambda x: K.squeeze(x, axis=target_dim),\n\t\t\t\tsqueeze_shape,\n\t\t\t\tname=self.name\n\t\t\t)\n\n\t\telif backend.get_name() == 'pytorch':\n\n\t\t\timport torch\t\t\t\t\t\t# pylint: disable=import-error\n\n\t\t\tdef connect(inputs):\n\t\t\t\t\"\"\" Connects the layer.\n\t\t\t\t\"\"\"\n\t\t\t\tassert len(inputs) == 1\n\t\t\t\tdim = self.dimension\n\t\t\t\tif dim < 0:\n\t\t\t\t\tdim += len(inputs[0]['shape'])\n\t\t\t\tdim += 1\n\t\t\t\treturn {\n\t\t\t\t\t'shape' : self.shape([inputs[0]['shape']]),\n\t\t\t\t\t'layer' : model.data.add_operation(\n\t\t\t\t\t\tlambda x: torch.squeeze(x, dim)\n\t\t\t\t\t)(inputs[0]['layer'])\n\t\t\t\t}\n\n\t\t\tyield connect\n\n\t\telse:\n\t\t\traise ValueError('Unknown or unsupported backend: {}'.format(backend))\n\n\t###########################################################################\n\tdef shape(self, input_shapes):\n\t\t\"\"\" Returns the output shape of this layer for a given input shape.\n\t\t\"\"\"\n\t\tif len(input_shapes) > 1:\n\t\t\traise ValueError('Activations only take a single input.')\n\t\tinput_shape = input_shapes[0]\n\n\t\tdim = self.dimension\n\t\tif dim < 0:\n\t\t\tdim += len(input_shape)\n\t\tif dim >= len(input_shape) or dim < 0:\n\t\t\traise ValueError('Invalid input shape for expand layer with '\n\t\t\t\t'dimension {}: {}'.format(self.dimension, input_shape))\n\t\treturn input_shape[:dim] + input_shape[dim+1:]\n\n### EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF.EOF\n"
]
| [
[
"torch.squeeze"
]
]
|
AnxietyYoungPoet/tutorials | [
"514a513f2839106603fea2bba6b8908725f874fc"
]
| [
"beginner_source/Intro_to_TorchScript_tutorial.py"
]
| [
"\"\"\"\nIntroduction to TorchScript\n===========================\n\n*James Reed ([email protected]), Michael Suo ([email protected])*, rev2\n\nThis tutorial is an introduction to TorchScript, an intermediate\nrepresentation of a PyTorch model (subclass of ``nn.Module``) that\ncan then be run in a high-performance environment such as C++.\n\nIn this tutorial we will cover:\n\n1. The basics of model authoring in PyTorch, including:\n\n- Modules\n- Defining ``forward`` functions\n- Composing modules into a hierarchy of modules\n\n2. Specific methods for converting PyTorch modules to TorchScript, our\n high-performance deployment runtime\n\n- Tracing an existing module\n- Using scripting to directly compile a module\n- How to compose both approaches\n- Saving and loading TorchScript modules\n\nWe hope that after you complete this tutorial, you will proceed to go through\n`the follow-on tutorial <https://pytorch.org/tutorials/advanced/cpp_export.html>`_\nwhich will walk you through an example of actually calling a TorchScript\nmodel from C++.\n\n\"\"\"\n\nimport torch # This is all you need to use both PyTorch and TorchScript!\nprint(torch.__version__)\n\n\n######################################################################\n# Basics of PyTorch Model Authoring\n# ---------------------------------\n#\n# Letโs start out be defining a simple ``Module``. A ``Module`` is the\n# basic unit of composition in PyTorch. It contains:\n#\n# 1. A constructor, which prepares the module for invocation\n# 2. A set of ``Parameters`` and sub-\\ ``Modules``. These are initialized\n# by the constructor and can be used by the module during invocation.\n# 3. A ``forward`` function. This is the code that is run when the module\n# is invoked.\n#\n# Letโs examine a small example:\n#\n\nclass MyCell(torch.nn.Module):\n def __init__(self):\n super(MyCell, self).__init__()\n\n def forward(self, x, h):\n new_h = torch.tanh(x + h)\n return new_h, new_h\n\nmy_cell = MyCell()\nx = torch.rand(3, 4)\nh = torch.rand(3, 4)\nprint(my_cell(x, h))\n\n\n######################################################################\n# So weโve:\n#\n# 1. Created a class that subclasses ``torch.nn.Module``.\n# 2. Defined a constructor. The constructor doesnโt do much, just calls\n# the constructor for ``super``.\n# 3. Defined a ``forward`` function, which takes two inputs and returns\n# two outputs. The actual contents of the ``forward`` function are not\n# really important, but itโs sort of a fake `RNN\n# cell <https://colah.github.io/posts/2015-08-Understanding-LSTMs/>`__โthat\n# isโitโs a function that is applied on a loop.\n#\n# We instantiated the module, and made ``x`` and ``y``, which are just 3x4\n# matrices of random values. Then we invoked the cell with\n# ``my_cell(x, h)``. This in turn calls our ``forward`` function.\n#\n# Letโs do something a little more interesting:\n#\n\nclass MyCell(torch.nn.Module):\n def __init__(self):\n super(MyCell, self).__init__()\n self.linear = torch.nn.Linear(4, 4)\n\n def forward(self, x, h):\n new_h = torch.tanh(self.linear(x) + h)\n return new_h, new_h\n\nmy_cell = MyCell()\nprint(my_cell)\nprint(my_cell(x, h))\n\n\n######################################################################\n# Weโve redefined our module ``MyCell``, but this time weโve added a\n# ``self.linear`` attribute, and we invoke ``self.linear`` in the forward\n# function.\n#\n# What exactly is happening here? ``torch.nn.Linear`` is a ``Module`` from\n# the PyTorch standard library. Just like ``MyCell``, it can be invoked\n# using the call syntax. We are building a hierarchy of ``Module``\\ s.\n#\n# ``print`` on a ``Module`` will give a visual representation of the\n# ``Module``\\ โs subclass hierarchy. In our example, we can see our\n# ``Linear`` subclass and its parameters.\n#\n# By composing ``Module``\\ s in this way, we can succintly and readably\n# author models with reusable components.\n#\n# You may have noticed ``grad_fn`` on the outputs. This is a detail of\n# PyTorchโs method of automatic differentiation, called\n# `autograd <https://pytorch.org/tutorials/beginner/blitz/autograd_tutorial.html>`__.\n# In short, this system allows us to compute derivatives through\n# potentially complex programs. The design allows for a massive amount of\n# flexibility in model authoring.\n#\n# Now letโs examine said flexibility:\n#\n\nclass MyDecisionGate(torch.nn.Module):\n def forward(self, x):\n if x.sum() > 0:\n return x\n else:\n return -x\n\nclass MyCell(torch.nn.Module):\n def __init__(self):\n super(MyCell, self).__init__()\n self.dg = MyDecisionGate()\n self.linear = torch.nn.Linear(4, 4)\n\n def forward(self, x, h):\n new_h = torch.tanh(self.dg(self.linear(x)) + h)\n return new_h, new_h\n\nmy_cell = MyCell()\nprint(my_cell)\nprint(my_cell(x, h))\n\n\n######################################################################\n# Weโve once again redefined our MyCell class, but here weโve defined\n# ``MyDecisionGate``. This module utilizes **control flow**. Control flow\n# consists of things like loops and ``if``-statements.\n#\n# Many frameworks take the approach of computing symbolic derivatives\n# given a full program representation. However, in PyTorch, we use a\n# gradient tape. We record operations as they occur, and replay them\n# backwards in computing derivatives. In this way, the framework does not\n# have to explicitly define derivatives for all constructs in the\n# language.\n#\n# .. figure:: https://github.com/pytorch/pytorch/raw/master/docs/source/_static/img/dynamic_graph.gif\n# :alt: How autograd works\n#\n# How autograd works\n#\n\n\n######################################################################\n# Basics of TorchScript\n# ---------------------\n#\n# Now letโs take our running example and see how we can apply TorchScript.\n#\n# In short, TorchScript provides tools to capture the definition of your\n# model, even in light of the flexible and dynamic nature of PyTorch.\n# Letโs begin by examining what we call **tracing**.\n#\n# Tracing ``Modules``\n# ~~~~~~~~~~~~~~~~~~~\n#\n\nclass MyCell(torch.nn.Module):\n def __init__(self):\n super(MyCell, self).__init__()\n self.linear = torch.nn.Linear(4, 4)\n\n def forward(self, x, h):\n new_h = torch.tanh(self.linear(x) + h)\n return new_h, new_h\n\nmy_cell = MyCell()\nx, h = torch.rand(3, 4), torch.rand(3, 4)\ntraced_cell = torch.jit.trace(my_cell, (x, h))\nprint(traced_cell)\ntraced_cell(x, h)\n\n\n######################################################################\n# Weโve rewinded a bit and taken the second version of our ``MyCell``\n# class. As before, weโve instantiated it, but this time, weโve called\n# ``torch.jit.trace``, passed in the ``Module``, and passed in *example\n# inputs* the network might see.\n#\n# What exactly has this done? It has invoked the ``Module``, recorded the\n# operations that occured when the ``Module`` was run, and created an\n# instance of ``torch.jit.ScriptModule`` (of which ``TracedModule`` is an\n# instance)\n#\n# TorchScript records its definitions in an Intermediate Representation\n# (or IR), commonly referred to in Deep learning as a *graph*. We can\n# examine the graph with the ``.graph`` property:\n#\n\nprint(traced_cell.graph)\n\n\n######################################################################\n# However, this is a very low-level representation and most of the\n# information contained in the graph is not useful for end users. Instead,\n# we can use the ``.code`` property to give a Python-syntax interpretation\n# of the code:\n#\n\nprint(traced_cell.code)\n\n\n######################################################################\n# So **why** did we do all this? There are several reasons:\n#\n# 1. TorchScript code can be invoked in its own interpreter, which is\n# basically a restricted Python interpreter. This interpreter does not\n# acquire the Global Interpreter Lock, and so many requests can be\n# processed on the same instance simultaneously.\n# 2. This format allows us to save the whole model to disk and load it\n# into another environment, such as in a server written in a language\n# other than Python\n# 3. TorchScript gives us a representation in which we can do compiler\n# optimizations on the code to provide more efficient execution\n# 4. TorchScript allows us to interface with many backend/device runtimes\n# that require a broader view of the program than individual operators.\n#\n# We can see that invoking ``traced_cell`` produces the same results as\n# the Python module:\n#\n\nprint(my_cell(x, h))\nprint(traced_cell(x, h))\n\n\n######################################################################\n# Using Scripting to Convert Modules\n# ----------------------------------\n#\n# Thereโs a reason we used version two of our module, and not the one with\n# the control-flow-laden submodule. Letโs examine that now:\n#\n\nclass MyDecisionGate(torch.nn.Module):\n def forward(self, x):\n if x.sum() > 0:\n return x\n else:\n return -x\n\nclass MyCell(torch.nn.Module):\n def __init__(self, dg):\n super(MyCell, self).__init__()\n self.dg = dg\n self.linear = torch.nn.Linear(4, 4)\n\n def forward(self, x, h):\n new_h = torch.tanh(self.dg(self.linear(x)) + h)\n return new_h, new_h\n\nmy_cell = MyCell(MyDecisionGate())\ntraced_cell = torch.jit.trace(my_cell, (x, h))\nprint(traced_cell.code)\n\n\n######################################################################\n# Looking at the ``.code`` output, we can see that the ``if-else`` branch\n# is nowhere to be found! Why? Tracing does exactly what we said it would:\n# run the code, record the operations *that happen* and construct a\n# ScriptModule that does exactly that. Unfortunately, things like control\n# flow are erased.\n#\n# How can we faithfully represent this module in TorchScript? We provide a\n# **script compiler**, which does direct analysis of your Python source\n# code to transform it into TorchScript. Letโs convert ``MyDecisionGate``\n# using the script compiler:\n#\n\nscripted_gate = torch.jit.script(MyDecisionGate())\n\nmy_cell = MyCell(scripted_gate)\ntraced_cell = torch.jit.script(my_cell)\nprint(traced_cell.code)\n\n\n######################################################################\n# Hooray! Weโve now faithfully captured the behavior of our program in\n# TorchScript. Letโs now try running the program:\n#\n\n# New inputs\nx, h = torch.rand(3, 4), torch.rand(3, 4)\ntraced_cell(x, h)\n\n\n######################################################################\n# Mixing Scripting and Tracing\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n# Some situations call for using tracing rather than scripting (e.g.ย a\n# module has many architectural decisions that are made based on constant\n# Python values that we would like to not appear in TorchScript). In this\n# case, scripting can be composed with tracing: ``torch.jit.script`` will\n# inline the code for a traced module, and tracing will inline the code\n# for a scripted module.\n#\n# An example of the first case:\n#\n\nclass MyRNNLoop(torch.nn.Module):\n def __init__(self):\n super(MyRNNLoop, self).__init__()\n self.cell = torch.jit.trace(MyCell(scripted_gate), (x, h))\n\n def forward(self, xs):\n h, y = torch.zeros(3, 4), torch.zeros(3, 4)\n for i in range(xs.size(0)):\n y, h = self.cell(xs[i], h)\n return y, h\n\nrnn_loop = torch.jit.script(MyRNNLoop())\nprint(rnn_loop.code)\n\n\n\n######################################################################\n# And an example of the second case:\n#\n\nclass WrapRNN(torch.nn.Module):\n def __init__(self):\n super(WrapRNN, self).__init__()\n self.loop = torch.jit.script(MyRNNLoop())\n\n def forward(self, xs):\n y, h = self.loop(xs)\n return torch.relu(y)\n\ntraced = torch.jit.trace(WrapRNN(), (torch.rand(10, 3, 4)))\nprint(traced.code)\n\n\n######################################################################\n# This way, scripting and tracing can be used when the situation calls for\n# each of them and used together.\n#\n# Saving and Loading models\n# -------------------------\n#\n# We provide APIs to save and load TorchScript modules to/from disk in an\n# archive format. This format includes code, parameters, attributes, and\n# debug information, meaning that the archive is a freestanding\n# representation of the model that can be loaded in an entirely separate\n# process. Letโs save and load our wrapped RNN module:\n#\n\ntraced.save('wrapped_rnn.zip')\n\nloaded = torch.jit.load('wrapped_rnn.zip')\n\nprint(loaded)\nprint(loaded.code)\n\n\n######################################################################\n# As you can see, serialization preserves the module hierarchy and the\n# code weโve been examining throughout. The model can also be loaded, for\n# example, `into\n# C++ <https://pytorch.org/tutorials/advanced/cpp_export.html>`__ for\n# python-free execution.\n#\n# Further Reading\n# ~~~~~~~~~~~~~~~\n#\n# Weโve completed our tutorial! For a more involved demonstration, check\n# out the NeurIPS demo for converting machine translation models using\n# TorchScript:\n# https://colab.research.google.com/drive/1HiICg6jRkBnr5hvK2-VnMi88Vi9pUzEJ\n#\n"
]
| [
[
"torch.jit.script",
"torch.jit.load",
"torch.jit.trace",
"torch.zeros",
"torch.tanh",
"torch.nn.Linear",
"torch.relu",
"torch.rand"
]
]
|
johnjmolina/MLKyoto | [
"dd1f7447f8ed6770da7132125c1f26b49e19c318"
]
| [
"_notebooks/utils/pdesolver/etdrk.py"
]
| [
"# last\nimport numpy as np\nfrom . import phi\n\nclass _etdrk:\n def __init__(self, *, G, dt):\n self.G = G\n self.dt = dt\n\nclass etdrk1(_etdrk):\n def __init__(self, *, L, G, dt, dps=100):\n super().__init__(G=G, dt=dt)\n hL = dt*L.reshape(-1)\n self.phi = np.array([phi.phin(n, hL, dps=dps).reshape(L.shape) for n in range(2)])\n\n def step(self, u):\n u[...] = self.phi[0,...] * u[...] + self.dt * self.phi[1,...] * self.G(u)\n return u\n\n\nclass etdrk2(_etdrk):\n def __init__(self, *, L, G, dt, dtype, dps=100):\n super().__init__(G=G, dt=dt)\n hL = dt*L.reshape(-1)\n hLh = hL / 2\n phi1 = phi.phin(1, hL, dps=dps).reshape(L.shape)\n phi2 = phi.phin(2, hL, dps=dps).reshape(L.shape)\n \n self.phi = np.array([phi.phin(n, hL, dps=dps).reshape(L.shape) for n in range(1)])\n self.phih = np.array([phi.phin(n, hLh, dps=dps).reshape(L.shape) for n in range(2)])\n self.aux = np.zeros((3,) + L.shape, dtype=dtype)\n self.hc1 = self.dt*(phi1[...]-2.0*phi2[...])\n self.hc2 = 2.0*self.dt*phi2[...]\n\n def step(self, u):\n Ui, G1, G2 = self.aux[0,...], self.aux[1,...], self.aux[2,...]\n\n # G1\n G1[...] = self.G(u)\n\n # U2, G2\n Ui[...] = self.phih[0,...]*u[...] + self.dt*(0.5*self.phih[1,...]*G1[...])\n G2[...] = self.G(Ui)\n\n # u_{n+1}\n u[...] = self.phi[0,...]*u[...] + self.hc1[...]*G1[...] + self.hc2[...]*G2[...]\n return u\n\nclass etdrk3(_etdrk):\n \"\"\" Heun's method : worst case order 2.75\"\"\"\n def __init__(self, *, L, G, dt, dtype, dps=100):\n super().__init__(G=G, dt=dt)\n hL = dt*L.reshape(-1)\n hL13 = hL/3.0\n hL23 = 2.0*hL13\n phi1 = phi.phin(1, hL, dps=dps).reshape(L.shape)\n phi1_13 = phi.phin(1, hL13, dps=dps).reshape(L.shape)\n phi1_23 = phi.phin(1, hL23, dps=dps).reshape(L.shape)\n phi2 = phi.phin(2, hL, dps=dps).reshape(L.shape)\n phi2_23 = phi.phin(2, hL23, dps=dps).reshape(L.shape)\n\n self.phi = np.array([phi.phin(n, hL, dps=dps).reshape(L.shape) for n in range(1)])\n self.phi13 = np.array([phi.phin(n, hL13,dps=dps).reshape(L.shape) for n in range(1)])\n self.phi23 = np.array([phi.phin(n, hL23,dps=dps).reshape(L.shape) for n in range(1)])\n self.hc1 = self.dt*(phi1 - 1.5*phi2)\n self.hc3 = self.dt*1.5*phi2\n self.hc1_2 = self.dt/3.0*phi1_13\n self.hc1_3 = self.dt/3.0*(2.0*phi1_23 - 4.0*phi2_23)\n self.hc2_3 = self.dt/3.0*(4.0*phi2_23)\n self.aux = np.zeros((3,) + L.shape, dtype=dtype)\n \n def step(self, u):\n Ui = self.aux[0,...]\n G1 = self.aux[1,...]\n G2 = self.aux[2,...]\n G3 = self.aux[2,...] # yes G3 and G2 are aliased\n\n #G1\n G1[...] = self.G(u)\n\n #U2(G1), G2\n Ui[...] = self.phi13[0,...]*u[...] + self.hc1_2[...]*G1[...]\n G2[...] = self.G(Ui)\n\n #U3(G1, G2), G3\n Ui[...] = self.phi23[0,...]*u[...] + self.hc1_3[...]*G1[...] + self.hc2_3[...]*G2[...]\n G3[...] = self.G(Ui)\n\n #u_{n+1}(G1, G3)\n u[...] = self.phi[0,...]*u[...] + self.hc1[...]*G1[...] + self.hc3[...]*G3[...]\n return u\n \n\nclass etdrk45(_etdrk):\n \"\"\" Hochbruck and Ostermann's fourth order ETDRK method\"\"\"\n def __init__(self, *, L, G, dt, dtype, dps=100):\n super().__init__(G=G, dt=dt)\n # temporary data\n hL = dt*L.reshape(-1)\n hLh = hL/2\n phi3 = phi.phin(3, hL, dps=dps).reshape(L.shape)\n phih3 = phi.phin(3, hLh,dps=dps).reshape(L.shape)\n \n # persistent data\n self.phi = np.array([phi.phin(n, hL, dps=dps).reshape(L.shape) for n in range(3)])\n self.phih = np.array([phi.phin(n, hLh, dps=dps).reshape(L.shape) for n in range(3)])\n self.a52 = phi.phi_a52(phi2_dt = self.phi[2], phi3_dt = phi3, phi2_hdt = self.phih[2], phi3_hdt = phih3)\n self.aux = np.zeros((6,)+L.shape, dtype=dtype)\n self.hc1 = self.dt*(self.phi[1,:] - 3*self.phi[2,:] + 4*phi3[:])\n self.hc4 = self.dt*(4*phi3[:] - self.phi[2,:])\n self.hc5 = self.dt*(4.0*self.phi[2,:] - 8.0*phi3[:])\n\n def step(self, u):\n Ui = self.aux[0,...]\n G1 = self.aux[1,...]\n G2 = self.aux[2,...]\n G3 = self.aux[3,...]\n G4 = self.aux[4,...]\n G5 = self.aux[5,...]\n uh = self.aux[5,...] # yes, uh and G5 are aliased\n\n uh[...] = self.phih[0,...]*u[...]\n\n #G1\n G1[...] = self.G(u)\n\n #U2(G1),G2 \n Ui[...] = uh[...] + self.dt*(0.5*self.phih[1,...]*G1[...])\n G2[...] = self.G(Ui)\n\n #U3(G1, G2),G3\n Ui[...] = uh[...] + self.dt*((0.5*self.phih[1,...]-self.phih[2,...])*G1[...] + self.phih[2,...]*G2[...])\n G3[...] = self.G(Ui)\n\n #U4(G1, G2, G3),G4\n Ui[...] = self.phi[0,...]*u[...] + self.dt*((self.phi[1,...] - 2*self.phi[2,...])*G1[...] + self.phi[2,...]*(G2[...] + G3[...]))\n G4[...] = self.G(Ui)\n\n #U5(G1, G2, G3, G4),G5\n Ui[...] = uh[...] + self.dt*((0.5*self.phih[1,...] - 0.25*self.phih[2,...] - self.a52[...])*G1[...] + self.a52[...]*(G2[...] + G3[...]) + (0.25*self.phih[2,...] - self.a52[...])*G4[...])\n G5[...] = self.G(Ui)\n\n # u_{n+1}(G1, G4, G5)\n u[...] = self.phi[0,...]*u[...] + self.hc1[...]*G1[...] + self.hc4[...]*G4[...] + self.hc5[...]*G5[...]\n return u\n"
]
| [
[
"numpy.zeros"
]
]
|
kemaeleon/drug_share | [
"a3c040a9ba1b2c4a9baafd6f97f59c89318fd6af"
]
| [
"drugshare/drugshare/templates/save.py"
]
| [
"import folium\nfrom folium import IFrame\nimport folium.plugins as plugins\nimport pandas as pd\nimport geopandas as gpd\nimport matplotlib.pyplot as plt\nimport requests\nimport io\nimport os\nimport numpy as np\nfrom datetime import timedelta, date\ndef daterange(start_date, end_date):\n for n in range(int ((end_date - start_date).days)):\n yield start_date + timedelta(n)\n\ndef go_back(end_date, days):\n for n in range(0,days):\n yield end_date - timedelta(n)\n\ndef ref_back(end_date, days):\n yield end_date - timedelta(days)\n\n\npd.set_option('display.max_columns', 50, 'display.max_rows', 500)\n\n''' Population Data '''\npop = pd.read_csv(\"pop_data.csv\")[['AREA', '2020']]\npop['2020']= pop['2020'].str.replace(\",\",\"\").astype(float)\n\n\n''' Empty Folium Map'''\n\nm = folium.Map(location=(51.5,0))\n\n''' Load simplified geometry file '''\nstate_geo = r\"map.json\"\n\n'''Calculate lookup for centroids of Lower Tier Local Authories '''\nfrom shapely.geometry import shape\nimport json\n\nlookup_cog = {}\nwith open('map.json') as json_file:\n collection = json.load(json_file)\n features = collection[\"features\"]\n for feature in features:\n s = shape(feature[\"geometry\"])\n l = feature[\"properties\"][\"lad19nm\"]\n lookup_cog[l]=s.centroid\n\n\n'''Get Covid 19 government data file'''\nurl=\"https://coronavirus.data.gov.uk/downloads/csv/coronavirus-cases_latest.csv\"\ns=requests.get(url).content\nvirus = pd.read_csv(io.StringIO(s.decode('utf-8'))).drop_duplicates(subset=None, keep='first', inplace=False)\nvirus = virus.replace(to_replace=\"Hackney and City of London\", value=\"Hackney\")\n''' Select lower tier LA data '''\nvirus = virus.loc[virus['Area type'] == 'ltla']\nvirus = virus.replace(to_replace = \"Cornwall and Isles of Scilly\", value=\"Cornwall\")\nvirus = virus[['Area name', 'Specimen date', 'Daily lab-confirmed cases']]\nvirus_index = pd.pivot_table(virus, index='Area name', columns= ['Specimen date'], values = \"Daily lab-confirmed cases\").fillna(0).rename_axis(None, axis=1)\nvirus_index['Area nm'] = virus_index.index\n\n''' Merge with Population data '''\ncovid_uk = virus_index.merge(pop, how='inner', left_on='Area nm', right_on='AREA')\ncovid_uk = covid_uk.fillna(0)\n\n\nstart_date = date(2020, 3,12)\nend_date = date.today()-timedelta(3)\n\n''' Calculate sum of weekly cases and differences of sums of weekly cases, sds, sdsnorm '''\n(sds, sdsnorm, rsds, delta_sdsnorm,ratio,barplots) = (covid_uk.copy(deep=True) for i in range(6))\n\nbarplots = barplots.set_index('AREA')\nbarplots = barplots.drop(columns=['2020','Area nm'])\nfor index, row in barplots.iterrows():\n label = str(index).replace(\" \",\"_\")\n tmp = barplots.T[index]\n tmp.plot(figsize=(3.0,3.0))\n plt.xticks(rotation='45')\n plt.ylabel(\"Daily cases\")\n plt.tight_layout()\n plt.savefig(os.path.join(os.getcwd(),'static',label + '.png'))\n plt.close()\n\n\nth = 0\nfor single_date in daterange(start_date, end_date):\n date = single_date.strftime(\"%Y-%m-%d\")\n sds[date] = 0\n for days in go_back(single_date,7):\n back_day = days.strftime(\"%Y-%m-%d\")\n sds[date] += covid_uk[back_day]\n sdsnorm[date]=np.sqrt(sds[date]/(sds['2020']/100000)) \n th = max(th, sdsnorm[date].max())\nbins = [0,0.00001,1,4,7,14,20,th]\n\n\nfor single_date in daterange(start_date, end_date):\n date = single_date.strftime(\"%Y-%m-%d\")\n show = str(single_date)\n print(show, sum(covid_uk[date]))\n m = folium.Map(location=(51.5,0))\n lname = \"week up to: \" + show + \", sqrt (weekly confirmed cases / 100k people)\"\n folium.Choropleth(\n tiles='cartodbpositron',\n geo_data=state_geo,\n name='choropleth',\n data=sdsnorm,\n legend_name = lname,\n columns=['Area nm', show],\n key_on='feature.properties.lad19nm',\n fill_opacity=0.7,\n line_opacity=0.2,\n bins = bins,\n ).add_to(m)\n\n for day in ref_back(single_date, 7):\n back_day = day.strftime(\"%Y-%m-%d\")\n rsds[date] = sds[date]-sds[back_day]\n #delta_sdsnorm[date] = sdsnorm[date]-sdsnorm[back_day]\n delta_sdsnorm[date] = sdsnorm[date]\n ratio[date] = sds[date]/sds[back_day].replace(np.inf, 5)\n ratio[date] = ratio[date].fillna(1)\n for index, row in rsds.iterrows():\n ly=str(row['AREA'])\n if ly == 'Hackney':\n ly = \"Hackney and City of London\" \n l1 = \"LA: \" + ly + \"<br>\" \n l2 = \"Pop: \" + str(row['2020']) + \"<br>\" \n l3 = \"Week to \" + str(date) + \", new cases: \" + str(sds[date][index]) + \"<br>\" \n l4 = \"Change prev week: \" + str(row[date]) + \"<br>\"\n LA = str(row['AREA']).replace(\" \",\"_\")\n im = '<img src=\"https://data.kemaeleon.com/static/' + LA + '.png\">'\n popup_str = \"<p style=font-family:'sans-serif' font-weight:300>\" + l1 + l2 + l3+ l4 + str(im) + \"</p>\"\n iframe = IFrame(html=popup_str, width=600, height=400)\n normpt = float(delta_sdsnorm[date][index])\n ratio_pt = float(ratio[date][index])\n bubblestring='lightgrey'\n if ratio_pt == np.inf:\n ratio_pt = 1\n bubblestring = 'blue'\n if ratio_pt > 1.0:\n bubblestring = 'red'\n elif ratio_pt < 1.0:\n bubblestring = 'green'\n ratio_pt = 1.0\n pt = lookup_cog[row['AREA']] \n folium.Circle(\n location = [pt.coords[0][1], pt.coords[0][0]],\n popup=folium.Popup(iframe, max_width=350),\n radius=ratio_pt*200,\n fill_opacity=0.3,\n fill_color=bubblestring,\n color=bubblestring,\n fill=False,\n ).add_to(m)\n '''\n if normpt > 0:\n colstring='red'\n else:\n colstring='green'\n old = str(sds[back_day][index])\n pt = lookup_cog[row['AREA']]\n if np.square(normpt) > 10 :\n pt = lookup_cog[row['AREA']],\n folium.Marker(\n location = [pt[0].coords[0][1], pt[0].coords[0][0]],\n popup= popup_str,\n icon=folium.Icon(color=colstring, icon='info-sign'),\n ).add_to(m)\n '''\n title_html = '''\n <h3 align=\"center\" style=\"font-size:20px\"><b>Density of weekly tier 1 and tier 2 Covid-19 Cases in England LAs</b></h3>\n <h3 This is a prototype, code and content under MIT licence</b></h3>\n <h6 align=\"center\" style=\"font-size:20px\"> code at: https://github.com/kemaeleon/drug_share/blob/master/drugshare/drugshare/templates/cv_bubble_new.py, MIT Licence</h6>\n <h3 align=\"center\" style=\"font-size:20px\"><b>Maps Released Under MIT Licence</b></h3>\n <h6 align=\"center\" style=\"font-size:12px\"><b>Please modifiy the date in the URL for data from a different date</b></h6> <h6 align=\"center\" style=\"font-size:12px\"><b>red bubble size reflects growing of weekly infections, current/previous week</b></h6> \n <h6 align=\"center\" style=\"font-size:12px\"><b>orange: increase, lime: decrease, grey: no change, turquoise bubble: new from zero</b></h6> \n '''\n top_of_page = '''\n <body>\n <div class=\"container\">\n <div class=\"row\">\n <div class=\"col-sm-12\">\n <img src=\"kemaeleon.png\"\" alt=\"lessons from viruses\">\n </div>\n\n </div>\n </div>\n '''\n style = '<style>.leaflet-popup-pane{margin-top: 100px;}</style>'\n head = \"\"\"\n<meta charset=\"utf-8\">\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\">\n\"\"\"\n m.get_root().header.add_child(folium.Element(head)) \n m.get_root().header.add_child(folium.Element(style)) \n m.get_root().html.add_child(folium.Element(top_of_page))\n \n m.save(show + '.html')\n with open(show + '.html', 'a') as file:\n file.write(title_html)\n"
]
| [
[
"matplotlib.pyplot.tight_layout",
"pandas.read_csv",
"numpy.sqrt",
"pandas.pivot_table",
"matplotlib.pyplot.close",
"pandas.set_option",
"matplotlib.pyplot.xticks",
"matplotlib.pyplot.ylabel"
]
]
|
oshadura/opendata-higgs-discovery | [
"47b4ac787a69b9580fc1f72948d3af0bdc20759b"
]
| [
"notebooks/atlas_analysis.py"
]
| [
"import asyncio\nfrom typing import List, Union\n\nimport numpy as np\nfrom coffea import hist\nfrom coffea.processor.servicex import Analysis, DataSource, LocalExecutor\nfrom func_adl import ObjectStream\nfrom func_adl_servicex import ServiceXSourceUpROOT\nfrom servicex.servicex import ServiceXDataset\n\n\ndef apply_event_cuts(source: ObjectStream) -> ObjectStream:\n '''Event level cuts for the analysis. Keep from sending data that we\n aren't going to need at all in the end.\n '''\n return (source\n .Where(lambda e: e.trigE or e.trigM))\n\n\ndef good_leptons(source: ObjectStream) -> ObjectStream:\n '''Select out all good leptons from each event. Return their pt, eta, phi,\n and E, and other things needed downstream.\n\n Because uproot doesn't tie toegher the objects, we can't do any cuts at this point.\n '''\n return source.Select(lambda e:\n {\n 'lep_pt': e.lep_pt,\n 'lep_eta': e.lep_eta,\n 'lep_phi': e.lep_phi,\n 'lep_energy': e.lep_E,\n 'lep_charge': e.lep_charge,\n 'lep_ptcone30': e.lep_ptcone30,\n 'lep_etcone20': e.lep_etcone20,\n 'lep_typeid': e.lep_type,\n 'lep_trackd0pvunbiased': e.lep_trackd0pvunbiased,\n 'lep_tracksigd0pvunbiased': e.lep_tracksigd0pvunbiased,\n 'lep_z0': e.lep_z0,\n 'mcWeight': e.mcWeight,\n 'scaleFactor': e.scaleFactor_ELE*e.scaleFactor_MUON*e.scaleFactor_LepTRIGGER*e.scaleFactor_PILEUP,\n })\n\n\nclass ATLAS_Higgs_4L(Analysis):\n '''Run the 4 Lepton analysis on ATLAS educational ntuples\n '''\n @staticmethod\n def process(events):\n from collections import defaultdict\n\n import awkward as ak\n\n sumw = defaultdict(float)\n mass_hist = hist.Hist(\n \"Events\",\n hist.Cat(\"channel\", \"Channel\"),\n hist.Cat(\"dataset\", \"Dataset\"),\n hist.Bin(\"mass\", \"$Z_{ee}$ [GeV]\", 60, 60, 180),\n )\n\n dataset = events.metadata['dataset']\n leptons = events.lep\n\n weight = ak.Array(np.ones(len(events.scaleFactor))) if events.metadata['is_data'] \\\n else events.scaleFactor*events.mcWeight\n\n # Good electon selection\n electrons_mask = ((leptons.typeid == 11)\n & (leptons.pt > 7000.0)\n & (abs(leptons.eta) <2.47)\n & (leptons.etcone20 / leptons.pt < 0.3)\n & (leptons.ptcone30 / leptons.pt < 0.3)\n & (abs(leptons.trackd0pvunbiased) / leptons.tracksigd0pvunbiased < 5)\n & (abs(leptons.z0*np.sin(leptons.theta)) < 0.5)\n )\n\n electrons_good = leptons[electrons_mask]\n\n # Good muon selection\n muon_mask = ((leptons.typeid == 13)\n & (leptons.pt > 5000.0)\n & (abs(leptons.eta) <2.5)\n & (leptons.etcone20 / leptons.pt < 0.3)\n & (leptons.ptcone30 / leptons.pt < 0.3)\n & (abs(leptons.trackd0pvunbiased) / leptons.tracksigd0pvunbiased < 3)\n & (abs(leptons.z0*np.sin(leptons.theta)) < 0.5)\n )\n\n muons_good = leptons[muon_mask]\n\n # In order to cut in sorted lepton pt, we have to rebuild a lepton array here\n leptons_good = ak.concatenate((electrons_good, muons_good), axis=1)\n leptons_good_index = ak.argsort(leptons_good.pt, ascending=False)\n leptons_good_sorted = leptons_good[leptons_good_index]\n\n # Event level cuts now that we know the good leptons\n # - We need to look at 4 good lepton events only\n # - We need same flavor, so check for even numbers of each flavor\n # - all charges must be balenced\n event_mask = (\n (ak.num(leptons_good_sorted) == 4)\n & ((ak.num(electrons_good) == 0) | (ak.num(electrons_good) == 2) | (ak.num(electrons_good) == 4))\n & ((ak.num(muons_good) == 0) | (ak.num(muons_good) == 2) | (ak.num(muons_good) == 4))\n & (ak.sum(electrons_good.charge, axis=1) == 0)\n & (ak.sum(muons_good.charge, axis=1) == 0)\n )\n\n # Next, we need to cut on the pT for the leading, sub-leading, and sub-sub-leading lepton\n leptons_good_preselection = leptons_good[event_mask]\n event_good_lepton_mask = (\n (leptons_good_preselection[:,0].pt > 25000.0)\n & (leptons_good_preselection[:,1].pt > 15000.0)\n & (leptons_good_preselection[:,2].pt > 10000.0)\n )\n\n # Now, we need to rebuild the good muon and electron lists with those selections\n muons_analysis = muons_good[event_mask][event_good_lepton_mask]\n electrons_analysis = electrons_good[event_mask][event_good_lepton_mask]\n\n # Lets do eemumu events - as there are no permutations there.abs\n # At this point if there are two muons, there must be two electrons\n eemumu_mask = (ak.num(muons_analysis) == 2)\n muon_eemumu = muons_analysis[eemumu_mask]\n electrons_eemumu = electrons_analysis[eemumu_mask]\n z1_eemumu = muon_eemumu[:,0] + muon_eemumu[:,1]\n z2_eemumu = electrons_eemumu[:,0] + electrons_eemumu[:,1]\n h_eemumu = z1_eemumu + z2_eemumu\n\n sumw[dataset] += len(h_eemumu)\n mass_hist.fill(\n channel=r'$ee\\mu\\mu$',\n mass=h_eemumu.mass/1000.0,\n dataset=dataset,\n weight=weight[eemumu_mask]\n )\n\n # Next, eeee. For this we have to build permutations and select the best one\n def four_leptons_one_flavor(same_flavor_leptons, event_weights, channel: str):\n fl_positive = same_flavor_leptons[same_flavor_leptons.charge > 0]\n fl_negative = same_flavor_leptons[same_flavor_leptons.charge < 0]\n fl_pairs = ak.cartesian((fl_positive, fl_negative))\n # fl_pairs_args = ak.argcartesian((fl_positive, fl_negative))\n zs = fl_pairs[\"0\"] + fl_pairs[\"1\"]\n\n delta = abs((91.18*1000.0) - zs.mass[:])\n closest_masses = np.min(delta, axis=-1)\n the_closest = (delta == closest_masses)\n the_furthest = the_closest[:,::-1]\n\n h_eeee = zs[the_closest] + zs[the_furthest]\n sumw[dataset] += len(h_eeee)\n mass_hist.fill(\n channel=channel,\n mass=ak.flatten(h_eeee.mass/1000.0),\n dataset=dataset,\n weight=event_weights,\n )\n\n four_leptons_one_flavor(electrons_analysis[(ak.num(electrons_analysis) == 4)],\n weight[(ak.num(electrons_analysis) == 4)],\n '$eeee$')\n four_leptons_one_flavor(muons_analysis[(ak.num(muons_analysis) == 4)],\n weight[(ak.num(muons_analysis) == 4)],\n '$\\\\mu\\\\mu\\\\mu\\\\mu$')\n \n return {\n \"sumw\": sumw,\n \"mass\": mass_hist,\n }\n\n\ndef make_ds(name: str, query: ObjectStream):\n '''Create a ServiceX Datasource for a particular ATLAS Open data file\n '''\n from utils import files\n is_data = name == 'data'\n datasets = [ServiceXDataset(files[name]['files'], backend_name='open_uproot')]\n return DataSource(query=query, metadata={'dataset': name, 'is_data': is_data}, datasets=datasets)\n\n\nasync def run_atlas_4l_analysis(ds_names: Union[str,List[str]]):\n '''\n Run on a known analysis file/files and return the result.\n Should be fine to start many of these at once.\n\n ds_names are names in utils, or \"*\" which means everything.\n '''\n # Parse the dataset if need be.\n if isinstance(ds_names, str):\n if ds_names != '*':\n raise Exception('DS Name should be a list or a * for everything')\n from utils import files\n ds_names = list(files.keys())\n\n # Create the query\n ds = ServiceXSourceUpROOT('cernopendata://dummy', \"mini\", backend_name='open_uproot')\n ds.return_qastle = True\n leptons = good_leptons(apply_event_cuts(ds))\n\n executor = LocalExecutor()\n #executor = DaskExecutor(client_addr=\"tls://localhost:8786\")\n datasources = [make_ds(ds_name, leptons) for ds_name in ds_names]\n\n # Create the analysis and we can run from there.\n analysis = ATLAS_Higgs_4L()\n\n async def run_updates_stream(accumulator_stream, name):\n '''Run to get the last item in the stream'''\n coffea_info = None\n try:\n async for coffea_info in accumulator_stream:\n pass\n except Exception as e:\n raise Exception(f'Failure while processing {name}') from e\n return coffea_info\n\n # Why do I need run_updates_stream, why not just await on execute (which fails with async gen can't).\n # Perhaps something from aiostream can help here?\n all_plots = await asyncio.gather(*[run_updates_stream(executor.execute(analysis, source), source.metadata['dataset']) for source in datasources])\n\n # Combine the plots\n all_plots_mass = [p['mass'] for p in all_plots]\n mass = all_plots_mass[0]\n for p in all_plots_mass[1:]:\n mass.add(p)\n\n return mass\n"
]
| [
[
"numpy.sin",
"numpy.min"
]
]
|
joaosoares/xray_teeth_detection | [
"2385038e1fa609988eb2dfef11c0fff04815b23f"
]
| [
"src/shape_test.py"
]
| [
"import unittest\n\nimport numpy as np\nimport numpy.testing as npt\n\nimport matplotlib.pyplot as plt\n\nfrom point import Point\nfrom shape import Shape\nfrom shapeutils import plot_shape, plot_vecs, plot_rectangle\nfrom testutils import load_incisor\n\n\nclass ShapeTest(unittest.TestCase):\n def test_translate_all_to_origin(self):\n shapes = [\n Shape([(1, 2), (1, 3), (1, 4), (2, 4), (3, 4), (3, 3), (3, 2), (2, 2)]),\n Shape(\n [(11, 2), (11, 3), (11, 4), (12, 4), (13, 4), (13, 3), (13, 2), (12, 2)]\n ),\n ]\n\n Shape.translate_all_to_origin(shapes)\n self.assertEqual(shapes[0].points.all(), shapes[1].points.all())\n\n def test_align_shapes(self):\n s1 = Shape([(1, 2), (1, 3), (1, 4), (2, 4), (3, 4), (3, 3), (3, 2), (2, 2)])\n s2 = Shape([(5, 2), (6, 3), (7, 4), (8, 3), (9, 2), (8, 1), (7, 0), (6, 1)])\n\n Shape.translate_all_to_origin([s1, s2])\n s2.align(s1)\n\n npt.assert_almost_equal(s1.points, s2.points, decimal=1)\n\n def test_get_orthogonal_vectors(self):\n round_shape = Shape(\n [\n (4.5, 1),\n (4, 1),\n (3.5, 1),\n (3, 1),\n (2.5, 1.5),\n (2, 2),\n (1.5, 2.5),\n (1, 3),\n (1, 3.5),\n (1, 4),\n (1.5, 4.5),\n (2, 5),\n (2.5, 5.5),\n (3, 6),\n (3.5, 6),\n (4, 6),\n (4.5, 6),\n (5, 6),\n (5.5, 5.5),\n (6, 5),\n (6.5, 4.5),\n (7, 4),\n (7, 3.5),\n (7, 3),\n (6.5, 2.5),\n (6, 2),\n (5.5, 1.5),\n (5, 1),\n ]\n )\n ort_vects = round_shape.get_orthogonal_vectors()\n print(ort_vects)\n\n plot_shape(round_shape, display=False)\n plot_vecs(ort_vects, round_shape.as_point_list())\n\n def test_as_point_list(self):\n s1 = Shape([(1, 2), (2, 1)])\n self.assertListEqual(s1.as_point_list(), [Point(1, 2), Point(2, 1)])\n\n def test_x_vector(self):\n s1 = Shape([(1, 2), (3, 4), (5, 6)])\n x_vec = s1.x_vector()\n npt.assert_array_equal(x_vec, np.array([1, 3, 5]))\n\n def test_y_vector(self):\n s1 = Shape([(1, 2), (3, 4), (5, 6)])\n y_vec = s1.y_vector()\n npt.assert_array_equal(y_vec, np.array([2, 4, 6]))\n\n def test_conform_to_rect(self):\n s1 = Shape([(-20, 20), (0, 20), (0, -40), (-20, -40)])\n bottom_left = Point(0, 0)\n top_right = Point(50, 50)\n plot_rectangle(bottom_left, top_right, display=False)\n s2 = s1.conform_to_rect(bottom_left, top_right)\n plot_shape([s1, s2])\n npt.assert_equal(s2.axis_means(), np.array([25, 25]))\n\n def test_apply_procrustes(self):\n asm, image_shapes = load_incisor()\n shapes = [imgshp.shape for imgshp in image_shapes]\n Shape.apply_procrustes(shapes)\n # Shape.translate_all_to_origin(shapes)\n plot_shape(shapes, dots=False)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n"
]
| [
[
"numpy.testing.assert_almost_equal",
"numpy.array"
]
]
|
BBQuercus/useful-scripts | [
"e476b08b80a633622052c21bea326b2187bf8798"
]
| [
"trackmate.py"
]
| [
"\"\"\"\\U0001F1EB\\U0001F1EF \\U00002B50 CSV track coordinate to TrackMate XML conversion.\n\nFiji allows for quick and easy viewing of images. TrackMate can be used to view tracks.\nUnfortunately, it isn't that simple to convert \"normal\" coordinate output into\nTrackMate-viewable format.\n\nRequires a \"tracks.csv\" file that contains the following columns:\n- x, y: Coordinate positions in x-/y-axis\n- particle: Unique ID assigned to all coordinates along one track\n- frame: Current point in time / frame\n\"\"\"\n\nimport argparse\nimport os\nimport tempfile\nimport xml.dom.minidom\nimport xml.etree.ElementTree as ET\n\nimport numpy as np\nimport pandas as pd\nimport skimage.io\n\n\ndef get_gaps(frames):\n def __longest_consecutive(a):\n \"\"\"Return length of longest consecutive range in list of integers.\"\"\"\n a = set(a)\n longest = 0\n for i in a:\n if i - 1 not in a:\n streak = 0\n while i in a:\n i += 1\n streak += 1\n longest = max(longest, streak)\n return longest\n\n full_length = np.arange(min(frames), max(frames))\n diff = np.setdiff1d(full_length, frames)\n longest = __longest_consecutive(diff)\n total = len(diff)\n return str(longest), str(total), str(len(full_length))\n\n\ndef __create_model(root):\n dict_spotfeatures = [\n {\n \"feature\": \"QUALITY\",\n \"name\": \"Quality\",\n \"shortname\": \"Quality\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"POSITION_X\",\n \"name\": \"X\",\n \"shortname\": \"X\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"POSITION_Y\",\n \"name\": \"Y\",\n \"shortname\": \"Y\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"POSITION_Z\",\n \"name\": \"Z\",\n \"shortname\": \"Z\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"POSITION_T\",\n \"name\": \"T\",\n \"shortname\": \"T\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"FRAME\",\n \"name\": \"Frame\",\n \"shortname\": \"Frame\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"RADIUS\",\n \"name\": \"Radius\",\n \"shortname\": \"R\",\n \"dimension\": \"LENGTH\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"VISIBILITY\",\n \"name\": \"Visibility\",\n \"shortname\": \"Visibility\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"MANUAL_COLOR\",\n \"name\": \"Manual spot color\",\n \"shortname\": \"Spot color\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"MEAN_INTENSITY\",\n \"name\": \"Mean intensity\",\n \"shortname\": \"Mean\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"MEDIAN_INTENSITY\",\n \"name\": \"Median intensity\",\n \"shortname\": \"Median\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"MIN_INTENSITY\",\n \"name\": \"Minimal intensity\",\n \"shortname\": \"Min\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"MAX_INTENSITY\",\n \"name\": \"Maximal intensity\",\n \"shortname\": \"Max\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TOTAL_INTENSITY\",\n \"name\": \"Total intensity\",\n \"shortname\": \"Total int.\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"STANDARD_DEVIATION\",\n \"name\": \"Standard deviation\",\n \"shortname\": \"Stdev.\",\n \"dimension\": \"INTENSITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"ESTIMATED_DIAMETER\",\n \"name\": \"Estimated diameter\",\n \"shortname\": \"Diam.\",\n \"dimension\": \"LENGTH\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"CONTRAST\",\n \"name\": \"Contrast\",\n \"shortname\": \"Constrast\",\n \"dimension\": \"NONE\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"SNR\",\n \"name\": \"Signal/Noise, ratio\",\n \"shortname\": \"SNR\",\n \"dimension\": \"NONE\",\n \"isint\": \"false\",\n },\n ]\n\n dict_edgefeatures = [\n {\n \"feature\": \"SPOT_SOURCE_ID\",\n \"name\": \"Source spot ID\",\n \"shortname\": \"Source ID\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"SPOT_TARGET_ID\",\n \"name\": \"Target spot ID\",\n \"shortname\": \"Target ID\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"LINK_COST\",\n \"name\": \"Link cost\",\n \"shortname\": \"Cost\",\n \"dimension\": \"NONE\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"EDGE_TIME\",\n \"name\": \"Time (mean)\",\n \"shortname\": \"T\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"EDGE_X_LOCATION\",\n \"name\": \"X Location (mean)\",\n \"shortname\": \"X\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"EDGE_Y_LOCATION\",\n \"name\": \"Y Location (mean)\",\n \"shortname\": \"Y\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"EDGE_Z_LOCATION\",\n \"name\": \"Z Location (mean)\",\n \"shortname\": \"Z\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"VELOCITY\",\n \"name\": \"Velocity\",\n \"shortname\": \"V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"DISPLACEMENT\",\n \"name\": \"Displacement\",\n \"shortname\": \"D\",\n \"dimension\": \"LENGTH\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"MANUAL_COLOR\",\n \"name\": \"Manual edge color\",\n \"shortname\": \"Edge color\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n ]\n\n dict_trackfeatures = [\n {\n \"feature\": \"NUMBER_SPOTS\",\n \"name\": \"Number of spots in track\",\n \"shortname\": \"N spots\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"NUMBER_GAPS\",\n \"name\": \"Number of gaps\",\n \"shortname\": \"Gaps\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"LONGEST_GAP\",\n \"name\": \"Longest gap\",\n \"shortname\": \"Longest gap\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"NUMBER_SPLITS\",\n \"name\": \"Number of split events\",\n \"shortname\": \"Splits\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"NUMBER_MERGES\",\n \"name\": \"Number of merge events\",\n \"shortname\": \"Merges\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"NUMBER_COMPLEX\",\n \"name\": \"Complex points\",\n \"shortname\": \"Complex\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"TRACK_DURATION\",\n \"name\": \"Duration of track\",\n \"shortname\": \"Duration\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_START\",\n \"name\": \"Track start\",\n \"shortname\": \"T start\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_STOP\",\n \"name\": \"Track stop\",\n \"shortname\": \"T stop\",\n \"dimension\": \"TIME\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_DISPLACEMENT\",\n \"name\": \"Track displacement\",\n \"shortname\": \"Displacement\",\n \"dimension\": \"LENGTH\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_INDEX\",\n \"name\": \"Track index\",\n \"shortname\": \"Index\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"TRACK_ID\",\n \"name\": \"Track ID\",\n \"shortname\": \"ID\",\n \"dimension\": \"NONE\",\n \"isint\": \"true\",\n },\n {\n \"feature\": \"TRACK_X_LOCATION\",\n \"name\": \"X Location (mean)\",\n \"shortname\": \"X\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_Y_LOCATION\",\n \"name\": \"Y Location (mean)\",\n \"shortname\": \"Y\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_Z_LOCATION\",\n \"name\": \"Z Location (mean)\",\n \"shortname\": \"Z\",\n \"dimension\": \"POSITION\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MEAN_SPEED\",\n \"name\": \"Mean velocity\",\n \"shortname\": \"Mean V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MAX_SPEED\",\n \"name\": \"Maximal velocity\",\n \"shortname\": \"Max V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MIN_SPEED\",\n \"name\": \"Minimal velocity\",\n \"shortname\": \"Min V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MEDIAN_SPEED\",\n \"name\": \"Median velocity\",\n \"shortname\": \"Median V\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_STD_SPEED\",\n \"name\": \"Velocity standard deviation\",\n \"shortname\": \"V std\",\n \"dimension\": \"VELOCITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MEAN_QUALITY\",\n \"name\": \"Mean quality\",\n \"shortname\": \"Mean Q\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MAX_QUALITY\",\n \"name\": \"Maximal quality\",\n \"shortname\": \"Max Q\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MIN_QUALITY\",\n \"name\": \"Minimal quality\",\n \"shortname\": \"Min Q\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_MEDIAN_QUALITY\",\n \"name\": \"Median quality\",\n \"shortname\": \"Median Q\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n {\n \"feature\": \"TRACK_STD_QUALITY\",\n \"name\": \"Quality standard deviation\",\n \"shortname\": \"Q std\",\n \"dimension\": \"QUALITY\",\n \"isint\": \"false\",\n },\n ]\n # Model\n model = ET.SubElement(root, \"Model\", spatialunits=\"pixel\", timeunits=\"frame\")\n featuredeclarations = ET.SubElement(model, \"FeatureDeclarations\")\n\n # SpotFeatures\n spotfeatures = ET.SubElement(featuredeclarations, \"SpotFeatures\")\n for dct in dict_spotfeatures:\n _ = ET.SubElement(spotfeatures, \"Feature\", **dct)\n\n # Edgefeatures\n edgefeatures = ET.SubElement(featuredeclarations, \"EdgeFeatures\")\n for dct in dict_edgefeatures:\n _ = ET.SubElement(edgefeatures, \"Feature\", **dct)\n\n # TrackFeatures\n trackfeatures = ET.SubElement(featuredeclarations, \"TrackFeatures\")\n for dct in dict_trackfeatures:\n _ = ET.SubElement(trackfeatures, \"Feature\", **dct)\n\n return model\n\n\ndef __create_allspots(model, df):\n # List of all spots (without tracks)\n allspots = ET.SubElement(model, \"AllSpots\", nspots=str(len(df)))\n for frame in df[\"frame\"].unique():\n frame_id = str(float(frame))\n df_frame = df[df[\"frame\"] == frame]\n spotsinframe = ET.SubElement(allspots, \"SpotsInFrame\", frame=str(frame))\n for row in df_frame.iterrows():\n try:\n size = str(row[1][\"size\"] * 2)\n except KeyError:\n size = \"1.0\"\n dict_spot = {\n \"ID\": f\"{row[0]:06}\",\n \"name\": f\"ID{row[0]:06}\",\n \"QUALITY\": \"1.0\",\n \"POSITION_T\": frame_id,\n \"MAX_INTENSITY\": \"1.0\",\n \"FRAME\": frame_id,\n \"MEDIAN_INTENSITY\": \"1.0\",\n \"VISIBILITY\": \"1\",\n \"MEAN_INTENSITY\": \"1.0\",\n \"TOTAL_INTENSITY\": \"1.0\",\n \"ESTIMATED_DIAMETER\": size,\n \"RADIUS\": \"1.0\",\n \"SNR\": \"1.0\",\n \"POSITION_X\": str(row[1][\"x\"]),\n \"POSITION_Y\": str(row[1][\"y\"]),\n \"STANDARD_DEVIATION\": \"1.0\",\n \"CONTRAST\": \"1.0\",\n \"MANUAL_COLOR\": \"-10921639\",\n \"MIN_INTENSITY\": \"0.0\",\n \"POSITION_Z\": \"0.0\",\n }\n _ = ET.SubElement(spotsinframe, \"Spot\", **dict_spot)\n\n\ndef __create_alltracks(model, df):\n # List of all tracks\n alltracks = ET.SubElement(model, \"AllTracks\")\n for particle in df[\"particle\"].unique():\n df_track = df[df[\"particle\"] == particle]\n track_ids = list(df_track.index)\n frames = np.array(df_track[\"frame\"])\n longest, total, duration = get_gaps(frames)\n dict_track = {\n \"name\": f\"Track_{particle}\",\n \"TRACK_ID\": str(particle),\n \"NUMBER_SPOTS\": str(len(frames)),\n \"NUMBER_GAPS\": longest,\n \"LONGEST_GAP\": total,\n \"NUMBER_SPLITS\": \"0\",\n \"NUMBER_MERGES\": \"0\",\n \"NUMBER_COMPLEX\": \"0\",\n \"TRACK_DURATION\": duration,\n \"TRACK_START\": str(min(frames)),\n \"TRACK_STOP\": str(max(frames)),\n \"TRACK_DISPLACEMENT\": \"0.01\",\n \"TRACK_INDEX\": str(particle),\n \"TRACK_X_LOCATION\": str(df_track[\"x\"].mean()),\n \"TRACK_Y_LOCATION\": str(df_track[\"y\"].mean()),\n \"TRACK_Z_LOCATION\": \"0.1\",\n \"TRACK_MEAN_SPEED\": \"0.1\",\n \"TRACK_MAX_SPEED\": \"0.1\",\n \"TRACK_MIN_SPEED\": \"0.1\",\n \"TRACK_MEDIAN_SPEED\": \"0.1\",\n \"TRACK_STD_SPEED\": \"0.1\",\n \"TRACK_MEAN_QUALITY\": \"0.1\",\n \"TRACK_MAX_QUALITY\": \"0.1\",\n \"TRACK_MIN_QUALITY\": \"0.1\",\n \"TRACK_MEDIAN_QUALITY\": \"0.1\",\n \"TRACK_STD_QUALITY\": \"0.1\",\n }\n track = ET.SubElement(alltracks, \"Track\", **dict_track)\n\n # Add all spots in the corresponding track\n for row in df_track.iterrows():\n dict_edge = {\n \"SPOT_SOURCE_ID\": f\"{row[0]:06}\",\n \"SPOT_TARGET_ID\": f\"{track_ids[track_ids.index(row[0]) - 1]:06}\",\n \"LINK_COST\": \"0.1\",\n \"EDGE_TIME\": \"0.1\",\n \"EDGE_X_LOCATION\": str(row[1][\"x\"]),\n \"EDGE_Y_LOCATION\": str(row[1][\"y\"]),\n \"EDGE_Z_LOCATION\": \"0.0\",\n \"VELOCITY\": \"0.1\",\n \"DISPLACEMENT\": \"0.1\",\n }\n _ = ET.SubElement(track, \"Edge\", **dict_edge)\n\n\ndef __create_filteredtracks(model, df):\n # Tracks after TrackMate's filtering\n filteredtracks = ET.SubElement(model, \"FilteredTracks\")\n for particle in df[\"particle\"].unique():\n _ = ET.SubElement(filteredtracks, \"TrackID\", TRACK_ID=str(particle))\n\n\ndef __create_settings(root, file_image):\n # Image metadata\n path, fname = os.path.split(file_image)\n image = skimage.io.imread(file_image)\n frames, width, height = sorted(image.shape)\n imagedata = {\n \"filename\": fname,\n \"folder\": path,\n \"width\": str(width),\n \"height\": str(height),\n \"nslices\": \"1\",\n \"nframes\": str(frames),\n \"pixelwidth\": \"1.0\",\n \"pixelheight\": \"1.0\",\n \"voxeldepth\": \"1.0\",\n \"timeinterval\": \"1.0\",\n }\n basicsettings = {\n \"xstart\": \"0\",\n \"xend\": str(width - 1),\n \"ystart\": \"0\",\n \"yend\": str(height - 1),\n \"zstart\": \"0\",\n \"zend\": \"0\",\n \"tstart\": \"0\",\n \"tend\": str(frames - 1),\n }\n detectorsettings = {\n \"DETECTOR_NAME\": \"LOG_DETECTOR\",\n \"TARGET_CHANNEL\": \"1\",\n \"RADIUS\": \"0.05\",\n \"THRESHOLD\": \"150.0\",\n \"DO_MEDIAN_FILTERING\": \"false\",\n \"DO_SUBPIXEL_LOCALIZATION\": \"true\",\n }\n initialspotfilter = {\"feature\": \"QUALITY\", \"value\": \"0.0\", \"isabove\": \"true\"}\n dict_trackersettings = {\n \"TRACKER_NAME\": \"SIMPLE_SPARSE_LAP_TRACKER\",\n \"CUTOFF_PERCENTILE\": \"0.9\",\n \"ALTERNATIVE_LINKING_COST_FACTOR\": \"1.05\",\n \"BLOCKING_VALUE\": \"Infinity\",\n }\n dict_subtrackersettings = {\n \"Linking\": {\"LINKING_MAX_DISTANCE\": \"0.5\"},\n \"GapClosing\": {\n \"ALLOW_GAP_CLOSING\": \"true\",\n \"GAP_CLOSING_MAX_DISTANCE\": \"0.5\",\n \"MAX_FRAME_GAP\": \"3\",\n },\n \"TrackSplitting\": {\n \"ALLOW_TRACK_SPLITTING\": \"false\",\n \"SPLITTING_MAX_DISTANCE\": \"15.0\",\n },\n \"TrackMerging\": {\n \"ALLOW_TRACK_MERGING\": \"false\",\n \"MERGING_MAX_DISTANCE\": \"15.0\",\n },\n }\n dict_analyzercollection = {\n \"SpotAnalyzers\": [\n \"MANUAL_SPOT_COLOR_ANALYZER\",\n \"Spot descriptive statistics\",\n \"Spot radius estimator\",\n \"Spot contrast and SNR\",\n ],\n \"EdgeAnalyzers\": [\n \"Edge target\",\n \"Edge mean location\",\n \"Edge velocity\",\n \"MANUAL_EDGE_COLOR_ANALYZER\",\n ],\n \"TrackAnalyzers\": [\n \"Branching analyzer\",\n \"Track duration\",\n \"Track index\",\n \"Track location\",\n \"Velocity\",\n \"TRACK_SPOT_QUALITY\",\n ],\n }\n\n # General Settings\n settings = ET.SubElement(root, \"Settings\")\n _ = ET.SubElement(settings, \"ImageData\", **imagedata)\n _ = ET.SubElement(settings, \"BasicSettings\", **basicsettings)\n _ = ET.SubElement(settings, \"DetectorSettings\", **detectorsettings)\n _ = ET.SubElement(settings, \"InitialSpotFilter\", **initialspotfilter)\n _ = ET.SubElement(settings, \"SpotFilterCollection\")\n\n # Tracker settings\n trackersettings = ET.SubElement(settings, \"TrackerSettings\", **dict_trackersettings)\n for k, v in dict_subtrackersettings.items():\n subelement = ET.SubElement(trackersettings, k, **v)\n _ = ET.SubElement(subelement, \"FeaturePenalties\")\n\n # Filter settings\n _ = ET.SubElement(settings, \"TrackFilterCollection\")\n analyzercollection = ET.SubElement(settings, \"AnalyzerCollection\")\n for k, v in dict_analyzercollection.items():\n subanalyzer = ET.SubElement(analyzercollection, k)\n for lst in v:\n _ = ET.SubElement(subanalyzer, \"Analyzer\", key=lst)\n\n\ndef __create_guistate(root):\n # TrackMate's GUI settings\n guistate = ET.SubElement(root, \"GUIState\", state=\"FilterTracks\")\n for _ in range(4):\n _ = ET.SubElement(guistate, \"View\", key=\"HYPERSTACKDISPLAYER\")\n\n\ndef __pretty_output(root, file_output):\n # Save file after fancy formatting to prettify\n with tempfile.TemporaryDirectory() as tempdirname:\n fname = os.path.join(tempdirname, \"file.xml\")\n tree = ET.ElementTree(root)\n tree.write(fname, encoding=\"UTF-8\", xml_declaration=True)\n dom = xml.dom.minidom.parse(fname)\n pretty_xml = dom.toprettyxml()\n\n with open(file_output, \"w\") as f:\n f.write(pretty_xml)\n\n\ndef create_trackmate_xml(file_tracks, file_image, file_output):\n # Check required track df columns\n df = pd.read_csv(file_tracks)\n req_cols = [\"x\", \"y\", \"frame\", \"particle\"]\n if not all(req in df.columns for req in req_cols):\n raise ValueError(f\"Not all required columns present! {req_cols} must exist.\")\n\n # XML tree\n root = ET.Element(\"TrackMate\", version=\"6.0.1\")\n\n # Model\n model = __create_model(root)\n __create_allspots(model, df)\n __create_alltracks(model, df)\n __create_filteredtracks(model, df)\n\n # Settings\n __create_settings(root, file_image)\n __create_guistate(root)\n\n # Save output\n __pretty_output(root, file_output)\n\n\ndef main():\n parser = argparse.ArgumentParser(\n prog=\"trackmate\",\n usage=(\n \"python trackmate.py --image image.tif --tracks tracks.csv \"\n \"--output outfile.xml\"\n ),\n description=__doc__,\n formatter_class=argparse.RawTextHelpFormatter,\n add_help=True,\n )\n parser.add_argument(\n \"-i\",\n \"--image\",\n type=str,\n required=False,\n help=\"Path to the input image for which tracks were created.\",\n )\n parser.add_argument(\n \"-t\",\n \"--tracks\",\n type=str,\n required=False,\n help=\"Path to the csv track file. See helptext for formating guidelines.\",\n )\n parser.add_argument(\n \"-o\",\n \"--output\",\n type=str,\n required=False,\n default=\"trackmate.xml\",\n help=\"Custom trackmate xml file output name [default: trackmate.xml]\",\n )\n parser._optionals.title = \"Arguments\"\n args = parser.parse_args()\n\n if (args.image is None) or (args.tracks is None):\n parser.print_help()\n else:\n create_trackmate_xml(\n file_image=args.image,\n file_tracks=args.tracks,\n file_output=args.output,\n )\n\n\nif __name__ == \"__main__\":\n main()\n"
]
| [
[
"numpy.array",
"pandas.read_csv",
"numpy.setdiff1d"
]
]
|
thanhtruongnhu/hello-world | [
"5fa3fc43064021daa7811e1a6eb7ea7e3b778416"
]
| [
"convertCoordinateRB1.py"
]
| [
"from picamera.array import PiRGBArray\nfrom picamera import PiCamera\nimport time\nimport cv2\nimport numpy as np\nimport time\nimport serial\nimport math\n# global variables \n\n# rf send\n\nser = serial.Serial(\n\tport = '/dev/ttyAMA0',\n\tbaudrate = 9600,\n\tparity = serial.PARITY_NONE,\n\tstopbits = serial.STOPBITS_ONE,\n\tbytesize = serial.EIGHTBITS,\n\ttimeout = 1\n)\n\n\n\n\n# function convert RGB value to HSV value\n\ndef convertHSV(G,R,B):\n colorBGR = np.uint8([[[B,G,R]]])\n colorHSV = cv2.cvtColor(colorBGR,cv2.COLOR_BGR2HSV)\n H_value = colorHSV[:,0,0]\n a= int(H_value)\n return a\n\n\n\n\n#function standardixed coordinate axis 2D image coordinate to 3D world coordinate with Z=1\n\ndef findCoordinate_rb1():\n coordinate = []\n hsv = cv2.cvtColor(image,cv2.COLOR_BGR2HSV)\n res1 = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)\n if x>10:\n up_yellow1 = np.array([x-10,100,100] ) \n under_yellow1 = np.array([x+10,255,255])\n else:\n \n up_yellow1 = np.array([0,100,100] ) \n under_yellow1 = np.array([x+10,255,255])\n mask1 = cv2. inRange(hsv,up_yellow1,under_yellow1)\n\n kernel = np.ones((5,5),np.uint8)\n mask = cv2.morphologyEx(mask1,cv2.MORPH_OPEN,kernel)\n mask = cv2.morphologyEx(mask,cv2.MORPH_OPEN,kernel)\n\n ret = cv2.findContours(mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]\n \n \n if len(ret) > 0:\n c = ret[0]\n ((x,y),R) = cv2.minEnclosingCircle(c)\n M = cv2.moments(c)\n x = int (M['m10']/M['m00'])\n y = int (M['m01']/M['m00'])\n R = int(R)\n coordinate.append(x)\n coordinate.append(y)\n coordinate.append(R)\n else:\n coordinate = None\n return coordinate\n\n\n\n#calibration\nmyfile = np.load('calib.npz')\nmtx = myfile['mtx']\ndist = myfile['dist']\nnewmtx = myfile['newcameramtx']\n\n# Stream video from module Pi camera\ncamera = PiCamera()\ncamera.resolution = (320,240)\ncamera.framerate = 40\nrawCapture = PiRGBArray(camera,size=(320,240))\n\ntime.sleep(1)\n\nfor frame in camera.capture_continuous(rawCapture,format = 'bgr',use_video_port=True):\n #start = time.time()\n img = frame.array\n h, w = img.shape[:2]\n newcameramtx, roi=cv2.getOptimalNewCameraMatrix(mtx,dist,(w,h),1,(w,h))\n img = cv2.undistort(img,mtx,dist,None,newcameramtx)\n #time.sleep(1)\n x,y,h,w = roi\n img = img[y:y+w,x:x+h]\n hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)\n#rb_1\n \n up_yellow1 = np.array([0,100,100] ) \n under_yellow1 = np.array([20,255,255])\n mask1 = cv2. inRange(hsv,up_yellow1,under_yellow1)\n\n kernel = np.ones((5,5),np.uint8)\n mask_rb1 = cv2.morphologyEx(mask1,cv2.MORPH_OPEN,kernel)\n mask_rb1 = cv2.morphologyEx(mask_rb1,cv2.MORPH_OPEN,kernel)\n\n ret1 = cv2.findContours(mask_rb1,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]\n\n if (len(ret1) > 0):\n c_1 = ret1[0]\n #rb1\n ((x_1,y_1),R_1) = cv2.minEnclosingCircle(c_1)\n M = cv2.moments(c_1)\n x_1 = int (M['m10']/M['m00'])\n y_1 = int (M['m01']/M['m00'])\n center1 = (x_1,y_1)\n R_1 = int(R_1)\n\n\n# process on map\n if ((x_1 >= 33 and y_1 >= 16)):\n x_world1 = (x_1 - 33)*(200/28)\n y_world1 = (y_1 - 16)*(200/28)\n #print (int(x_world1),int(y_world1))\n '''\n if R>10:\n cv2.circle(img,center,R,(255,0,0),2)\n cv2.putText(img,\"(\"+str(x_world)+\",\"+str(y_world)+\")\",(x,y),cv2.FONT_HERSHEY_SIMPLEX,0.4,(0,0,255),1)\n '''\n#process coordinate rb1\n canny_rb1 = c_1[:,:,0]\n #print a\n max_a1 = []\n for i in range (0,len(canny_rb1)):\n k_1 = math.pow((int(c_1[i,:,0])-x_1),2) + math.pow((int(c_1[i,:,1])-y_1),2)\n max_a1.append(k_1)\n j_1 = max_a1.index(max(max_a1))\n x_max1 = int (c_1[j_1,:,0])\n y_max1 = int (c_1[j_1,:,1])\n #print (x_max1,y_max1)\n u_1 = np.array([x_max1 - x_1, y_max1 - y_1])\n v_1 = np.array([1,0])\n u_value1 = math.sqrt(math.pow(u_1[0],2) + math.pow(u_1[1],2))\n v_value1 = 1\n rad = math.acos(np.sum(u_1*v_1) / (u_value1*v_value1))\n if (y_max1 >= y_1):\n Angle1 = math.degrees(rad)\n if (y_max1 < y_1):\n Angle1 = 360 - math.degrees(rad)\n print (Angle1)\n\n if R_1>1:\n cv2.circle(img,center1,2,(255,255,255),2)\n cv2.circle(img,(x_max1,y_max1),2,(255,255,255),2)\n #cv2.putText(img,\"(\"+str(x_1)+\",\"+str(y_1)+\")\",(x_1,y_1),cv2.FONT_HERSHEY_SIMPLEX,0.4,(255,255,255),1)\n \n else:\n cv2.imshow('frame',img) \n \n\n# RF send\n \n byte_0 = int (255) #Start Byte\n # current position\n byte_1 = int (x_world1)// 254 #Transfer the Quotient \n byte_2 = int (x_world1)% 254 #Transfer the Remainder \n byte_3 = int (y_world1)// 254 #Transfer the Quotient \n byte_4 = int (y_world1)% 254 #Transfer the Remainder \n # target positon\n # current angle\n byte_5 = int (Angle1)// 254\n byte_6 = int (Angle1)% 254\n byte_7 = int (255) #Stop Byte\n #list1=[byte_0]\n list1=[byte_0,byte_1,byte_2,byte_3,byte_4,byte_5,byte_6,byte_7]\n #cv2.imshow('frame',img)\n\t\n ser.write(list1)\n #stop = time.time()\n #print (stop - start)\n ser.flush()\n #print(list1)\n #time.sleep(0.25)\n\n\n cv2.imshow('frame',img)\n key = cv2.waitKey(1)\n\n rawCapture.truncate(0)\n if key == ord(\"q\"):\n ser.close()\n cv2.destroyAllWindows()\n break\n\n\n\n"
]
| [
[
"numpy.uint8",
"numpy.ones",
"numpy.load",
"numpy.array",
"numpy.sum"
]
]
|
songanz/fusion | [
"fe3389dd92938ea58b2b78068552da13972a51cb"
]
| [
"Frustum-PointNet/eval_frustum_pointnet_val_2ddetections.py"
]
| [
"# camera-ready\n\nfrom datasets import DatasetKittiVal2ddetections, wrapToPi, getBinCenter # (this needs to be imported before torch, because cv2 needs to be imported before torch for some reason)\nfrom frustum_pointnet import FrustumPointNet\n\nimport torch\nimport torch.utils.data\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.optim as optim\nimport torch.nn.functional as F\n\nimport numpy as np\nimport pickle\n\nbatch_size = 32\nroot_dir = \"/home/songanz/Documents/Git_repo/fusion/\" # change this for your own usage\nnetwork = FrustumPointNet(\"Frustum-PointNet_eval_val_2ddetections\", project_dir=root_dir)\nnetwork.load_state_dict(torch.load(root_dir + \"pretrained_models/model_37_2_epoch_400.pth\"))\nnetwork = network.cuda()\n\nNH = network.BboxNet_network.NH\n\nval_dataset = DatasetKittiVal2ddetections(kitti_data_path=root_dir + \"data/kitti\",\n kitti_meta_path=root_dir + \"data/kitti/meta\",\n NH=NH)\n\nnum_val_batches = int(len(val_dataset)/batch_size)\n\nval_loader = torch.utils.data.DataLoader(dataset=val_dataset,\n batch_size=batch_size, shuffle=False,\n num_workers=16)\n\nnetwork.eval() # (set in evaluation mode, this affects BatchNorm and dropout)\neval_dict = {}\nfor step, (frustum_point_clouds, img_ids, input_2Dbboxes, frustum_Rs, frustum_angles, empty_frustum_flags, centered_frustum_mean_xyz, mean_car_size, scores_2d) in enumerate(val_loader):\n if step % 100 == 0:\n print (\"step: %d/%d\" % (step+1, num_val_batches))\n\n with torch.no_grad(): # (corresponds to setting volatile=True in all variables, this is done during inference to reduce memory consumption)\n frustum_point_clouds = Variable(frustum_point_clouds) # (shape: (batch_size, num_points, 4))\n frustum_point_clouds = frustum_point_clouds.transpose(2, 1) # (shape: (batch_size, 4, num_points))\n\n frustum_point_clouds = frustum_point_clouds.cuda()\n\n outputs = network(frustum_point_clouds)\n outputs_InstanceSeg = outputs[0] # (shape: (batch_size, num_points, 2))\n outputs_TNet = outputs[1] # (shape: (batch_size, 3))\n outputs_BboxNet = outputs[2] # (shape: (batch_size, 3 + 3 + 2*NH))\n seg_point_clouds_mean = outputs[3] # (shape: (batch_size, 3))\n dont_care_mask = outputs[4] # (shape: (batch_size, ))\n\n ############################################################################\n # save data for visualization:\n ############################################################################\n centered_frustum_mean_xyz = centered_frustum_mean_xyz[0].numpy()\n mean_car_size = mean_car_size[0].numpy()\n for i in range(outputs_InstanceSeg.size()[0]):\n dont_care_mask_value = dont_care_mask[i]\n empty_frustum_flag = empty_frustum_flags[i]\n\n # don't care about predicted 3Dbboxes that corresponds to empty\n # point clouds outputted by InstanceSeg, or empty input frustums:\n if dont_care_mask_value == 1 and empty_frustum_flag == 0:\n pred_InstanceSeg = outputs_InstanceSeg[i].data.cpu().numpy() # (shape: (num_points, 2))\n frustum_point_cloud = frustum_point_clouds[i].transpose(1, 0).data.cpu().numpy() # (shape: (num_points, 4))\n seg_point_cloud_mean = seg_point_clouds_mean[i].data.cpu().numpy() # (shape: (3, ))\n img_id = img_ids[i]\n input_2Dbbox = input_2Dbboxes[i] # (shape: (4, ))\n frustum_R = frustum_Rs[i] # (shape: (3, 3))\n frustum_angle = frustum_angles[i]\n score_2d = scores_2d[i]\n\n unshifted_frustum_point_cloud_xyz = frustum_point_cloud[:, 0:3] + centered_frustum_mean_xyz\n decentered_frustum_point_cloud_xyz = np.dot(np.linalg.inv(frustum_R), unshifted_frustum_point_cloud_xyz.T).T\n frustum_point_cloud[:, 0:3] = decentered_frustum_point_cloud_xyz\n\n row_mask = pred_InstanceSeg[:, 1] > pred_InstanceSeg[:, 0]\n pred_seg_point_cloud = frustum_point_cloud[row_mask, :]\n\n pred_center_TNet = np.dot(np.linalg.inv(frustum_R), outputs_TNet[i].data.cpu().numpy() + centered_frustum_mean_xyz + seg_point_cloud_mean) # (shape: (3, )) # NOTE!\n centroid = seg_point_cloud_mean\n\n pred_center_BboxNet = np.dot(np.linalg.inv(frustum_R), outputs_BboxNet[i][0:3].data.cpu().numpy() + centered_frustum_mean_xyz + seg_point_cloud_mean + outputs_TNet[i].data.cpu().numpy()) # (shape: (3, )) # NOTE!\n\n pred_h = outputs_BboxNet[i][3].data.cpu().numpy() + mean_car_size[0]\n pred_w = outputs_BboxNet[i][4].data.cpu().numpy() + mean_car_size[1]\n pred_l = outputs_BboxNet[i][5].data.cpu().numpy() + mean_car_size[2]\n\n pred_bin_scores = outputs_BboxNet[i][6:(6+4)].data.cpu().numpy() # (shape (NH=8, ))\n pred_residuals = outputs_BboxNet[i][(6+4):].data.cpu().numpy() # (shape (NH=8, ))\n pred_bin_number = np.argmax(pred_bin_scores)\n pred_bin_center = getBinCenter(pred_bin_number, NH=NH)\n pred_residual = pred_residuals[pred_bin_number]\n pred_centered_r_y = pred_bin_center + pred_residual\n pred_r_y = wrapToPi(pred_centered_r_y + frustum_angle) # NOTE!\n\n pred_r_y = pred_r_y.data.cpu().numpy()\n input_2Dbbox = input_2Dbbox.data.cpu().numpy()\n score_2d = score_2d.cpu().numpy()\n\n if img_id not in eval_dict:\n eval_dict[img_id] = []\n\n bbox_dict = {}\n bbox_dict[\"pred_center_TNet\"] = pred_center_TNet\n bbox_dict[\"pred_center_BboxNet\"] = pred_center_BboxNet\n bbox_dict[\"centroid\"] = centroid\n bbox_dict[\"pred_h\"] = pred_h\n bbox_dict[\"pred_w\"] = pred_w\n bbox_dict[\"pred_l\"] = pred_l\n bbox_dict[\"pred_r_y\"] = pred_r_y\n bbox_dict[\"input_2Dbbox\"] = input_2Dbbox\n bbox_dict[\"score_2d\"] = score_2d\n\n eval_dict[img_id].append(bbox_dict)\n\nwith open(\"%s/eval_dict_val_2ddetections.pkl\" % network.model_dir, \"wb\") as file:\n pickle.dump(eval_dict, file, protocol=2) # (protocol=2 is needed to be able to open this file with python2)\n"
]
| [
[
"torch.load",
"numpy.linalg.inv",
"torch.utils.data.DataLoader",
"numpy.argmax",
"torch.no_grad",
"torch.autograd.Variable"
]
]
|
Jxtopher/python-image-manipulation | [
"a4b527f36162afe020acbb4ad5784ab1c84b1dac"
]
| [
"sources/sierpinski_triangle.py"
]
| [
"from typing import List\nfrom PIL import Image\nfrom copy import deepcopy\nimport numpy as np\n\n\ndef apply_rules(rules: List[dict], line: List, new_line: List, num_case: int) -> None:\n for rule in rules:\n if (\n rule[\"pattern\"][0] == line[num_case - 1]\n and rule[\"pattern\"][1] == line[num_case]\n and rule[\"pattern\"][2] == line[num_case + 1]\n ):\n new_line[num_case] = rule[\"new_state\"]\n break\n\n\nif __name__ == \"__main__\":\n rules_num_90 = [\n {\"pattern\": [1, 1, 1], \"new_state\": 0},\n {\"pattern\": [1, 1, 0], \"new_state\": 1},\n {\"pattern\": [1, 0, 1], \"new_state\": 0},\n {\"pattern\": [1, 0, 0], \"new_state\": 1},\n {\"pattern\": [0, 1, 1], \"new_state\": 1},\n {\"pattern\": [0, 1, 0], \"new_state\": 0},\n {\"pattern\": [0, 0, 1], \"new_state\": 1},\n {\"pattern\": [0, 0, 0], \"new_state\": 0},\n ]\n\n color = {\n \"red\": (255, 0, 0),\n \"white\": (255, 255, 255),\n \"black\": (0, 0, 0),\n \"aero_blue\": (202, 241, 222),\n \"picton_blue\": (75, 177, 249),\n \"amber\": (255, 125, 3),\n \"catalina_blue\": (0, 51, 119),\n \"papaya_whip\": (254, 243, 215),\n }\n\n n = 500\n line_t0 = np.array([0] * n)\n line_t1 = np.array([0] * n)\n img = Image.new(\"RGB\", (n, n), color[\"picton_blue\"])\n\n line_t0[round(n / 2)] = 1\n\n for i in range(n):\n if line_t0[i] == 1:\n img.putpixel((i, 0), color[\"black\"])\n\n for num_line in range(1, n - 1):\n for i in range(1, n - 1):\n apply_rules(rules_num_90, line_t0, line_t1, i)\n\n for i in range(n):\n if line_t1[i] == 1:\n img.putpixel((i, num_line), color[\"black\"])\n\n line_t0 = deepcopy(line_t1)\n\n img.save(\"ret_images/sierpinski_triangle.png\")\n"
]
| [
[
"numpy.array"
]
]
|
sayanghosh/FLSim | [
"7b47c83c811070cf0f560ff74647fa47adc441be"
]
| [
"flsim/trainers/sync_trainer.py"
]
| [
"#!/usr/bin/env python3\n# Copyright (c) Meta Platforms, Inc. and affiliates.\n# All rights reserved.\n#\n# This source code is licensed under the BSD-style license found in the\n# LICENSE file in the root directory of this source tree.\n\nfrom __future__ import annotations\n\nimport logging\nimport math\nfrom dataclasses import dataclass\nfrom time import time\nfrom typing import Any, Dict, Iterable, List, Optional, Tuple\n\nimport torch\nfrom flsim.channels.message import Message\nfrom flsim.clients.base_client import Client\nfrom flsim.clients.dp_client import DPClientConfig, DPClient\nfrom flsim.common.timeline import Timeline\nfrom flsim.data.data_provider import IFLDataProvider\nfrom flsim.interfaces.metrics_reporter import IFLMetricsReporter, Metric, TrainingStage\nfrom flsim.interfaces.model import IFLModel\nfrom flsim.servers.sync_dp_servers import SyncDPSGDServerConfig\nfrom flsim.servers.sync_secagg_servers import SyncSecAggServerConfig\nfrom flsim.servers.sync_servers import (\n ISyncServer,\n SyncServerConfig,\n FedAvgOptimizerConfig,\n)\nfrom flsim.trainers.trainer_base import FLTrainer, FLTrainerConfig\nfrom flsim.utils.config_utils import fullclassname\nfrom flsim.utils.config_utils import init_self_cfg\nfrom flsim.utils.config_utils import is_target\nfrom flsim.utils.distributed.fl_distributed import FLDistributedUtils\nfrom flsim.utils.fl.common import FLModelParamUtils\nfrom flsim.utils.fl.stats import RandomVariableStatsTracker\nfrom hydra.utils import instantiate\nfrom omegaconf import OmegaConf\nfrom tqdm import tqdm\n\n\nclass SyncTrainer(FLTrainer):\n \"\"\"Implements FederatedAveraging: https://arxiv.org/abs/1602.05629\n\n Attributes:\n epochs (int): Training epochs\n report_train_metrics (bool): Whether metrics on training data should be\n computed and reported.\n \"\"\"\n\n def __init__(\n self,\n *,\n model: IFLModel,\n cuda_enabled: bool = False,\n **kwargs,\n ):\n init_self_cfg(\n self,\n component_class=__class__, # pyre-fixme[10]: Name `__class__` is used but not defined.\n config_class=SyncTrainerConfig,\n **kwargs,\n )\n\n super().__init__(model=model, cuda_enabled=cuda_enabled, **kwargs)\n self.server: ISyncServer = instantiate(\n # pyre-ignore[16]\n self.cfg.server,\n global_model=model,\n channel=self.channel,\n )\n self.clients = {}\n\n @classmethod\n def _set_defaults_in_cfg(cls, cfg):\n if OmegaConf.is_missing(cfg.server, \"_target_\"):\n cfg.server = SyncServerConfig(optimizer=FedAvgOptimizerConfig())\n\n def global_model(self) -> IFLModel:\n \"\"\"This function makes it explicit that self.global_model() is owned\n by the server, not by SyncTrainer\n \"\"\"\n return self.server.global_model\n\n @property\n def is_user_level_dp(self):\n return is_target(self.cfg.server, SyncDPSGDServerConfig)\n\n @property\n def is_sample_level_dp(self):\n return is_target(self.cfg.client, DPClientConfig)\n\n @property\n def is_secure_aggregation_enabled(self):\n return is_target(self.cfg.server, SyncSecAggServerConfig)\n\n def create_or_get_client_for_data(self, dataset_id: int, datasets: Any):\n \"\"\"This function is used to create clients in a round. Thus, it\n is called UPR * num_rounds times per training run. Here, we use\n <code>OmegaConf.structured</code> instead of <code>hydra.instantiate</code>\n to minimize the overhead of hydra object creation.\n \"\"\"\n if self.is_sample_level_dp:\n client = DPClient(\n # pyre-ignore[16]\n **OmegaConf.structured(self.cfg.client),\n dataset=datasets.get_train_user(dataset_id),\n name=f\"client_{dataset_id}\",\n timeout_simulator=self._timeout_simulator,\n store_last_updated_model=self.cfg.report_client_metrics,\n channel=self.channel,\n cuda_manager=self._cuda_state_manager,\n )\n else:\n client = Client(\n **OmegaConf.structured(self.cfg.client),\n dataset=datasets.get_train_user(dataset_id),\n name=f\"client_{dataset_id}\",\n timeout_simulator=self._timeout_simulator,\n store_last_updated_model=self.cfg.report_client_metrics,\n channel=self.channel,\n cuda_manager=self._cuda_state_manager,\n )\n self.clients[dataset_id] = client\n return self.clients[dataset_id]\n\n def train(\n self,\n data_provider: IFLDataProvider,\n metric_reporter: IFLMetricsReporter,\n num_total_users: int,\n distributed_world_size: int,\n rank: int = 0,\n ) -> Tuple[IFLModel, Any]:\n \"\"\"Train and eval a model, the model states will be modified. This function\n iterates over epochs specified in config, and for each epoch:\n\n 1. Trains model in a federated way: different models are trained over data\n from different users, and are averaged into 'model' at the end of epoch\n 2. Evaluate averaged model using evaluation data\n 3. Calculate metrics based on evaluation results and select best model\n\n Args:\n data_provider (IFLDataProvider): provide training, evaluation, and test data\n iterables and get a user's data based on user ID\n metric_reporter (IFLMetricsReporter): compute metric based on training\n output and report results to console, file, etc.\n num_total_users (int): number of total users for training\n\n Returns:\n model, best_metric: the trained model together with the best metric\n\n Note:\n one `epoch` = go over all users once is not True here\n since users in each round are selected randomly, this isn't precisely true\n we may go over some users more than once, and some users never\n however, as long as users_per_round << num_total_users, this will work\n the alternative is to keep track of all users that have already\n been selected in the current epoch - impractical and not worth it\n however, we may have that option in simulation later on.\n TODO correct note if above option added.\n \"\"\"\n # set up synchronization utilities for distributed training\n FLDistributedUtils.setup_distributed_training(\n distributed_world_size, use_cuda=self.cuda_enabled\n ) # TODO do not call distributed utils here, this is upstream responsibility\n self.logger.info(f\" dist world size = {distributed_world_size}\")\n\n if rank != 0:\n FLDistributedUtils.suppress_output()\n\n # pyre-fixme[16]: `SyncTrainer` has no attribute `cfg`.\n assert self.cfg.users_per_round % distributed_world_size == 0\n\n best_metric = None\n best_model_state = self.global_model().fl_get_module().state_dict()\n # last_best_epoch = 0\n users_per_round = min(self.cfg.users_per_round, num_total_users)\n\n self.data_provider = data_provider\n num_rounds_in_epoch = self.rounds_in_one_epoch(num_total_users, users_per_round)\n num_users_on_worker = data_provider.num_train_users()\n self.logger.debug(\n f\"num_users_on_worker: {num_users_on_worker}, \"\n f\"users_per_round: {users_per_round}, \"\n f\"num_total_users: {num_total_users}\"\n )\n # torch.multinomial requires int instead of float, cast it as int\n users_per_round_on_worker = int(users_per_round / distributed_world_size)\n self._validate_users_per_round(users_per_round_on_worker, num_users_on_worker)\n\n self.logger.info(\"Start training\")\n if self.logger.isEnabledFor(logging.DEBUG):\n norm = FLModelParamUtils.debug_model_norm(\n self.global_model().fl_get_module()\n )\n self.logger.debug(\n self.cuda_enabled and distributed_world_size > 1,\n f\"from worker {rank}: model norm is {norm} after round {iter}\",\n )\n\n # main training loop\n num_int_epochs = math.ceil(self.cfg.epochs)\n for epoch in tqdm(\n range(1, num_int_epochs + 1), desc=\"Epoch\", unit=\"epoch\", position=0\n ):\n for round in tqdm(\n range(1, num_rounds_in_epoch + 1),\n desc=\"Round\",\n unit=\"round\",\n position=0,\n ):\n timeline = Timeline(\n epoch=epoch, round=round, rounds_per_epoch=num_rounds_in_epoch\n )\n\n t = time()\n clients = self._client_selection(\n num_users_on_worker,\n users_per_round_on_worker,\n data_provider,\n self.global_model(),\n epoch,\n )\n self.logger.info(f\"Client Selection took: {time() - t} s.\")\n\n agg_metric_clients = self._choose_clients_for_post_aggregation_metrics(\n train_clients=clients,\n num_total_users=num_users_on_worker,\n users_per_round=users_per_round_on_worker,\n )\n\n # training on selected clients for the round\n self.logger.info(f\"# clients/round on worker {rank}: {len(clients)}.\")\n self._train_one_round(\n timeline=timeline,\n clients=clients,\n agg_metric_clients=agg_metric_clients,\n users_per_round=users_per_round,\n metric_reporter=metric_reporter\n if self.cfg.report_train_metrics\n else None,\n )\n\n if self.logger.isEnabledFor(logging.DEBUG):\n norm = FLModelParamUtils.debug_model_norm(\n self.global_model().fl_get_module()\n )\n self.logger.debug(\n self.cuda_enabled and distributed_world_size > 1,\n f\"from worker {rank}: model norm: {norm} @ \"\n f\"epoch:{epoch}, round:{round}\",\n )\n\n # report training success rate and training time variance\n if rank == 0:\n if (\n self._timeout_simulator.sample_mean_per_user != 0\n or self._timeout_simulator.sample_var_per_user != 0\n ):\n self.logger.info(\n f\"mean training time/user: \"\n f\"{self._timeout_simulator.sample_mean_per_user}\",\n f\"variance of training time/user: \"\n f\"{self._timeout_simulator.sample_var_per_user}\",\n )\n\n t = time()\n best_metric, best_model_state = self._maybe_run_evaluation(\n model=self.global_model(),\n timeline=timeline,\n data_provider=data_provider,\n metric_reporter=metric_reporter,\n best_metric=best_metric,\n best_model_state=best_model_state,\n )\n self.logger.info(f\"Evaluation took {time() - t} s.\")\n\n if self.stop_fl_training(\n epoch=epoch, round=round, num_rounds_in_epoch=num_rounds_in_epoch\n ):\n break\n\n # pyre-fixme[61]: `timeline` may not be initialized here.\n self._post_epoch_client_metrics_eval(timeline, metric_reporter)\n if self.stop_fl_training(\n epoch=epoch,\n round=round, # pyre-fixme[61]: `round` may not be initialized here.\n num_rounds_in_epoch=num_rounds_in_epoch,\n ):\n break\n\n if rank == 0 and best_metric is not None:\n self._save_model_and_metrics(self.global_model(), best_model_state)\n\n return self.global_model(), best_metric\n\n def _post_epoch_client_metrics_eval(\n self,\n timeline: Timeline,\n metric_reporter: IFLMetricsReporter,\n ):\n self._report_post_epoch_client_metrics(\n timeline=timeline,\n metric_reporter=metric_reporter,\n )\n\n def stop_fl_training(self, *, epoch, round, num_rounds_in_epoch) -> bool:\n # stop if necessary number of steps/epochs are completed in case of fractional epochs\n # or if client times out\n global_round_num = (epoch - 1) * num_rounds_in_epoch + round\n return (\n (global_round_num / num_rounds_in_epoch)\n >= self.cfg.epochs # pyre-fixme[16]: `SyncTrainer` has no attribute `cfg`.\n or self._timeout_simulator.stop_fl()\n )\n\n def _drop_overselected_users(\n self, clents_triggered: List[Client], num_users_keep: int\n ) -> List[Client]:\n \"\"\"\n sort users by their training time, and only keep num_users_keep users\n \"\"\"\n all_training_times = [c.get_total_training_time() for c in clents_triggered]\n all_training_times.sort()\n # only select first num_users_keep userids sort by their finish time\n num_users_keep = min([num_users_keep, len(all_training_times)])\n last_user_time = all_training_times[num_users_keep - 1]\n num_users_added = 0\n clients_used = []\n for c in clents_triggered:\n # if two clients finished at the same time, order for entering\n # the cohort is arbitrary\n if (c.get_total_training_time() <= last_user_time) and (\n num_users_added < num_users_keep\n ):\n num_users_added += 1\n clients_used.append(c)\n\n return clients_used\n\n def _client_selection(\n self,\n num_users: int,\n users_per_round: int,\n data_provider: IFLDataProvider,\n global_model: IFLModel,\n epoch: int,\n ) -> List[Client]:\n # pyre-fixme[16]: `SyncTrainer` has no attribute `cfg`.\n num_users_overselected = math.ceil(users_per_round / self.cfg.dropout_rate)\n user_indices_overselected = self.server.select_clients_for_training(\n num_total_users=num_users,\n users_per_round=num_users_overselected,\n data_provider=data_provider,\n epoch=epoch,\n )\n clients_triggered = [\n self.create_or_get_client_for_data(i, self.data_provider)\n for i in user_indices_overselected\n ]\n clients_to_train = self._drop_overselected_users(\n clients_triggered, users_per_round\n )\n return clients_to_train\n\n def _save_model_and_metrics(self, model: IFLModel, best_model_state):\n model.fl_get_module().load_state_dict(best_model_state)\n\n def _train_one_round(\n self,\n timeline: Timeline,\n clients: Iterable[Client],\n agg_metric_clients: Iterable[Client],\n users_per_round: int,\n metric_reporter: Optional[IFLMetricsReporter],\n ) -> None:\n \"\"\"Args:\n timeline: information about the round, epoch, round number, ...\n clients: clients for the round\n agg_metric_clients: clients for evaluating the post-aggregation training metrics\n metric_reporter: the metric reporter to pass to other methods\n \"\"\"\n t = time()\n self.server.init_round()\n self.logger.info(f\"Round initialization took {time() - t} s.\")\n\n def update(client):\n client_delta, weight = client.generate_local_update(\n self.global_model(), metric_reporter\n )\n self.server.receive_update_from_client(Message(client_delta, weight))\n\n t = time()\n for client in clients:\n update(client)\n self.logger.info(f\"Collecting round's clients took {time() - t} s.\")\n\n t = time()\n self.server.step()\n self.logger.info(f\"Finalizing round took {time() - t} s.\")\n\n t = time()\n self._report_train_metrics(\n model=self.global_model(),\n timeline=timeline,\n metric_reporter=metric_reporter,\n )\n self._evaluate_global_model_after_aggregation(\n clients=agg_metric_clients,\n model=self.global_model(),\n timeline=timeline,\n users_per_round=users_per_round,\n metric_reporter=metric_reporter,\n )\n self._calc_post_epoch_communication_metrics(\n timeline,\n metric_reporter,\n )\n self.logger.info(f\"Aggregate round reporting took {time() - t} s.\")\n\n def _choose_clients_for_post_aggregation_metrics(\n self,\n train_clients: Iterable[Client],\n num_total_users: int,\n users_per_round: int,\n ) -> Iterable[Client]:\n \"\"\"\n Chooses clients for the post-aggregation training metrics.\n Depending on config parameters, either return the round's\n training clients or new randomly drawn clients.\n \"\"\"\n # pyre-fixme[16]: `SyncTrainer` has no attribute `cfg`.\n if self.cfg.use_train_clients_for_aggregation_metrics:\n return train_clients\n\n # For the post-aggregation metrics, evaluate on new users\n agg_metric_client_idcs = torch.multinomial(\n torch.ones(num_total_users, dtype=torch.float),\n users_per_round,\n replacement=False,\n ).tolist()\n\n agg_metric_clients = [\n self.create_or_get_client_for_data(i, self.data_provider)\n for i in agg_metric_client_idcs\n ]\n return agg_metric_clients\n\n def _calc_privacy_metrics(\n self,\n clients: Iterable[Client],\n model: IFLModel,\n metric_reporter: Optional[IFLMetricsReporter],\n ) -> List[Metric]:\n \"\"\"\n Calculates privacy metrics.\n \"\"\"\n\n metrics = []\n if self.is_user_level_dp:\n user_eps = self.server.privacy_budget.epsilon # pyre-fixme\n metrics.append(Metric(\"user level dp (eps)\", user_eps))\n if self.is_sample_level_dp:\n # calculate sample level dp privacy loss statistics.\n all_client_eps = torch.Tensor(\n [c.privacy_budget.epsilon for c in clients] # pyre-fixme\n )\n mean_client_eps = all_client_eps.mean()\n max_client_eps = all_client_eps.max()\n min_client_eps = all_client_eps.min()\n p50_client_eps = torch.median(all_client_eps)\n sample_dp_metrics: List[Metric] = Metric.from_args(\n mean=mean_client_eps,\n min=min_client_eps,\n max=max_client_eps,\n median=p50_client_eps,\n )\n metrics.append(Metric(\"sample level dp (eps)\", sample_dp_metrics))\n\n return metrics\n\n def _calc_overflow_metrics(\n self,\n clients: Iterable[Client],\n model: IFLModel,\n users_per_round: int,\n metric_reporter: Optional[IFLMetricsReporter],\n ) -> List[Metric]:\n \"\"\"\n Calculates overflow metrics.\n \"\"\"\n metrics = []\n if self.is_secure_aggregation_enabled:\n for client in clients:\n client.eval(model=model, metric_reporter=metric_reporter)\n (\n convert_overflow_perc,\n aggregate_overflow_perc,\n ) = self.server.calc_avg_overflow_percentage( # pyre-fixme\n users_per_round, model\n )\n overflow_metrics: List[Metric] = Metric.from_args(\n convert_overflow_percentage=convert_overflow_perc,\n aggregate_overflow_percentage=aggregate_overflow_perc,\n )\n metrics.append(Metric(\"overflow per round\", overflow_metrics))\n\n return metrics\n\n def calc_post_epoch_client_metrics(\n self,\n client_models: Dict[Client, IFLModel],\n round_timeline: Timeline,\n metric_reporter: IFLMetricsReporter,\n ) -> List[List[Metric]]:\n \"\"\"\n Calculates client-side metrics on the overall evaluation set\n \"\"\"\n client_metrics = []\n if metric_reporter is not None:\n for client, model in tqdm(client_models.items()):\n metric_reporter.reset()\n client.eval(\n model=model,\n metric_reporter=metric_reporter,\n )\n # pyre-fixme[16]: `IFLMetricsReporter` has no attribute\n # `compute_scores`.\n score = metric_reporter.compute_scores()\n client_metrics.append(Metric.from_dict(score))\n\n return client_metrics\n\n def _evaluate_global_model_after_aggregation(\n self,\n clients: Iterable[Client],\n model: IFLModel,\n timeline: Timeline,\n users_per_round: int,\n metric_reporter: Optional[IFLMetricsReporter] = None,\n ):\n if (\n metric_reporter is not None\n # pyre-fixme[16]: `SyncTrainer` has no attribute `cfg`.\n and self.cfg.report_train_metrics\n and self.cfg.report_train_metrics_after_aggregation\n and timeline.tick(1.0 / self.cfg.train_metrics_reported_per_epoch)\n ):\n with torch.no_grad():\n model.fl_get_module().eval()\n for eval_user in self.data_provider.eval_users():\n for batch in eval_user.eval_data():\n batch_metrics = model.get_eval_metrics(batch)\n if metric_reporter is not None:\n metric_reporter.add_batch_metrics(batch_metrics)\n model.fl_get_module().train()\n\n print(f\"Reporting {timeline} for aggregation\")\n privacy_metrics = self._calc_privacy_metrics(\n clients, model, metric_reporter\n )\n overflow_metrics = self._calc_overflow_metrics(\n clients, model, users_per_round, metric_reporter\n )\n\n metric_reporter.report_metrics(\n model=model,\n reset=True,\n stage=TrainingStage.AGGREGATION,\n timeline=timeline,\n epoch=timeline.global_round_num(), # for legacy\n print_to_channels=True,\n extra_metrics=privacy_metrics + overflow_metrics,\n )\n\n def _validate_users_per_round(\n self, users_per_round_on_worker: int, num_users_on_worker: int\n ):\n assert users_per_round_on_worker <= num_users_on_worker, (\n \"Users per round is greater than number of users in data provider for the worker.\"\n \"If you are using paged dataloader, increase your num_users_per_page >> users_per_round\"\n )\n\n def _report_post_epoch_client_metrics(\n self,\n timeline: Timeline,\n metric_reporter: Optional[IFLMetricsReporter],\n ):\n if (\n metric_reporter is not None\n # pyre-fixme[16]: `SyncTrainer` has no attribute `cfg`.\n and self.cfg.report_client_metrics\n and self.cfg.report_client_metrics_after_epoch\n and (timeline.epoch % self.cfg.client_metrics_reported_per_epoch == 0)\n ):\n client_models = {\n client: client.last_updated_model for client in self.clients.values()\n }\n client_scores = self.calc_post_epoch_client_metrics(\n client_models, timeline, metric_reporter\n )\n\n # Find stats over the client_metrics (mean, min, max, median, std)\n client_stats_trackers = {}\n score_names = [metric.name for metric in next(iter(client_scores))]\n for score_name in score_names:\n client_stats_trackers[score_name] = RandomVariableStatsTracker(\n tracks_quantiles=True\n )\n for client_metric_list in client_scores:\n for client_metric in client_metric_list:\n client_stats_trackers[client_metric.name].update(\n client_metric.value\n )\n\n reportable_client_metrics = []\n for score_name in score_names:\n for stat_name, stat_key in [\n (\"Mean\", \"mean_val\"),\n (\"Median\", \"median_val\"),\n (\"Upper Quartile\", \"upper_quartile_val\"),\n (\"Lower Quartile\", \"lower_quartile_val\"),\n (\"Min\", \"min_val\"),\n (\"Max\", \"max_val\"),\n (\"Standard Deviation\", \"standard_deviation_val\"),\n (\"Num Samples\", \"num_samples\"),\n ]:\n score = client_stats_trackers[score_name].__getattribute__(stat_key)\n reportable_client_metrics.append(Metric(stat_name, score))\n\n metric_reporter.report_metrics(\n model=None,\n reset=True,\n stage=TrainingStage.PER_CLIENT_EVAL,\n timeline=timeline,\n epoch=timeline.global_round_num(), # for legacy\n print_to_channels=True,\n extra_metrics=reportable_client_metrics,\n )\n\n @staticmethod\n def rounds_in_one_epoch(num_total_users: int, users_per_round: int) -> int:\n return math.ceil(num_total_users / users_per_round)\n\n\ndef force_print(is_distributed: bool, *args, **kwargs) -> None:\n if is_distributed:\n try:\n device_info = f\" [device:{torch.cuda.current_device()}]\"\n # pyre-fixme[28]: Unexpected keyword argument `force`.\n print(*args, device_info, **kwargs, force=True)\n except TypeError:\n pass\n else:\n print(*args, **kwargs)\n\n\n@dataclass\nclass SyncTrainerConfig(FLTrainerConfig):\n _target_: str = fullclassname(SyncTrainer)\n server: SyncServerConfig = SyncServerConfig()\n users_per_round: int = 10\n # overselect users_per_round / dropout_rate users, only use first\n # users_per_round updates\n dropout_rate: float = 1.0\n report_train_metrics_after_aggregation: bool = False\n report_client_metrics_after_epoch: bool = False\n # Whether client metrics on eval data should be computed and reported.\n report_client_metrics: bool = False\n # how many times per epoch should we report client metrics\n # numbers greater than 1 help with plotting more precise training curves\n client_metrics_reported_per_epoch: int = 1\n"
]
| [
[
"torch.ones",
"torch.Tensor",
"torch.cuda.current_device",
"torch.median",
"torch.no_grad"
]
]
|
event-driven-robotics/movenet.pytorch | [
"24c1175645ede19d21a98506f5e9006a4b546e83"
]
| [
"lib/task/task_tools.py"
]
| [
"\"\"\"\r\n@Fire\r\nhttps://github.com/fire717\r\n\"\"\"\r\n\r\nimport torch.optim as optim\r\nimport numpy as np\r\nimport cv2\r\n\r\nfrom lib.utils.utils import maxPoint, extract_keypoints\r\n\r\n_range_weight_x = np.array([[x for x in range(48)] for _ in range(48)])\r\n_range_weight_y = _range_weight_x.T\r\n\r\n\r\n# _reg_weight = np.load(\"lib/data/my_weight_reg.npy\") # 99x99\r\n\r\n\r\ndef getSchedu(schedu, optimizer):\r\n if 'default' in schedu:\r\n factor = float(schedu.strip().split('-')[1])\r\n patience = int(schedu.strip().split('-')[2])\r\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer,\r\n mode='max', factor=factor, patience=patience, min_lr=0.000001)\r\n\r\n elif 'step' in schedu:\r\n step_size = int(schedu.strip().split('-')[1])\r\n gamma = int(schedu.strip().split('-')[2])\r\n scheduler = optim.lr_scheduler.StepLR(optimizer, step_size=step_size, gamma=gamma, last_epoch=-1)\r\n\r\n elif 'SGDR' in schedu:\r\n T_0 = int(schedu.strip().split('-')[1])\r\n T_mult = int(schedu.strip().split('-')[2])\r\n scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer,\r\n T_0=T_0,\r\n T_mult=T_mult)\r\n elif 'MultiStepLR' in schedu:\r\n milestones = [int(x) for x in schedu.strip().split('-')[1].split(',')]\r\n gamma = float(schedu.strip().split('-')[2])\r\n scheduler = optim.lr_scheduler.MultiStepLR(optimizer,\r\n milestones=milestones,\r\n gamma=gamma)\r\n\r\n else:\r\n raise Exception(\"Unknown schedular.\")\r\n\r\n return scheduler\r\n\r\n\r\ndef getOptimizer(optims, model, learning_rate, weight_decay):\r\n if optims == 'Adam':\r\n optimizer = optim.Adam(model.parameters(), lr=learning_rate, weight_decay=weight_decay)\r\n elif optims == 'SGD':\r\n optimizer = optim.SGD(model.parameters(), lr=learning_rate, momentum=0.9, weight_decay=weight_decay)\r\n else:\r\n raise Exception(\"Unknown optimizer.\")\r\n return optimizer\r\n\r\n\r\n############### Tools\r\n\r\ndef clipGradient(optimizer, grad_clip=1):\r\n \"\"\"\r\n Clips gradients computed during backpropagation to avoid explosion of gradients.\r\n\r\n :param optimizer: optimizer with the gradients to be clipped\r\n :param grad_clip: clip value\r\n \"\"\"\r\n for group in optimizer.param_groups:\r\n for param in group[\"params\"]:\r\n if param.grad is not None:\r\n param.grad.data.clamp_(-grad_clip, grad_clip)\r\n\r\n\r\n# def sigmoid(x):\r\n# # TODO: Implement sigmoid function\r\n# return 1/(1 + np.exp(-x))\r\n\r\ndef movenetDecode(data, kps_mask=None, mode='output', num_joints=17,\r\n img_size=192, hm_th=0.1):\r\n ##data [64, 7, 48, 48] [64, 1, 48, 48] [64, 14, 48, 48] [64, 14, 48, 48]\r\n # kps_mask [n, 7]\r\n\r\n if mode == 'output':\r\n batch_size = data[0].size(0)\r\n\r\n heatmaps = data[0].detach().cpu().numpy()\r\n\r\n heatmaps[heatmaps < hm_th] = 0\r\n\r\n centers = data[1].detach().cpu().numpy()\r\n\r\n regs = data[2].detach().cpu().numpy()\r\n offsets = data[3].detach().cpu().numpy()\r\n\r\n cx, cy = maxPoint(centers)\r\n # cx,cy = extract_keypoints(centers[0])\r\n # print(\"movenetDecode 119 cx,cy: \",cx,cy)\r\n\r\n dim0 = np.arange(batch_size, dtype=np.int32).reshape(batch_size, 1)\r\n dim1 = np.zeros((batch_size, 1), dtype=np.int32)\r\n\r\n res = []\r\n for n in range(num_joints):\r\n # nchw!!!!!!!!!!!!!!!!!\r\n\r\n reg_x_origin = (regs[dim0, dim1 + n * 2, cy, cx] + 0.5).astype(np.int32)\r\n reg_y_origin = (regs[dim0, dim1 + n * 2 + 1, cy, cx] + 0.5).astype(np.int32)\r\n # print(reg_x_origin,reg_y_origin)\r\n reg_x = reg_x_origin + cx\r\n reg_y = reg_y_origin + cy\r\n # print(reg_x, reg_y)\r\n\r\n ### for post process\r\n reg_x = np.reshape(reg_x, (reg_x.shape[0], 1, 1))\r\n reg_y = np.reshape(reg_y, (reg_y.shape[0], 1, 1))\r\n # print(reg_x.shape,reg_x,reg_y)\r\n reg_x = reg_x.repeat(48, 1).repeat(48, 2)\r\n reg_y = reg_y.repeat(48, 1).repeat(48, 2)\r\n # print(reg_x.repeat(48,1).repeat(48,2).shape)\r\n # bb\r\n\r\n #### ๆ นๆฎcenterๅพๅฐๅ
ณ้ฎ็นๅๅฝไฝ็ฝฎ๏ผ็ถๅๅ ๆheatmap\r\n range_weight_x = np.reshape(_range_weight_x, (1, 48, 48)).repeat(reg_x.shape[0], 0)\r\n range_weight_y = np.reshape(_range_weight_y, (1, 48, 48)).repeat(reg_x.shape[0], 0)\r\n tmp_reg_x = (range_weight_x - reg_x) ** 2\r\n tmp_reg_y = (range_weight_y - reg_y) ** 2\r\n # print(tmp_reg_x.shape, _range_weight_x.shape, reg_x.shape)\r\n tmp_reg = (tmp_reg_x + tmp_reg_y) ** 0.5 + 1.8 # origin 1.8\r\n # print(tmp_reg.shape,heatmaps[:,n,...].shape)(1, 48, 48)\r\n # print(heatmaps[:,n,...][0][19:25,19:25])\r\n # cv2.imwrite(\"t.jpg\",heatmaps[:,n,...][0]*255)\r\n # print(tmp_reg[0][19:25,19:25])\r\n tmp_reg = heatmaps[:, n, ...] / tmp_reg\r\n # print(tmp_reg[0][19:25,19:25])\r\n\r\n # reg_cx = max(0,min(47,reg_x[0][0][0]))\r\n # reg_cy = max(0,min(47,reg_y[0][0][0]))\r\n # _reg_weight_part = _reg_weight[49-reg_cy:49-reg_cy+48, 49-reg_cx:49-reg_cx+48]\r\n # if _reg_weight_part.shape[0]!=48 or _reg_weight_part.shape[1]!=48:\r\n # print(_reg_weight_part.shape)\r\n # print(reg_cy,reg_cx)\r\n # bbb\r\n # # print(_reg_weight_part[reg_cy,reg_cx])\r\n # #keep reg_cx reg_cy to 1\r\n # tmp_reg = heatmaps[:,n,...]*_reg_weight_part\r\n\r\n # b\r\n\r\n # if n==1:\r\n # cv2.imwrite('output/predict/t3.jpg', cv2.resize(tmp_reg[0]*2550,(192,192)))\r\n tmp_reg = tmp_reg[:, np.newaxis, :, :]\r\n reg_x, reg_y = maxPoint(tmp_reg, center=False)\r\n\r\n # # print(reg_x, reg_y)\r\n reg_x[reg_x > 47] = 47\r\n reg_x[reg_x < 0] = 0\r\n reg_y[reg_y > 47] = 47\r\n reg_y[reg_y < 0] = 0\r\n\r\n score = heatmaps[dim0, dim1 + n, reg_y, reg_x]\r\n # print(score)\r\n offset_x = offsets[dim0, dim1 + n * 2, reg_y, reg_x] # *img_size//4\r\n offset_y = offsets[dim0, dim1 + n * 2 + 1, reg_y, reg_x] # *img_size//4\r\n # print(offset_x,offset_y)\r\n res_x = (reg_x + offset_x) / (img_size // 4)\r\n res_y = (reg_y + offset_y) / (img_size // 4)\r\n # print(res_x,res_y)\r\n\r\n res_x[score < hm_th] = -1\r\n res_y[score < hm_th] = -1\r\n\r\n res.extend([res_x, res_y])\r\n # b\r\n\r\n res = np.concatenate(res, axis=1) # bs*14\r\n\r\n\r\n\r\n elif mode == 'label':\r\n kps_mask = kps_mask.detach().cpu().numpy()\r\n\r\n data = data.detach().cpu().numpy()\r\n # print(data.shape)\r\n batch_size = data.shape[0]\r\n\r\n heatmaps = data[:, :num_joints, :, :]\r\n centers = data[:, num_joints, :, :]\r\n regs = data[:, num_joints + 1:(num_joints * 3) + 1, :, :]\r\n offsets = data[:, (num_joints * 3) + 1:, :, :]\r\n\r\n # cv2.imwrite(os.path.join(\"_centers.jpg\"), centers[0][0]*255)\r\n # cv2.imwrite(os.path.join(\"_heatmaps0.jpg\"), heatmaps[0][0]*255)\r\n # cv2.imwrite(os.path.join(\"_regs0.jpg\"), regs[0][0]**2*255)\r\n # cv2.imwrite(os.path.join(\"_offsets0.jpg\"), offsets[0][1]**2*1000)\r\n # bb\r\n # print(\"movenetDecode centers \",centers)\r\n # print(centers[0,0,26:30,30:33])\r\n # print(_center_weight[20:26,20:26])\r\n # t = centers*_center_weight\r\n # print(t[0,0,20:26,20:26])\r\n cx, cy = maxPoint(centers)\r\n # cx,cy = extract_keypoints(centers[0])\r\n # print(\"decode maxPoint \" ,cx, cy)\r\n # print(regs[0][0][22:26,22:26])\r\n # print(regs[0][1][22:26,22:26])\r\n\r\n # print(cx.shape,cy.shape)#(64, 1) (64, 1)\r\n # print(cx.squeeze().shape)#(64,)\r\n # print(regs.shape)#64, 14, 48, 48\r\n dim0 = np.arange(batch_size, dtype=np.int32).reshape(batch_size, 1)\r\n dim1 = np.zeros((batch_size, 1), dtype=np.int32)\r\n\r\n res = []\r\n for n in range(num_joints):\r\n # nchw!!!!!!!!!!!!!!!!!\r\n # print(regs[dim0,dim1,cx,cy].shape) #64,1\r\n\r\n reg_x_origin = (regs[dim0, dim1 + n * 2, cy, cx] + 0.5).astype(np.int32)\r\n reg_y_origin = (regs[dim0, dim1 + n * 2 + 1, cy, cx] + 0.5).astype(np.int32)\r\n\r\n # print(reg_x_origin,reg_y_origin)\r\n # print(np.max(regs[dim0,dim1+n*2,:,:]),np.min(regs[dim0,dim1+n*2,:,:]))\r\n\r\n # print(regs[dim0,dim1+n*2,22:26,22:26])\r\n # b\r\n # print(kps_mask.shape, kps_mask[:,n].shape,kps_mask[:,n])\r\n # bb\r\n\r\n # print(reg_x_origin,reg_y_origin)\r\n\r\n reg_x = reg_x_origin + cx\r\n reg_y = reg_y_origin + cy\r\n\r\n # print(reg_x, reg_y)\r\n reg_x[reg_x > 47] = 47\r\n reg_x[reg_x < 0] = 0\r\n reg_y[reg_y > 47] = 47\r\n reg_y[reg_y < 0] = 0\r\n\r\n offset_x = offsets[dim0, dim1 + n * 2, reg_y, reg_x] # *img_size//4\r\n offset_y = offsets[dim0, dim1 + n * 2 + 1, reg_y, reg_x] # *img_size//4\r\n # print(offset_x,offset_y)\r\n res_x = (reg_x + offset_x) / (img_size // 4)\r\n res_y = (reg_y + offset_y) / (img_size // 4)\r\n\r\n # ไธๅญๅจ็็น่ฎพไธบ-1 ๅ็ปญไธๅไธacc่ฎก็ฎ\r\n res_x[kps_mask[:, n] == 0] = -1\r\n res_y[kps_mask[:, n] == 0] = -1\r\n # print(res_x,res_y)\r\n # print()\r\n res.extend([res_x, res_y])\r\n # b\r\n\r\n res = np.concatenate(res, axis=1) # bs*14\r\n # print(res.shape)\r\n # b\r\n return res\r\n\r\ndef restore_sizes(img_tensor,pose,size_out):\r\n size_in = img_tensor.shape\r\n\r\n # resize image\r\n img = np.transpose(img_tensor.cpu().numpy(), axes=[1, 2, 0])\r\n img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)\r\n img_out = cv2.resize(img,(size_out[1],size_out[0]))\r\n pose_out = np.copy(pose.reshape((-1,2)))\r\n for i in range(len(pose_out)):\r\n pose_out[i,0] = pose_out[i,0] * size_out[1]\r\n pose_out[i,1] = pose_out[i,1] * size_out[0]\r\n\r\n return img_out, pose_out\r\n"
]
| [
[
"torch.optim.lr_scheduler.MultiStepLR",
"torch.optim.lr_scheduler.CosineAnnealingWarmRestarts",
"torch.optim.lr_scheduler.ReduceLROnPlateau",
"numpy.reshape",
"numpy.arange",
"numpy.concatenate",
"numpy.zeros",
"torch.optim.lr_scheduler.StepLR"
]
]
|
npetrenko/recurrent_frcnn | [
"9fb948a9f6ee87e8f6d48d65c8ad2e957f7ab7ee"
]
| [
"test_frcnn.py"
]
| [
"from __future__ import division\nimport random\nimport pprint\nimport sys\nimport time\nimport numpy as np\nimport pickle\nimport os\n\nfrom keras import backend as K\nfrom keras.optimizers import Adam\nfrom rcnn import config, data_generators\nfrom rcnn import losses as losses\nimport rcnn.roi_helpers as roi_helpers\nfrom keras.utils import generic_utils\nfrom rcnn.MOT_parser import read_ini\nimport cv2\n\nimport tensorflow as tf\nfrom rcnn import detector_rpn_extraction\nfrom rcnn.generate_cache import create_cache\n\nfrom rcnn import config\nfrom rcnn import roi_helpers\n\nfrom os.path import join\nfrom os import listdir\n\nos.environ['CUDA_VISIBLE_DEVICES'] = \"\"\n\nsess = tf.Session()\nK.set_session(sess)\n\nsys.setrecursionlimit(40000)\n\ndataset_path = ['/tmp/MOT17_test/']\npart = 'train'\nnum_rois = 32\nconfig_filename = 'config.pickle'\n\nsave_path = './experiment_save/with_det'#'./save_dir/rpn_only.sv'\nn_jobs = 4\n\nseqs = [join(dataset, part, video) for dataset in dataset_path for video in listdir(join(dataset, part)) if 'DS_' not in video and 'DS_' not in dataset]\nprint(seqs)\n\nsess = tf.Session()\nK.set_session(sess)\n\nwith open(config_filename, 'rb') as f_in:\n\tC = pickle.load(f_in)\n\nfrom rcnn import simple_nn as nn\n\nnum_anchors = len(C.anchor_box_scales) * len(C.anchor_box_ratios)\n\n\n# turn off any data augmentation at test time\nC.use_horizontal_flips = False\nC.use_vertical_flips = False\nC.rot_90 = False\n\nclass_mapping = C.class_mapping\n\ndef format_img_size(img, C):\n\t\"\"\" formats the image size based on config \"\"\"\n\timg_min_side = float(C.im_size)\n\t(height,width,_) = img.shape\n\t\t\n\tif width <= height:\n\t\tratio = img_min_side/width\n\t\tnew_height = int(ratio * height)\n\t\tnew_width = int(img_min_side)\n\telse:\n\t\tratio = img_min_side/height\n\t\tnew_width = int(ratio * width)\n\t\tnew_height = int(img_min_side)\n\timg = cv2.resize(img, (new_width, new_height), interpolation=cv2.INTER_CUBIC)\n\treturn img, ratio\t\n\ndef format_img_channels(img, C):\n\t\"\"\" formats the image channels based on config \"\"\"\n\timg = img[:, :, (2, 1, 0)]\n\timg = img.astype(np.float32)\n\timg[:, :, 0] -= C.img_channel_mean[0]\n\timg[:, :, 1] -= C.img_channel_mean[1]\n\timg[:, :, 2] -= C.img_channel_mean[2]\n\timg /= C.img_scaling_factor\n\timg = np.transpose(img, (2, 0, 1))\n\timg = np.expand_dims(img, axis=0)\n\treturn img\n\ndef format_img(img, C):\n\t\"\"\" formats an image for model prediction based on config \"\"\"\n\timg, ratio = format_img_size(img, C)\n\timg = format_img_channels(img, C)\n\treturn img, ratio\n\n# Method to transform the coordinates of the bounding box to its original size\ndef get_real_coordinates(ratio, x1, y1, x2, y2):\n\n\treal_x1 = int(round(x1 // ratio))\n\treal_y1 = int(round(y1 // ratio))\n\treal_x2 = int(round(x2 // ratio))\n\treal_y2 = int(round(y2 // ratio))\n\n\treturn (real_x1, real_y1, real_x2 ,real_y2)\n\nif 'bg' not in class_mapping:\n\tclass_mapping['bg'] = len(class_mapping)\n\nclass_mapping = {v: k for k, v in class_mapping.items()}\nprint(class_mapping)\n\nclass_to_color = {class_mapping[v]: np.random.randint(0, 255, 3) for v in class_mapping}\nC.num_rois = num_rois\n\n# define the RPN, built on the base layers\nnum_anchors = len(C.anchor_box_scales) * len(C.anchor_box_ratios)\n\nmodel = nn.FRCNN(num_anchors, C.num_rois, base_weights=None, lr = 0.00001)\n\nprint('Loading weights from {}'.format(save_path))\nsaver = tf.train.Saver()\nsaver.restore(sess, save_path)\n\nall_imgs = []\n\nclasses = {}\n\nbbox_threshold = 0.76\n\nwith sess.as_default():\n for video_seq in seqs:\n seqinfo = read_ini(join(video_seq, 'seqinfo.ini'))\n\n img_path = join(video_seq, seqinfo['imDir'])\n\n try:\n coord_form = seqinfo['coordform']\n except KeyError:\n coord_form = None\n\n num_gt_objects = 0\n with open(join(video_seq, 'gt/gt.txt'), 'r') as f:\n for line in f:\n #frameix,x1,y1,w,h = map(lambda x: int(float(x)), line_split[0:1] + line_split[2:6])\n num_gt_objects += 1\n\n im_seq = []\n bbox_seq = []\n\n st = time.time()\n\n for idx, img_name in enumerate(sorted(os.listdir(img_path))):\n if not img_name.lower().endswith(('.bmp', '.jpeg', '.jpg', '.png', '.tif', '.tiff')):\n continue\n print(img_name)\n\n filepath = join(img_path,img_name)\n\n img = cv2.imread(filepath)\n\n X, ratio = format_img(img, C)\n\n X = np.transpose(X, (0, 2, 3, 1))\n im_seq.append(X[0])\n\n im_seq = np.array(im_seq)[np.newaxis,...]\n\n # get the feature maps and output from the RPN\n Y1_seq, Y2_seq, F_seq = model.predict_rpn_base(im_seq)\n\n\n for t in range(Y1_seq.shape[1]):\n bbox_seq.append([])\n Y1, Y2, F = Y1_seq[:,t], Y2_seq[:,t], F_seq[:,t]\n R = roi_helpers.rpn_to_roi(Y1, Y2, C, 'tf', overlap_thresh=0.7)\n\n # convert from (x1,y1,x2,y2) to (x,y,w,h)\n R[:, 2] -= R[:, 0]\n R[:, 3] -= R[:, 1]\n\n # apply the spatial pyramid pooling to the proposed regions\n bboxes = {}\n probs = {}\n\n for jk in range(R.shape[0]//C.num_rois + 1):\n ROIs = np.expand_dims(R[C.num_rois*jk:C.num_rois*(jk+1), :], axis=0)\n if ROIs.shape[1] == 0:\n break\n\n if jk == R.shape[0]//C.num_rois:\n #pad R\n curr_shape = ROIs.shape\n target_shape = (curr_shape[0],C.num_rois,curr_shape[2])\n ROIs_padded = np.zeros(target_shape).astype(ROIs.dtype)\n ROIs_padded[:, :curr_shape[1], :] = ROIs\n ROIs_padded[0, curr_shape[1]:, :] = ROIs[0, 0, :]\n ROIs = ROIs_padded\n\n [P_cls, P_regr] = model.predict_detec(F, ROIs)\n\n for ii in range(P_cls.shape[1]):\n\n #if np.max(P_cls[0, ii, :]) < bbox_threshold or np.argmax(P_cls[0, ii, :]) == (P_cls.shape[2] - 1):\n #continue\n if P_cls[0,ii,0] < bbox_threshold:\n continue\n\n cls_name = class_mapping[0]\n #cls_name = class_mapping[np.argmax(P_cls[0, ii, :])]\n\n if cls_name not in bboxes:\n bboxes[cls_name] = []\n probs[cls_name] = []\n\n (x, y, w, h) = ROIs[0, ii, :]\n\n #cls_num = np.argmax(P_cls[0, ii, :])\n cls_num = 0\n\n try:\n (tx, ty, tw, th) = P_regr[0, ii, 4*cls_num:4*(cls_num+1)]\n tx /= C.classifier_regr_std[0]\n ty /= C.classifier_regr_std[1]\n tw /= C.classifier_regr_std[2]\n th /= C.classifier_regr_std[3]\n x, y, w, h = roi_helpers.apply_regr(x, y, w, h, tx, ty, tw, th)\n except:\n pass\n bboxes[cls_name].append([C.rpn_stride*x, C.rpn_stride*y, C.rpn_stride*(x+w), C.rpn_stride*(y+h)])\n probs[cls_name].append(np.max(P_cls[0, ii, :]))\n\n all_dets = []\n\n for key in bboxes:\n bbox = np.array(bboxes[key])\n bbox_seq[-1].append(bbox)\n\n new_boxes, new_probs = roi_helpers.non_max_suppression_fast(bbox, np.array(probs[key]), overlap_thresh=0.5)\n for jk in range(new_boxes.shape[0]):\n (x1, y1, x2, y2) = new_boxes[jk,:]\n\n (real_x1, real_y1, real_x2, real_y2) = get_real_coordinates(ratio, x1, y1, x2, y2)\n\n #cv2.rectangle(img,(real_x1, real_y1), (real_x2, real_y2), (int(class_to_color[key][0]), int(class_to_color[key][1]), int(class_to_color[key][2])),2)\n\n textLabel = '{}: {}'.format(key,int(100*new_probs[jk]))\n all_dets.append((key,100*new_probs[jk]))\n\n (retval,baseLine) = cv2.getTextSize(textLabel,cv2.FONT_HERSHEY_COMPLEX,1,1)\n textOrg = (real_x1, real_y1-0)\n\n #cv2.rectangle(img, (textOrg[0] - 5, textOrg[1]+baseLine - 5), (textOrg[0]+retval[0] + 5, textOrg[1]-retval[1] - 5), (0, 0, 0), 2)\n #cv2.rectangle(img, (textOrg[0] - 5,textOrg[1]+baseLine - 5), (textOrg[0]+retval[0] + 5, textOrg[1]-retval[1] - 5), (255, 255, 255), -1)\n #cv2.putText(img, textLabel, textOrg, cv2.FONT_HERSHEY_DUPLEX, 1, (0, 0, 0), 1)\n\n print('Elapsed time = {}'.format(time.time() - st))\n print('GT/DET ratio = {}'.format(sum([len(x) for x in bbox_seq])/num_gt_objects))\n #cv2.imshow('img', img)\n #cv2.waitKey(0)\n # cv2.imwrite('./results_imgs/{}.png'.format(idx),img)\n"
]
| [
[
"numpy.expand_dims",
"numpy.max",
"tensorflow.Session",
"numpy.transpose",
"tensorflow.train.Saver",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
]
|
ArmandoSep/DS-Unit-3-Sprint-2-SQL-and-Databases | [
"3087a3f0602362fa5ec7c81e3517ac582e7d1c26"
]
| [
"module1-introduction-to-sql/buddymove_queries.py"
]
| [
"\nimport pandas as pd \nimport os\nimport sqlite3\n\ndf = pd.read_csv(\"module1-introduction-to-sql/buddymove_holidayiq.csv\")\ndf = df.rename(columns={'User Id':'id'})\n\n# construct a path to wherever your database exists\nDB_FILEPATH = os.path.join(os.path.dirname(__file__), \"buddymove_holidayiq.sqlite3\")\n\nconnection = sqlite3.connect(DB_FILEPATH)\nprint(\"CONNECTION:\", connection)\n\ncursor = connection.cursor()\nprint(\"CURSOR\", cursor)\n\n# Transform the DF into SQL\n#df.to_sql('review', con=connection, if_exists='replace')\n\n# Query 1: Count how many rows you have\nquery = \"SELECT count(DISTINCT id) as user_count FROM review;\"\n\nresult1 = cursor.execute(query).fetchone()\nprint(\"RESULT 1: Count how many rows you have\", result1)\n\n# Query 2: How many users who reviewed at least 100 Nature in the category \n# also reviewed at least 100 in the Shopping category?\nquery = \"SELECT count(DISTINCT id) as count FROM review \\\n\tWHERE Nature >= 100 and\tShopping >= 100;\"\n\nresult2 = cursor.execute(query).fetchone()\nprint(\"RESULT 2: How many users who reviewed at least 100 Nature in the category \\\n also reviewed at least 100 in the Shopping category?\", result2)"
]
| [
[
"pandas.read_csv"
]
]
|
Immocat/ACTOR | [
"c7237e82e333bf2c57f7d8e12f27d0831233befc"
]
| [
"src/utils/tensors.py"
]
| [
"import torch\n\n\ndef lengths_to_mask(lengths):\n max_len = max(lengths)\n mask = torch.arange(max_len, device=lengths.device).expand(len(lengths), max_len) < lengths.unsqueeze(1)\n return mask\n \n\ndef collate_tensors(batch):\n dims = batch[0].dim()\n max_size = [max([b.size(i) for b in batch]) for i in range(dims)]\n size = (len(batch),) + tuple(max_size)\n canvas = batch[0].new_zeros(size=size)\n for i, b in enumerate(batch):\n sub_tensor = canvas[i]\n for d in range(dims):\n sub_tensor = sub_tensor.narrow(d, 0, b.size(d))\n sub_tensor.add_(b)\n return canvas\n\n\ndef collate(batch):\n databatch = [b[0] for b in batch]\n labelbatch = [b[1] for b in batch]\n lenbatch = [len(b[0][0][0]) for b in batch]\n\n databatchTensor = collate_tensors(databatch)\n labelbatchTensor = torch.as_tensor(labelbatch)\n lenbatchTensor = torch.as_tensor(lenbatch)\n\n maskbatchTensor = lengths_to_mask(lenbatchTensor)\n batch = {\"x\": databatchTensor, \"y\": labelbatchTensor,\n \"mask\": maskbatchTensor, \"lengths\": lenbatchTensor}\n return batch\n"
]
| [
[
"torch.arange",
"torch.as_tensor"
]
]
|
tobyrsmith/ExLunaPlots | [
"02bd15c33cbeae8644a4d60938c5eb922ebd228c"
]
| [
"15415ree.py"
]
| [
"#!/home/toby/anaconda/bin/python\n\nimport matplotlib.pyplot as plt\nimport numpy as np\n\ndef log_10_product(x, pos):\n if (x < 1.0):\n return '%3.1f' % (x)\n else:\n return '%i' % (x)\n\ncc = '0.10'\n\nfont = {'family' : 'DejaVu Serif',\n 'weight' : 'normal',\n 'size' : 20,\n}\n\ntfont = {\n 'family' : 'DejaVu Serif',\n 'weight' : 'normal',\n 'size' : 14}\n\nsfont = {\n 'family' : 'DejaVu Serif',\n 'weight' : 'bold',\n 'style': 'italic',\n 'size' : 10}\n\nplt.rc('font', **tfont)\nplt.rc(\"axes\", linewidth=2.0,edgecolor=cc)\n\nfig, ax = plt.subplots()\n\nax = plt.subplot(111, axisbg='0.90', axisbelow=True)\n\nax.grid(b=True, which='major', color='#ffffff', linewidth=2, linestyle='-')\n\nax.spines['top'].set_visible(False)\nax.spines['right'].set_visible(False)\nax.spines['bottom'].set_visible(False)\nax.spines['left'].set_visible(False)\nax.get_xaxis().tick_bottom()\nax.get_yaxis().tick_left()\n\nax.xaxis.set_tick_params(width=2,length=4)\nax.yaxis.set_tick_params('minor',width=2,length=0)\nax.yaxis.set_tick_params('major',width=2,length=4)\n\nax.yaxis.label.set_color(cc)\nax.xaxis.label.set_color(cc)\nax.tick_params(axis='x', colors=cc)\nax.tick_params(axis='y', colors=cc)\n\n# End Defaults\n\n\n\neln,ab,cc = np.loadtxt(\"10022_REE.dat\",usecols=(1,2,3), unpack=True)\neln15,ab15,cc15 = np.loadtxt(\"15415REE.dat\",usecols=(1,4,3), unpack=True)\nel = np.array(['x','La','Ce','Pr','Nd','Pm','Sm','Eu','Gd','Tb','Dy','Ho','Er','Tm','Yb','Lu'])\n\nratio = ab/cc\nratio15 = ab15/cc15\n\nax.set_yscale('log')\n\nax.xaxis.set_major_locator(plt.MultipleLocator(1))\nax.xaxis.set_major_formatter(plt.FixedFormatter(el))\n\nformatter = plt.FuncFormatter(log_10_product)\nax.yaxis.set_major_formatter(formatter)\n\nplt.plot(eln,ratio,linewidth=2,color='b')\nplt.plot(eln,ratio,'o',markersize=15,color='r')\n\nplt.plot(eln15,ratio15,linewidth=2,color='g')\nplt.plot(eln15,ratio15,'o',markersize=15,color='yellow')\n\nplt.xlim(56.5,71.5)\nplt.ylim(0.05,500)\n\nplt.xlabel('\\nElement', fontdict=font)\nplt.ylabel('Sample / Chondrite', fontdict=font)\n\nplt.text(67,175, '10022', fontdict=font)\nplt.text(67,0.3, '15415', fontdict=font)\n\nplt.subplots_adjust(bottom=0.15, left=.15, right=.99, top=.99)\n\nplt.savefig('test.png',dpi=300)\n#plt.show()\n\n\n"
]
| [
[
"matplotlib.pyplot.FuncFormatter",
"matplotlib.pyplot.ylim",
"matplotlib.pyplot.rc",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.MultipleLocator",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlim",
"matplotlib.pyplot.subplot",
"matplotlib.pyplot.subplots_adjust",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.text",
"numpy.array",
"matplotlib.pyplot.FixedFormatter",
"numpy.loadtxt",
"matplotlib.pyplot.ylabel"
]
]
|
marshuang80/napari | [
"10f1d0f39fe9ccd42456c95458e2f23b59450f02"
]
| [
"napari/util/colormaps/vendored/cm.py"
]
| [
"\"\"\"\nBuiltin colormaps, colormap handling utilities, and the `ScalarMappable` mixin.\n\n.. seealso::\n\n :doc:`/gallery/color/colormap_reference` for a list of builtin\n colormaps.\n\n :doc:`/tutorials/colors/colormap-manipulation` for examples of how to\n make colormaps and\n\n :doc:`/tutorials/colors/colormaps` an in-depth discussion of\n choosing colormaps.\n\n :doc:`/tutorials/colors/colormapnorms` for more details about data\n normalization\n\n\n\"\"\"\n\nimport functools\n\nimport numpy as np\nfrom numpy import ma\n\nfrom . import colors\nfrom ._cm import datad\nfrom ._cm_listed import cmaps as cmaps_listed\n\n\ncmap_d = {}\n\n\n# reverse all the colormaps.\n# reversed colormaps have '_r' appended to the name.\n\n\ndef _reverser(f, x=None):\n \"\"\"Helper such that ``_reverser(f)(x) == f(1 - x)``.\"\"\"\n if x is None:\n # Returning a partial object keeps it picklable.\n return functools.partial(_reverser, f)\n return f(1 - x)\n\n\ndef revcmap(data):\n \"\"\"Can only handle specification *data* in dictionary format.\"\"\"\n data_r = {}\n for key, val in data.items():\n if callable(val):\n valnew = _reverser(val)\n # This doesn't work: lambda x: val(1-x)\n # The same \"val\" (the first one) is used\n # each time, so the colors are identical\n # and the result is shades of gray.\n else:\n # Flip x and exchange the y values facing x = 0 and x = 1.\n valnew = [(1.0 - x, y1, y0) for x, y0, y1 in reversed(val)]\n data_r[key] = valnew\n return data_r\n\n\ndef _reverse_cmap_spec(spec):\n \"\"\"Reverses cmap specification *spec*, can handle both dict and tuple\n type specs.\"\"\"\n\n if 'listed' in spec:\n return {'listed': spec['listed'][::-1]}\n\n if 'red' in spec:\n return revcmap(spec)\n else:\n revspec = list(reversed(spec))\n if len(revspec[0]) == 2: # e.g., (1, (1.0, 0.0, 1.0))\n revspec = [(1.0 - a, b) for a, b in revspec]\n return revspec\n\n\ndef _generate_cmap(name, lutsize):\n \"\"\"Generates the requested cmap from its *name*. The lut size is\n *lutsize*.\"\"\"\n\n spec = datad[name]\n\n # Generate the colormap object.\n if 'red' in spec:\n return colors.LinearSegmentedColormap(name, spec, lutsize)\n elif 'listed' in spec:\n return colors.ListedColormap(spec['listed'], name)\n else:\n return colors.LinearSegmentedColormap.from_list(name, spec, lutsize)\n\n\nLUTSIZE = 256\n\n# Generate the reversed specifications (all at once, to avoid\n# modify-when-iterating).\ndatad.update({cmapname + '_r': _reverse_cmap_spec(spec)\n for cmapname, spec in datad.items()})\n\n# Precache the cmaps with ``lutsize = LUTSIZE``.\n# Also add the reversed ones added in the section above:\nfor cmapname in datad:\n cmap_d[cmapname] = _generate_cmap(cmapname, LUTSIZE)\n\ncmap_d.update(cmaps_listed)\n\nlocals().update(cmap_d)\n\n\n# Continue with definitions ...\n\n\ndef register_cmap(name=None, cmap=None, data=None, lut=None):\n \"\"\"\n Add a colormap to the set recognized by :func:`get_cmap`.\n\n It can be used in two ways::\n\n register_cmap(name='swirly', cmap=swirly_cmap)\n\n register_cmap(name='choppy', data=choppydata, lut=128)\n\n In the first case, *cmap* must be a :class:`matplotlib.colors.Colormap`\n instance. The *name* is optional; if absent, the name will\n be the :attr:`~matplotlib.colors.Colormap.name` attribute of the *cmap*.\n\n In the second case, the three arguments are passed to\n the :class:`~matplotlib.colors.LinearSegmentedColormap` initializer,\n and the resulting colormap is registered.\n\n \"\"\"\n if name is None:\n try:\n name = cmap.name\n except AttributeError:\n raise ValueError(\"Arguments must include a name or a Colormap\")\n\n if not isinstance(name, str):\n raise ValueError(\"Colormap name must be a string\")\n\n if isinstance(cmap, colors.Colormap):\n cmap_d[name] = cmap\n return\n\n # For the remainder, let exceptions propagate.\n if lut is None:\n lut = LUTSIZE\n cmap = colors.LinearSegmentedColormap(name, data, lut)\n cmap_d[name] = cmap\n\n\ndef get_cmap(name=None, lut=None):\n \"\"\"\n Get a colormap instance, defaulting to rc values if *name* is None.\n\n Colormaps added with :func:`register_cmap` take precedence over\n built-in colormaps.\n\n If *name* is a :class:`matplotlib.colors.Colormap` instance, it will be\n returned.\n\n If *lut* is not None it must be an integer giving the number of\n entries desired in the lookup table, and *name* must be a standard\n mpl colormap name.\n \"\"\"\n if name is None:\n name = 'magma'\n\n if isinstance(name, colors.Colormap):\n return name\n\n if name in cmap_d:\n if lut is None:\n return cmap_d[name]\n else:\n return cmap_d[name]._resample(lut)\n else:\n raise ValueError(\n \"Colormap %s is not recognized. Possible values are: %s\"\n % (name, ', '.join(sorted(cmap_d))))\n\n\nclass ScalarMappable(object):\n \"\"\"\n This is a mixin class to support scalar data to RGBA mapping.\n The ScalarMappable makes use of data normalization before returning\n RGBA colors from the given colormap.\n\n \"\"\"\n def __init__(self, norm=None, cmap=None):\n r\"\"\"\n\n Parameters\n ----------\n norm : :class:`matplotlib.colors.Normalize` instance\n The normalizing object which scales data, typically into the\n interval ``[0, 1]``.\n If *None*, *norm* defaults to a *colors.Normalize* object which\n initializes its scaling based on the first data processed.\n cmap : str or :class:`~matplotlib.colors.Colormap` instance\n The colormap used to map normalized data values to RGBA colors.\n \"\"\"\n if cmap is None:\n cmap = get_cmap()\n if norm is None:\n norm = colors.Normalize()\n\n self._A = None\n #: The Normalization instance of this ScalarMappable.\n self.norm = norm\n #: The Colormap instance of this ScalarMappable.\n self.cmap = get_cmap(cmap)\n #: The last colorbar associated with this ScalarMappable. May be None.\n self.colorbar = None\n self.update_dict = {'array': False}\n\n def to_rgba(self, x, alpha=None, bytes=False, norm=True):\n \"\"\"\n Return a normalized rgba array corresponding to *x*.\n\n In the normal case, *x* is a 1-D or 2-D sequence of scalars, and\n the corresponding ndarray of rgba values will be returned,\n based on the norm and colormap set for this ScalarMappable.\n\n There is one special case, for handling images that are already\n rgb or rgba, such as might have been read from an image file.\n If *x* is an ndarray with 3 dimensions,\n and the last dimension is either 3 or 4, then it will be\n treated as an rgb or rgba array, and no mapping will be done.\n The array can be uint8, or it can be floating point with\n values in the 0-1 range; otherwise a ValueError will be raised.\n If it is a masked array, the mask will be ignored.\n If the last dimension is 3, the *alpha* kwarg (defaulting to 1)\n will be used to fill in the transparency. If the last dimension\n is 4, the *alpha* kwarg is ignored; it does not\n replace the pre-existing alpha. A ValueError will be raised\n if the third dimension is other than 3 or 4.\n\n In either case, if *bytes* is *False* (default), the rgba\n array will be floats in the 0-1 range; if it is *True*,\n the returned rgba array will be uint8 in the 0 to 255 range.\n\n If norm is False, no normalization of the input data is\n performed, and it is assumed to be in the range (0-1).\n\n \"\"\"\n # First check for special case, image input:\n try:\n if x.ndim == 3:\n if x.shape[2] == 3:\n if alpha is None:\n alpha = 1\n if x.dtype == np.uint8:\n alpha = np.uint8(alpha * 255)\n m, n = x.shape[:2]\n xx = np.empty(shape=(m, n, 4), dtype=x.dtype)\n xx[:, :, :3] = x\n xx[:, :, 3] = alpha\n elif x.shape[2] == 4:\n xx = x\n else:\n raise ValueError(\"third dimension must be 3 or 4\")\n if xx.dtype.kind == 'f':\n if norm and (xx.max() > 1 or xx.min() < 0):\n raise ValueError(\"Floating point image RGB values \"\n \"must be in the 0..1 range.\")\n if bytes:\n xx = (xx * 255).astype(np.uint8)\n elif xx.dtype == np.uint8:\n if not bytes:\n xx = xx.astype(np.float32) / 255\n else:\n raise ValueError(\"Image RGB array must be uint8 or \"\n \"floating point; found %s\" % xx.dtype)\n return xx\n except AttributeError:\n # e.g., x is not an ndarray; so try mapping it\n pass\n\n # This is the normal case, mapping a scalar array:\n x = ma.asarray(x)\n if norm:\n x = self.norm(x)\n rgba = self.cmap(x, alpha=alpha, bytes=bytes)\n return rgba\n\n def set_array(self, A):\n \"\"\"Set the image array from numpy array *A*.\n\n Parameters\n ----------\n A : ndarray\n \"\"\"\n self._A = A\n self.update_dict['array'] = True\n\n def get_array(self):\n 'Return the array'\n return self._A\n\n def get_cmap(self):\n 'return the colormap'\n return self.cmap\n\n def get_clim(self):\n 'return the min, max of the color limits for image scaling'\n return self.norm.vmin, self.norm.vmax\n\n def set_clim(self, vmin=None, vmax=None):\n \"\"\"\n set the norm limits for image scaling; if *vmin* is a length2\n sequence, interpret it as ``(vmin, vmax)`` which is used to\n support setp\n\n ACCEPTS: a length 2 sequence of floats; may be overridden in methods\n that have ``vmin`` and ``vmax`` kwargs.\n \"\"\"\n if vmax is None:\n try:\n vmin, vmax = vmin\n except (TypeError, ValueError):\n pass\n if vmin is not None:\n self.norm.vmin = colors._sanitize_extrema(vmin)\n if vmax is not None:\n self.norm.vmax = colors._sanitize_extrema(vmax)\n self.changed()\n\n def set_cmap(self, cmap):\n \"\"\"\n set the colormap for luminance data\n\n Parameters\n ----------\n cmap : colormap or registered colormap name\n \"\"\"\n cmap = get_cmap(cmap)\n self.cmap = cmap\n self.changed()\n\n def set_norm(self, norm):\n \"\"\"Set the normalization instance.\n\n Parameters\n ----------\n norm : `.Normalize`\n \"\"\"\n if norm is None:\n norm = colors.Normalize()\n self.norm = norm\n self.changed()\n\n def autoscale(self):\n \"\"\"\n Autoscale the scalar limits on the norm instance using the\n current array\n \"\"\"\n if self._A is None:\n raise TypeError('You must first set_array for mappable')\n self.norm.autoscale(self._A)\n self.changed()\n\n def autoscale_None(self):\n \"\"\"\n Autoscale the scalar limits on the norm instance using the\n current array, changing only limits that are None\n \"\"\"\n if self._A is None:\n raise TypeError('You must first set_array for mappable')\n self.norm.autoscale_None(self._A)\n self.changed()\n\n def add_checker(self, checker):\n \"\"\"\n Add an entry to a dictionary of boolean flags\n that are set to True when the mappable is changed.\n \"\"\"\n self.update_dict[checker] = False\n\n def check_update(self, checker):\n \"\"\"\n If mappable has changed since the last check,\n return True; else return False\n \"\"\"\n if self.update_dict[checker]:\n self.update_dict[checker] = False\n return True\n return False\n\n def changed(self):\n for key in self.update_dict:\n self.update_dict[key] = True\n self.stale = True\n"
]
| [
[
"numpy.uint8",
"numpy.ma.asarray",
"numpy.empty"
]
]
|
yuningkang/APIRecX | [
"aaef5f3f0b669d7a907ddb3273e6658c9267c68a"
]
| [
"baseline/lstm/model/RNN_Common.py"
]
| [
"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass RnnCommon(nn.Module):\n def __init__(self,\n input_size,\n hidden_size,\n layer_num,\n batch_first,\n drop_out = 0.0,\n biderction=True,\n rnn_type = \"LSTM\"\n ):\n super(RnnCommon,self).__init__()\n\n self._rnn_type =rnn_type\n self._input_size = input_size\n self._hidden_size = hidden_size\n self._layer_num = layer_num\n self._bidirection = biderction\n self._batch_first = batch_first\n self._num_direction == 2 if self._bidirection else 1\n\n if self._rnn_type == \"LSTM\":\n self._rnn_cell = nn.LSTMCell\n elif self._rnn_type == \"RNN\":\n self._rnn_cell = nn.RNNCell\n elif self._rnn_type == \"GRU\":\n self._rnn_cell = nn.GRUCell\n\n #ๅฎไนๅๅๅๅๅ็cellๅฎ็ฐๅคๅฑ\n self._fw_cell = nn.ModuleList()\n self._bw_cell = nn.ModuleList()\n\n for i in range(self._layer_num):\n layer_input_size = self._input_size if i == 0 else self._hidden_size*self._num_direction\n self._fw_cell.append(self._rnn_cell(layer_input_size,self._hidden_size))\n if self._bidirection:\n self._bw_cell.append(self._rnn_cell(layer_input_size,self._hidden_size))\n\n\n\n def _forward(self,cell,input,init_hidden,mask):\n if self._batch_first:\n input = input.transpose(0,1)\n seq_len = input.shape[1]\n output = []\n for i in range(seq_len):\n if self._rnn_type == \"LSTM\":\n h1,c1 = cell(input[i],init_hidden)\n h1 = h1 * mask[i]\n c1 = c1 * mask[i]\n output.append(h1)\n init_hidden =(h1,c1)\n else:\n h1 = cell(input[i],init_hidden)\n h1 = h1 * mask[i]\n output.append(h1)\n init_hidden = h1\n output = torch.stack(output,dim=0)\n\n return output,init_hidden\n\n def _backward(self,cell,input,init_hidden,mask):\n if self._batch_first:\n input = input.transpose(0,1)\n seq_len = input.shape[0]\n output = []\n for i in reversed(range(seq_len)):\n if self._rnn_type == \"LSTM\":\n h1,c1= cell(input[i],init_hidden)\n h1 = h1 * mask[i]\n c1 = c1 * mask[i]\n output.append(h1)\n init_hidden = (h1,c1)\n else:\n output.append(h1)\n init_hidden = h1\n\n output = torch.stack(output,dim=0)\n reversed()\n return output,init_hidden\n\n\n\n\n def forward(self, inputs,mask,init_hidden = None):\n '''\n\n :param inputs: [batch,seq,input_size] if batch_first\n :param init_hideen:\n :param mask :[batch,seq]\n :return:\n '''\n hn = []\n cn = []\n inputs = inputs.transpose(0,1) if self._batch_first else inputs\n mask = mask.transpose(0,1)\n mask= mask.unsuqueeze(dim=2).expand((-1,-1,self._hidden_size))\n if init_hidden == None:\n init_hidden =init_hidden(inputs.shape[1])\n for i in range(self._layer_num):\n #fw_output,bw_output of shape [seq_len,batch,hidden_size]\n #fw_hn of shape [batch_size,hidden_size]\n fw_output,fw_hidden =self._forward(self._fw_cell[i],inputs,init_hidden,mask)\n if self._bidirection:\n bw_output,bw_hidden = self._backward(self._bw_cell[i],inputs,init_hidden,mask)\n\n if self._rnn_type == \"LSTM\":\n hn.append(torch.cat((fw_hidden[0],bw_hidden[0]),dim=1) if self._bidirection else fw_hidden[0])\n cn.append(torch.cat((fw_hidden[1],bw_hidden[1]),dim=1) if self._bidirection else fw_hidden[1])\n else:\n hn.append(torch.cat((fw_hidden,bw_hidden),dim=1) if self._bidirection else fw_hidden)\n\n\n inputs = torch.cat((fw_output,bw_output),dim=2)\n\n output = inputs.transpose(0,1)\n hn = torch.stack(hn,dim=0)\n if self._rnn_type ==\"LSTM\":\n cn = torch.stack(cn,dim=0)\n hidden = (hn,cn)\n else:\n hidden = hn\n\n return output,hidden\n\n\n def init_hidden(self,batch_size):\n h0 = torch.zeros(batch_size,self._hidden_size)\n if self._rnn_type == \"LSTM\":\n return h0,h0\n\n else :\n return h0\n"
]
| [
[
"torch.stack",
"torch.nn.ModuleList",
"torch.cat",
"torch.zeros"
]
]
|
RoxanneYang/STAM | [
"7334ec13eae90802f04367ffebdffe8d6d70738f"
]
| [
"analyzer/utils.py"
]
| [
"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Mar 2 10:14:23 2018\n\n@author: admin\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport statsmodels.api as sm\nimport pymysql\nimport time\nfrom functools import wraps\nfrom datetime import datetime\n\nconfig = {\n 'host': 'magiquant.mysql.rds.aliyuncs.com',\n 'port': 3306,\n 'user':'haoamc',\n 'passwd':'voucher.seem.user',\n 'db': 'quant'\n }\ndef timer(function):\n @wraps(function)\n def function_timer(*args, **kwargs):\n t0 = time.time()\n result = function(*args, **kwargs)\n t1 = time.time()\n print (\"Total time running %s: %s seconds\" %(function.__name__, str(round((t1-t0), 2))))\n return result\n return function_timer\n \n@timer \ndef winsorize(ts, method, alpha, nsigma):\n \"\"\"\n recognize extreme value and replace these with up_value or down_value\n \n Params:\n ts: \n pd.Series, cross section factor\n method:\n 'quantitles':\n data under alpha/2 percentile or above (1 - alpha/2) \n percentile as extreme values\n 'mv':\n data deviate the mean beyond nsigma * std as extreme values\n this method may need several times\n 'mad':\n use Median Absolute Deviation(MAD) instead of mean\n md = median(ts)\n MAD = median(|ts - md|)\n use 1.483*MAD instead of std\n this method is more robust than 'mv'\n 'boxplot':\n IOR = Q3 - Q1\n data beyong [Q1 - 3 * IQR, Q3 + 3 * IQR] as abnormal values\n boxplot is not sensitive with extreme values\n when tha data is positive skew and right fat tailed, too much \n data will divide into extreme values\n 'boxplot_skew_adj':\n md = median(ts)\n mc = median(((x_i - md) - (md - x_j)) / (x_i - x_j))\n where x_i > md and x_j < md\n L = ... and U = ...\n [optional]:\n alpha: valid for method = 'quantitles'\n nsigma: vallid for method = 'mv' and 'mad'\n Return:\n ts,pd.Series \n \"\"\"\n # look for the location of nan\n nan_label = np.where(np.isnan(ts))[0]\n ts[nan_label] = 0\n if method == 'quantitles':\n d = ts.quantile(alpha / 2.0)\n u = ts.quantile(1 - alpha / 2.0)\n elif method == 'mv':\n sigma = ts.std() \n d = ts.mean() - sigma * nsigma\n u = ts.mean() + sigma * nsigma\n elif method == 'mad':\n md = ts.median()\n MAD = (ts - md).abs().median() * 1.483\n d = md - MAD * nsigma\n u = md + MAD * nsigma\n elif method == 'boxplot':\n Q1 = ts.quantile(0.25)\n Q3 = ts.quantile(0.75)\n IQR = Q3 - Q1\n d = Q1 - 3 * IQR\n u = Q3 + 3 * IQR\n elif method == 'boxplot_skew_adj':\n md = ts.median()\n x_u, x_d = ts[ts > md], ts[ts < md]\n x_u = x_u.reset_index(drop = True)\n x_d = x_d.reset_index(drop = True)\n h = np.zeros((len(x_u),len(x_d)))\n for i in range(len(x_u)):\n for j in range(len(x_d)):\n h[i,j] = (x_u.iloc[i] + x_d.iloc[j] - 2 * md)/ \\\n (x_u.iloc[i] - x_d.iloc[j])\n mc = np.median(h.flatten())\n Q1 = ts.quantile(0.25)\n Q3 = ts.quantile(0.75)\n IQR = Q3 - Q1\n if mc >= 0:\n d = Q1 - 1.5 * np.exp(-3.5 * mc) * IQR\n u = Q1 + 1.5 * np.exp(4 * mc) * IQR\n else:\n d = Q1 - 1.5 * np.exp(-4 * mc) * IQR\n u = Q1 + 1.5 * np.exp(3.5 * mc) * IQR\n else:\n raise ValueError('No method called: ', method)\n ts[ts > u] = u\n ts[ts < d] = d \n ts[nan_label] = np.nan \n return ts\n \n@timer\ndef standardize(ts,cap,method):\n \"\"\"\n use cap_weighted mean to standardize the factor\n \n Params:\n ts:\n pd.Series, cross section factor data\n cap:\n pd.Series, cross section cap data, the secID is matched one by one\n available for cap_weighted\n method:\n 'cap_weighted' or 'average'\n Return:\n ts:\n pd.Series \n \"\"\"\n nan_label = np.where(np.isnan(ts))[0]\n ts[nan_label] = 0\n if method == 'cap_weighted':\n mean = np.average(ts, weights = cap)\n else:\n mean = np.average(ts)\n ts = (ts - mean) / ts.std()\n ts[nan_label] = np.nan\n return ts\n@timer\ndef alpha_preprocess(df):\n \"\"\"\n Params:\n df: multi-index,['date','ID']\n \"\"\"\n df1 = df.unstack()\n df_mod = pd.DataFrame([])\n for i in range(np.size(df1,0)):\n ts = df1.iloc[i,:]\n ts_win = winsorize(ts, 'boxplot', None, None)\n ts_stand = standardize(ts_win,None,'average')\n df_mod = pd.concat([df_mod,pd.DataFrame(ts_stand)], axis = 0)\n df_mod.columns = list(df1)\n df_mod.index = df1.index.tolist()\n df2 = df.stack()\n return df2\n \ndef style_stand(df,cap):\n for i in range(np.size(df,1)):\n df.iloc[:,i] = standardize(df.iloc[:,i],cap,'cap_weighted')\n return df\n\ndef orthogonal(df,indus,style):\n \"\"\"\n orthogonal\n factors which gets rid of the effect of industry and style factors\n \n \"\"\"\n \ndef get_industry_matrix(industries):\n \"\"\"\n get the industry dummy matrix\n Param:\n industries: \n pd.Series,index = secID,value = ่กไธๅ็งฐ\n Return:\n df:\n pd.DataFrame,industry dummy matrix\n \"\"\"\n sec_ids = industries.index.tolist()\n nb_sec_ids = len(sec_ids)\n unique_industry = industries.unique()\n nb_unique_industry = len(unique_industry)\n matrix = np.zeros([nb_sec_ids,nb_unique_industry])\n for i in range(nb_sec_ids):\n col_index = np.where(unique_industry == industries[i])[0]\n matrix[i,col_index] = 1.0 \n df = pd.DataFrame(matrix)\n df.index = sec_ids\n df.columns = unique_industry.tolist() \n return df \n\n \ndef get_resi_factor(factor,indus,style):\n \"\"\"\n compute the pure factor values which gets rid of the effect of industries and style factor\n ------------------------\n Param:\n factor:\n pd.DataFrame,multi-index, index = ['date','secID'] \n indus:\n pd.DataFrame, industry dummy matirx, index = secID\n style:\n pd.DataFrame,columns = [style factor], index = secID\n Return:\n pure factor\n \"\"\"\n cap = pd.DataFrame(style['Size'])\n Y = factor.unstack()\n X_temp = pd.concat([indus,style], axis = 1)\n# X = sm.add_constant(X_temp)\n wls_model = sm.WLS(Y,X_temp,weights = cap)\n results = wls_model.fit()\n factor_resi = results.resid\n return factor_resi\n\ndef get_pure_return(ret,indus,style,cap):\n \"\"\"\n compute the ret which gets rid of indus effects and style effects\n -------------\n Param:\n ret:\n index = 'secID', ret of secID\n indus:\n pd.DataFrame, industry dummy matrix, index = secID\n style:\n pd.DataFrame,columns = [style factor], index = secID\n\n Return:\n \n \n \"\"\"\n\n Y = ret\n X_temp = pd.concat([indus,style], axis = 1)\n# X = sm.add_constant(X_temp)\n wls_model = sm.WLS(Y,X_temp,weights = cap)\n results = wls_model.fit()\n ret_resi = results.resid\n return ret_resi\n\n\ndef extract_part_from_all(secID, df, name):\n '''\n ไปๅ
ๅซsecID็dataframeไธญๆๅ็ปๅฎsecID็ๆฐๆฎ\n param secID: list of str\n param df: dataframe,ๅ
ถไธญๆไธๅไธบๅ
ๅซไธ่ฟฐsecID็ๆดๅคง่ๅด็secID\n param name: str,dfไธญsecID็ๅๅ u'name'ๆ ผๅผ\n '''\n label = [df[df[name].str.contains(secID[i])].index.tolist() for i in range(len(secID))]\n label_list = list(np.array(label).flatten())\n df_part = df.iloc[label_list, :]\n df_return = df_part.reset_index(drop=True)\n return df_return\n\n \n\n\nclass Connector:\n def __init__(self):\n# if db == 'quant':\n self.config = {\n 'host': 'magiquant.mysql.rds.aliyuncs.com',\n 'port': 3306,\n 'user':'haoamc',\n 'passwd':'voucher.seem.user',\n 'db': 'quant'\n }\n \n self.conn = pymysql.connect(**self.config)\n self.cursor = self.conn.cursor()\n \n def __del__(self):\n self.conn.close()\n \n def get_tradedate(self,begin,end):\n \"\"\"\n get tradedate between begin date and end date\n Params:\n begin:\n str,eg: '1999-01-01'\n end:\n str,eg: '2017-12-31'\n Return:\n pd.DataFrame\n \"\"\"\n query = \"SELECT calendar_date FROM trade_calendar WHERE is_trade_day= 1 AND \\\n calendar_date >= '%s' AND calendar_date <= '%s';\"%(begin,end)\n self.cursor.execute(query)\n data = pd.DataFrame(list(self.cursor.fetchall()))\n data.columns = ['date']\n# data = pd.DataFrame(pd.to_datetime(data['date']))\n return data\n \n def get_style_factor_from_sql(self,mode,begin,end,table_name):\n \"\"\"\n get barra style factor from sql,including Beta, Momentum,Size,EY,RV,Growth,\\\n BP,Leverage,Liquidity\n ----------------------------------\n Params:\n begin:\n str,eg: '1999-01-01'\n end:\n str,eg: '2017-12-31'\n Return:\n pd.DataFrame,multi-index \n \"\"\"\n if mode == 0 :\n query = \"SELECT * FROM %s WHERE trade_date = '%s';\"%(table_name,begin)\n else:\n query = \"SELECT * FROM barra_style_factors_mod WHERE trade_date >= '%s' AND\\\n trade_date <= '%s';\"%(begin,end)\n self.cursor.execute(query)\n data = pd.DataFrame(list(self.cursor.fetchall()))\n data.columns = ['date','secID','Beta','Momentum','Size','EY','RV','Growth',\\\n 'BP','Leverage','Liquidity']\n \n# data['date'] = pd.to_datetime(data['date'])\n# data = data.set_index('ID')\n# data = data.set_index([data['date'], data.index],drop = True)\n del data['date']\n data = data.set_index('secID')\n return data\n \n def get_indus(self,date):\n \"\"\"\n get all industry information\n ------------------------\n Params:\n date:str, eg:\"2010-01-01\"\n Returns:\n pd.Series,index = secID,columns = ['sectorID']\n \"\"\"\n query = \"SELECT stock_id,industry_sw FROM stock_sector WHERE trade_date = '%s';\"%(date)\n self.cursor.execute(query)\n data = pd.DataFrame(list(self.cursor.fetchall()))\n data.columns = ['secID','sectorID']\n data = data.set_index('secID')\n return data\n \n def get_ret(self,date):\n \"\"\"\n get all stocks' daily ret\n ----------------------\n Params:\n date: str,eg: '2010-01-01'\n Return:\n \n \"\"\"\n query = \"SELECT stock_id, PctChg FROM stock_market_data WHERE trade_date = '%s';\"%(date)\n self.cursor.execute(query)\n data = pd.DataFrame(list(self.cursor.fetchall()))\n data.columns = ['secID','ret']\n data = data.set_index('secID')\n return data\n \n def get_cap(self,date):\n \"\"\"\n get all stocks' daily cap\n ------------------------\n Params:\n date:str,eg:\"2010-01-01\"\n Return:\n pd.DataFrame,columns = ['secID','TotalValue']\n \n \"\"\"\n query = \"SELECT stock_id,TotalValue FROM stock_alpha_factors WHERE trade_date = '%s';\"%(date)\n self.cursor.execute(query)\n data = pd.DataFrame(list(self.cursor.fetchall()))\n data.columns = ['secID','cap']\n data = data.set_index('secID')\n return data\n \n\n def get_ret_daily(self,date,stocklist):\n \"\"\"\n get the daily ret of certain stocklist\n \"\"\"\n ret_all = self.get_ret(date)\n ret = extract_part_from_all(stocklist,ret_all,'secID')\n ret = ret.set_index('secID')\n return ret\n \n def get_cap_daily(self,date,stocklist):\n \"\"\"\n get the daily cap of certain stocklist\n Params:\n date:\n str, eg:\"2010-01-01\"\n stocklist:\n list of str\n Return:\n pd.DataFrame\n \"\"\"\n cap_all = self.get_cap(date)\n cap = extract_part_from_all(stocklist,cap_all,'secID')\n cap = cap.set_index('secID')\n return cap\n \n \n def get_alpha(self,date,factor_name):\n \"\"\"\n get the alpha factor from sql\n \"\"\"\n query = \"SELECT stock_id,%s FROM alpha_raw WHERE trade_date = '%s';\"%(factor_name,date)\n self.cursor.execute(query)\n data = pd.DataFrame(list(self.cursor.fetchall()))\n data.columns = ['secID',factor_name]\n return data\n\n \n\nif __name__ == '__main__':\n# #############################################################\n# alpha = pd.read_csv('..\\\\alpha\\\\data\\\\1.csv')\n# alpha = alpha.set_index(['date','ID'])\n# alpha = alpha_preprocess(alpha)\n \n #################### get standard style factor and pure ret################\n #####################upload only end 2017-08-09################################\n connector = Connector()\n trade_date = connector.get_tradedate('2012-10-22','2012-10-24') \n style = pd.DataFrame([])\n ret_resi_all = pd.DataFrame([])\n# for i in range(len(trade_date)): \n for i in range(1):\n date = trade_date.iloc[i,0]\n ret = connector.get_ret(date)\n indus = connector.get_indus(date)\n date_str = datetime.strptime(str(date),\"%Y-%m-%d\").strftime('%Y%m%d')\n style_factor = connector.get_style_factor_from_sql(0,date_str,None,'barra_style_factors')\n cap = connector.get_cap(date)\n data_all = pd.concat([ret,indus,style_factor,cap], axis = 1, join = 'inner')\n \n industry_matrix = get_industry_matrix(data_all['sectorID'])\n style_factor_stand = style_stand(pd.DataFrame(data_all.iloc[:,2:11]),data_all['cap'])\n \n ret_resi = get_pure_return(pd.DataFrame(data_all['ret']),industry_matrix,style_factor_stand,data_all['cap'])\n \n style_factor_stand['date'] = date\n style = pd.concat([style,style_factor_stand], axis = 0)\n# ret_resi_temp = pd.DataFrame(ret_resi)\n# ret_resi_temp.columns = ['ret']\n# ret_resi_temp['date'] = date\n# ret_resi_all = pd.concat([ret_resi_all,ret_resi_temp], axis = 0)\n print(i)\n# style.to_csv('..\\\\analyzer\\\\style_temp3.csv')\n# ret_resi_all.to_csv('..\\\\analyzer\\\\ret3.csv')\n \n\n \n \n\n \n \n \n "
]
| [
[
"pandas.concat",
"numpy.isnan",
"pandas.DataFrame",
"numpy.size",
"numpy.exp",
"numpy.array",
"numpy.average",
"numpy.zeros",
"numpy.where"
]
]
|
haraldschilly/riemann_book | [
"46698d695c43da1ad51cd10249240b2531ee578e"
]
| [
"utils/animation_tools.py"
]
| [
"\"\"\"\n*NOTE:* This version is slightly modified from the one in\n $CLAW/visclaw/src/python/visclaw/animation_tools.py\n\nSome functions requires JSAnimation, either from Clawpack \nor by installing it separately from\n https://github.com/jakevdp/JSAnimation\n\nThis animation_tools module contains tools to create animations in Python and\nJupyter notebooks.\n\nThree types of animations are supported:\n - using the ipywidget interact to create a figure with a slider bar,\n - using JSAnimation to create Javascript code that loops over a set of\n images and adds controls to play as an animation.\n - creation of mp4 files using ffmpeg (provided this package is installed).\n\nThe set of images to combine in an animation can be specified as a\nlist of images, a list of `matplotlib` figures, or a directory of\n`png` or other image files.\n\nUtilities are provided to convert between these.\n\nFunctions are provided to create inline animations in Jupyter notebooks or\nstand-alone files that can be viewed in other ways, including\n - An html file with the JSAnimation version,\n - A mp4 file,\n - A reStructured text file with the JSAnimation for inclusion in Sphinx docs.\n\nThe utility function make_anim_from_plotdir can be used to convert the png\nfiles in a Clawpack _plots directory into standalone animations of the types\nlisted above. See the file make_anim.py for an example of how this can be\ninvoked from an applications directory.\n\nSee also:\n https://ipywidgets.readthedocs.io/en/latest/#ipywidgets\n https://github.com/jakevdp/JSAnimation\n\nMore documentation of these functions is needed and they can probably be\nimproved.\n\n\"\"\"\n\n# use Python 3 style print function rather than Python 2 print statements:\nfrom __future__ import print_function\n\nfrom IPython.display import display\nfrom matplotlib import image, animation\nfrom matplotlib import pyplot as plt\nfrom ipywidgets import interact, interact_manual\nimport ipywidgets\n\ntry:\n from JSAnimation import IPython_display\nexcept:\n try:\n from clawpack.visclaw.JSAnimation import IPython_display\n except:\n print(\"*** Warning: JSAnimation not found\")\n \n\n\ndef make_plotdir(plotdir='_plots', clobber=True):\n \"\"\"\n Utility function to create a directory for storing a sequence of plot\n files, or if the directory already exists, clear out any old plots.\n If clobber==False then it will abort instead of deleting existing files.\n \"\"\"\n\n import os\n if os.path.isdir(plotdir):\n if clobber:\n os.system(\"rm %s/*\" % plotdir)\n else:\n raise IOError('*** Cannot clobber existing directory %s' % plotdir)\n else:\n os.system(\"mkdir %s\" % plotdir)\n print(\"Figure files for each frame will be stored in \", plotdir)\n\n\ndef save_frame(frameno, plotdir='_plots', fname_base='frame', format='png',\n verbose=False, **kwargs):\n \"\"\"\n After giving matplotlib commands to create the plot for a single frame\n of the desired animation, this can be called to save the figure with\n the appropriate file name such as _plots/frame00001.png.\n \"\"\"\n\n plt.draw()\n filename = '%s/%s%s.%s' % (plotdir, fname_base, str(frameno).zfill(5), format)\n plt.savefig(filename, **kwargs)\n if verbose:\n print(\"Saved \",filename)\n\n\ndef make_anim(plotdir, fname_pattern='frame*.png', figsize=(10,6), dpi=None):\n \"\"\"\n Assumes that a set of frames are available as png files in directory _plots,\n numbered consecutively, e.g. frame0000.png, frame0001.png, etc.\n\n Creates an animation based display each frame in turn, and returns anim.\n\n You can then display anim in an IPython notebook, or\n call make_html(anim) to create a stand-alone webpage.\n \"\"\"\n\n import matplotlib\n\n if matplotlib.backends.backend in ['MacOSX']:\n print(\"*** animation.FuncAnimation doesn't work with backend %s\"\n % matplotlib.backends.backend)\n print(\"*** Suggest using 'Agg'\")\n return\n\n import glob # for finding all files matching a pattern\n\n # Find all frame files:\n filenames = glob.glob('%s/%s' % (plotdir, fname_pattern))\n\n # sort them into increasing order:\n filenames=sorted(filenames)\n\n fig = plt.figure(figsize=figsize, dpi=dpi)\n ax = fig.add_axes([0, 0, 1, 1])\n ax.axis('off') # so there's not a second set of axes\n im = plt.imshow(image.imread(filenames[0]))\n\n def init():\n im.set_data(image.imread(filenames[0]))\n return im,\n\n def animate(i):\n image_i=image.imread(filenames[i])\n im.set_data(image_i)\n return im,\n\n anim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=len(filenames), interval=200,\n blit=True)\n\n return anim\n\n\ndef JSAnimate_images(images, figsize=(10,6), dpi=None):\n \"Turn a list of images into a JSAnimation.\"\n\n import matplotlib\n\n if matplotlib.backends.backend in ['MacOSX']:\n print(\"*** animation.FuncAnimation doesn't work with backend %s\"\n % matplotlib.backends.backend)\n print(\"*** Suggest using 'Agg'\")\n return\n\n fig = plt.figure(figsize=figsize, dpi=dpi)\n ax = fig.add_axes([0, 0, 1, 1])\n ax.axis('off') # so there's not a second set of axes\n\n im = plt.imshow(images[0])\n\n def init():\n im.set_data(images[0])\n return im,\n\n def animate(i):\n im.set_data(images[i])\n return im,\n\n anim = animation.FuncAnimation(fig, animate, init_func=init,\n frames=len(images), interval=200,\n blit=True)\n\n plt.close(fig)\n return anim\n\n\ndef make_html(anim, file_name='anim.html', title=None, raw_html='',\n fps=None, embed_frames=True, default_mode='once'):\n \"\"\"\n Take an animation created by make_anim and convert it into a stand-alone\n html file.\n \"\"\"\n try:\n from JSAnimation.IPython_display import anim_to_html\n except:\n try:\n from clawpack.visclaw.JSAnimation.IPython_display import anim_to_html\n except:\n print(\"*** Warning: JSAnimation not found, cannot import anim_to_html\")\n\n html_body = anim_to_html(anim, fps=fps, embed_frames=embed_frames, \\\n default_mode=default_mode)\n\n html_file = open(file_name,'w')\n html_file.write(\"<html>\\n <h1>%s</h1>\\n\" % title)\n html_file.write(raw_html)\n html_file.write(html_body)\n html_file.close()\n print(\"Created %s\" % file_name)\n\n\ndef make_rst(anim, file_name='anim.rst',\n fps=None, embed_frames=True, default_mode='once'):\n \"\"\"\n Take an animation created by make_anim and convert it into an rst file\n (reStructuredText, for inclusion in Sphinx documentation, for example).\n \"\"\"\n try:\n from JSAnimation.IPython_display import anim_to_html\n except:\n try:\n from clawpack.visclaw.JSAnimation.IPython_display import anim_to_html\n except:\n print(\"*** Warning: JSAnimation not found, cannot import anim_to_html\")\n\n rst_body = anim_to_html(anim, fps=fps, embed_frames=embed_frames, \\\n default_mode=default_mode)\n\n rst_body = rst_body.split('\\n')\n\n rst_file = open(file_name,'w')\n rst_file.write(\".. raw:: html\\n\")\n for line in rst_body:\n rst_file.write(\" %s\\n\" % line)\n rst_file.close()\n print(\"Created %s\" % file_name)\n print(\"Imbed this in another rst file using:\")\n print(\".. include:: %s\" % file_name)\n\n\ndef make_mp4(anim, file_name='anim.mp4',\n fps=None, embed_frames=True, default_mode='once'):\n \"\"\"\n Take an animation and covert to mp4 file using ffmpeg, which must be\n installed.\n \"\"\"\n import os\n\n if not animation.writers.is_available('ffmpeg'):\n print(\"** ffmpeg must be installed to create mp4 file\")\n return\n\n if os.path.splitext(file_name)[1] != '.mp4':\n print(\"*** Might not work if file extension is not .mp4\")\n if fps is None:\n fps = 3\n writer = animation.writers['ffmpeg'](fps=fps)\n anim.save(file_name, writer=writer)\n print(\"Created %s\" % file_name)\n\n\ndef read_images(plotdir, fname_pattern='*.png'):\n\n import glob, os\n images = []\n files = glob.glob(os.path.join(plotdir, fname_pattern))\n for file in files:\n im = plt.imread(file)\n images.append(im)\n return images\n\ndef save_images(images, figsize=(8,6), plotdir='_plots', clobber=True,\n fname_base='frame', format='png', verbose=False, **kwargs):\n\n make_plotdir(plotdir=plotdir, clobber=clobber)\n for frameno, img in enumerate(images):\n fig = imshow_noaxes(img, figsize)\n filename = '%s/%s%s.%s' % (plotdir, fname_base, str(frameno).zfill(5), format)\n plt.savefig(filename, format=format, **kwargs)\n plt.close(fig)\n if verbose:\n print(\"Saved \",filename)\n\ndef save_figs(figs, plotdir='_plots', clobber=True,\n fname_base='frame', format='png', verbose=False, **kwargs):\n\n make_plotdir(plotdir=plotdir, clobber=clobber)\n for frameno,fig in enumerate(figs):\n filename = '%s/%s%s.%s' % (plotdir, fname_base, str(frameno).zfill(5), format)\n fig.savefig(filename, format=format, **kwargs)\n plt.close(fig)\n if verbose:\n print(\"Saved \",filename)\n\n\ndef make_image(fig, **kwargs):\n \"\"\"\n Take a matplotlib figure *fig* and convert it to an image *im* that\n can be viewed with imshow.\n \"\"\"\n\n import io\n png = io.BytesIO()\n fig.savefig(png,format='png', **kwargs)\n png.seek(0)\n im = plt.imread(png)\n return im\n\ndef make_images(figs, **kwargs):\n \"\"\"\n Take a list of matplotlib figures *figs* and convert to list of images.\n \"\"\"\n\n images = []\n for fig in figs:\n im = make_image(fig, **kwargs)\n images.append(im)\n return images\n\ndef imshow_noaxes(im, figsize=(8,6)):\n fig = plt.figure(figsize=figsize)\n ax = plt.axes()\n plt.imshow(im)\n ax.axis('off')\n return fig\n\ndef interact_animate_images(images, figsize=(10,6), manual=False, TextInput=False):\n \"Create an interact that loops over all the frames contained in a list of images.\"\n\n def display_frame(frameno):\n imshow_noaxes(images[frameno], figsize=figsize)\n plt.show()\n\n if TextInput:\n if TextInput:\n print(\"Valid frameno values: from %i to %i\" % (0,len(images)-1))\n widget = ipywidgets.IntText(min=0,max=len(images)-1, value=0)\n else:\n widget = ipywidgets.IntSlider(min=0,max=len(images)-1, value=0)\n\n if manual:\n interact_manual(display_frame, frameno=widget)\n else:\n interact(display_frame, frameno=widget)\n\ndef interact_animate_figs(figs, manual=False, TextInput=False):\n \"\"\"\n Create an interact that loops over all the frames contained in a list of figures.\n\n Passing in the argument `manual=True` will use the widget `interact_manual`\n instead of `interact`. This refrains from updating the image as you move\n the slider bar. Instead you move the slider as desired and then click on\n the `Run` button to re-display the image. This is useful if there are many\n frames and you want to be able to jump to around without all the\n intermediate frames being displayed, which can slow down the response\n significantly.\n\n The argument `TextInput=True` can be specified to produce a text input cell\n rather than a slider bar.\n \"\"\"\n\n def display_frame(frameno):\n display(figs[frameno])\n\n if TextInput:\n widget = ipywidgets.IntText(min=0,max=len(figs)-1, value=0)\n else:\n widget = ipywidgets.IntSlider(min=0,max=len(figs)-1, value=0)\n\n if manual:\n if TextInput:\n print(\"Valid frameno values: from %i to %i\" % (0,len(figs)-1))\n interact_manual(display_frame, frameno=widget)\n else:\n interact(display_frame, frameno=widget)\n\n\ndef animate_figs(figs, style='ipywidgets', figsize=(10,6), **kwargs):\n \"\"\"\n Create an animation from a set of figures,\n style = 'ipywidgets' or 'JSAnimation'\n returns anim\n \"\"\"\n\n images = make_images(figs)\n\n if style == 'ipywidgets':\n anim = interact_animate_images(images, figsize=figsize, **kwargs)\n elif style == 'JSAnimation':\n anim = JSAnimate_images(images, figsize=figsize, **kwargs)\n else:\n raise ValueError('** Unrecognized style = %s' % style)\n\n return anim\n\ndef make_anim_from_plotdir(plotdir='_plots', fignos='all', outputs=[],\n file_name_prefix='', figsize=(5,4), dpi=None,\n fps=5):\n\n \"\"\"\n After running `make plots` using VisClaw, convert the png files in\n the plots directory into an animation, and perhaps also\n stand-alone files that can be embedded in webpages or Sphinx documentation.\n\n outputs can be a list containing any of 'mp4','html','rst'\n\n Call this from a script that starts with:\n import matplotlib\n matplotlib.use('Agg')\n \"\"\"\n import glob, re\n\n if fignos == 'all':\n # determine what fignos are used in the plotdir\n movie_files = glob.glob(plotdir + '/movie*html')\n if len(movie_files) == 0:\n print('No movie files found in %s' % plotdir)\n return\n\n fignos = []\n regexp = re.compile(r\"movie[^ ]*fig(?P<figno>[0-9]*)[.html]\")\n for f in movie_files:\n result = regexp.search(f)\n fignos.append(result.group('figno'))\n\n print(\"Found these figures: %s\" % fignos)\n\n for figno in fignos:\n\n fname_pattern = 'frame*fig%s.png' % figno\n anim = make_anim(plotdir, fname_pattern, figsize, dpi)\n\n if 'mp4' in outputs:\n file_name = file_name_prefix + 'fig%s.mp4' % figno\n make_mp4(anim, file_name, fps=fps,\n embed_frames=True, default_mode='once')\n\n if 'html' in outputs:\n file_name = file_name_prefix + 'fig%s.html' % figno\n make_html(anim, file_name, fps=fps,\n embed_frames=True, default_mode='once')\n\n if 'rst' in outputs:\n file_name = file_name_prefix + 'fig%s.rst' % figno\n make_rst(anim, file_name, fps=fps,\n embed_frames=True, default_mode='once')\n\n return anim\n"
]
| [
[
"matplotlib.pyplot.imshow",
"matplotlib.animation.writers.is_available",
"matplotlib.pyplot.imread",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.draw",
"matplotlib.pyplot.axes",
"matplotlib.image.imread",
"matplotlib.pyplot.close",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
]
|
dchabot/ophyd_hkl | [
"60cb3c3a695898d35ad7b513951bf4470a40711f"
]
| [
"tests/test_signal.py"
]
| [
"\nimport sys\nimport logging\nimport unittest\nimport threading\nimport random\nimport time\nimport copy\n\nimport numpy as np\nimport epics\n\nfrom ophyd.signal import (Signal, EpicsSignal, EpicsSignalRO)\nfrom ophyd.utils import (ReadOnlyError, TimeoutError)\n\nlogger = logging.getLogger(__name__)\n\n\nclass FakeEpicsPV(object):\n _connect_delay = (0.05, 0.1)\n _update_rate = 0.1\n fake_values = (0.1, 0.2, 0.3)\n _pv_idx = 0\n\n def __init__(self, pvname, form=None,\n callback=None, connection_callback=None,\n auto_monitor=True, enum_strs=None,\n **kwargs):\n\n self._pvname = pvname\n self._callback = callback\n self._connection_callback = connection_callback\n self._form = form\n self._auto_monitor = auto_monitor\n self._value = self.fake_values[0]\n self._connected = False\n self.enum_strs = enum_strs\n FakeEpicsPV._pv_idx += 1\n self._idx = FakeEpicsPV._pv_idx\n\n self._update = True\n\n self._lock = threading.Lock()\n self._thread = threading.Thread(target=self._update_loop)\n self._thread.setDaemon(True)\n self._thread.start()\n\n # callbacks mechanism copied from pyepics\n self.callbacks = {}\n\n if callback:\n self.add_callback(callback)\n\n def get_ctrlvars(self):\n pass\n\n @property\n def connected(self):\n return self._connected\n\n def wait_for_connection(self, timeout=None):\n if self._pvname in ('does_not_connect', ):\n return False\n\n while not self._connected:\n time.sleep(0.05)\n\n return True\n\n def _update_loop(self):\n time.sleep(random.uniform(*self._connect_delay))\n if self._connection_callback is not None:\n self._connection_callback(pvname=self._pvname, conn=True, pv=self)\n\n if self._pvname in ('does_not_connect', ):\n return\n\n self._connected = True\n last_value = None\n\n while True:\n with self._lock:\n if self._update:\n self._value = random.choice(self.fake_values)\n\n if self._value != last_value:\n sys.stdout.flush()\n self.run_callbacks()\n last_value = self._value\n\n time.sleep(self._update_rate)\n\n time.sleep(0.01)\n\n @property\n def lower_ctrl_limit(self):\n return min(self.fake_values)\n\n @property\n def upper_ctrl_limit(self):\n return max(self.fake_values)\n\n def run_callbacks(self):\n for index in sorted(list(self.callbacks.keys())):\n self.run_callback(index)\n\n def run_callback(self, index):\n fcn, kwargs = self.callbacks[index]\n kwd = dict(pvname=self._pvname,\n count=1,\n nelm=1,\n type=None,\n typefull=None,\n ftype=None,\n access='rw',\n chid=self._idx,\n read_access=True,\n write_access=True,\n value=self.value,\n )\n\n kwd.update(kwargs)\n kwd['cb_info'] = (index, self)\n if hasattr(fcn, '__call__'):\n fcn(**kwd)\n\n def add_callback(self, callback=None, index=None, run_now=False,\n with_ctrlvars=True, **kw):\n if hasattr(callback, '__call__'):\n if index is None:\n index = 1\n if len(self.callbacks) > 0:\n index = 1 + max(self.callbacks.keys())\n self.callbacks[index] = (callback, kw)\n\n if run_now:\n if self.connected:\n self.run_callback(index)\n return index\n\n def remove_callback(self, index=None):\n if index in self.callbacks:\n self.callbacks.pop(index)\n\n def clear_callbacks(self):\n self.callbacks = {}\n\n @property\n def precision(self):\n return 0\n\n @property\n def timestamp(self):\n return time.time()\n\n @property\n def pvname(self):\n return self._pvname\n\n @property\n def value(self):\n return self._value\n\n def __repr__(self):\n return '<FakePV %s value=%s>' % (self._pvname, self.value)\n\n def get(self, as_string=False, use_numpy=False,\n use_monitor=False):\n if as_string:\n\n if isinstance(self.value, list):\n if self.enum_strs:\n return [self.enum_strs[_] for _ in self.value]\n return list(self.value)\n if isinstance(self.value, str):\n return self.value\n else:\n if self.enum_strs:\n return self.enum_strs[self.value]\n return str(self.value)\n elif use_numpy:\n return np.array(self.value)\n else:\n return self.value\n\n def put(self, value, wait=False, timeout=30.0,\n use_complete=False, callback=None, callback_data=None):\n\n with self._lock:\n self._update = False\n self._value = value\n\n\nclass FakeEpicsWaveform(FakeEpicsPV):\n strings = ['abcd', 'efgh', 'ijkl']\n fake_values = [[ord(c) for c in s] + [0]\n for s in strings]\n\n\ndef setUpModule():\n epics._PV = epics.PV\n epics.PV = FakeEpicsPV\n\n\ndef tearDownModule():\n logger.debug('Cleaning up')\n epics.PV = epics._PV\n\n\nclass FakePVTests(unittest.TestCase):\n def test_fakepv(self):\n pvname = 'fakepv_nowaythisexists' * 10\n\n info = dict(called=False)\n\n def conn(**kwargs):\n info['conn'] = True\n info['conn_kw'] = kwargs\n\n def value_cb(**kwargs):\n info['value'] = True\n info['value_kw'] = kwargs\n\n pv = epics.PV(pvname, callback=value_cb, connection_callback=conn,\n )\n\n if not pv.wait_for_connection():\n raise ValueError('should return True on connection')\n\n self.assertEquals(pv.pvname, pvname)\n\n pv._update_rate = 0.5\n time.sleep(0.2)\n\n self.assertTrue(info['conn'])\n self.assertTrue(info['value'])\n self.assertEquals(info['value_kw']['value'], pv.value)\n\n\nclass SignalTests(unittest.TestCase):\n def test_signal_base(self):\n start_t = time.time()\n\n name = 'test'\n value = 10.0\n signal = Signal(name=name, value=value, timestamp=start_t)\n signal.wait_for_connection()\n\n self.assertTrue(signal.connected)\n self.assertEquals(signal.name, name)\n self.assertEquals(signal.value, value)\n self.assertEquals(signal.get(), value)\n self.assertEquals(signal.timestamp, start_t)\n\n info = dict(called=False)\n\n def _sub_test(**kwargs):\n info['called'] = True\n info['kw'] = kwargs\n\n signal.subscribe(_sub_test, run=False)\n self.assertFalse(info['called'])\n\n signal.value = value\n signal.clear_sub(_sub_test)\n\n signal.subscribe(_sub_test, run=False)\n signal.clear_sub(_sub_test, event_type=signal.SUB_VALUE)\n\n kw = info['kw']\n self.assertIn('value', kw)\n self.assertIn('timestamp', kw)\n self.assertIn('old_value', kw)\n\n self.assertEquals(kw['value'], value)\n self.assertEquals(kw['old_value'], value)\n self.assertEquals(kw['timestamp'], signal.timestamp)\n\n # readback callback for soft signal\n info = dict(called=False)\n signal.subscribe(_sub_test, event_type=Signal.SUB_VALUE,\n run=False)\n self.assertFalse(info['called'])\n signal.put(value + 1)\n self.assertTrue(info['called'])\n\n signal.clear_sub(_sub_test)\n kw = info['kw']\n\n self.assertIn('value', kw)\n self.assertIn('timestamp', kw)\n self.assertIn('old_value', kw)\n\n self.assertEquals(kw['value'], value + 1)\n self.assertEquals(kw['old_value'], value)\n self.assertEquals(kw['timestamp'], signal.timestamp)\n\n signal.trigger()\n signal.read()\n signal.describe()\n signal.read_configuration()\n signal.describe_configuration()\n\n eval(repr(signal))\n\n def test_signal_copy(self):\n start_t = time.time()\n\n name = 'test'\n value = 10.0\n signal = Signal(name=name, value=value, timestamp=start_t)\n sig_copy = copy.copy(signal)\n\n self.assertEquals(signal.name, sig_copy.name)\n self.assertEquals(signal.value, sig_copy.value)\n self.assertEquals(signal.get(), sig_copy.get())\n self.assertEquals(signal.timestamp, sig_copy.timestamp)\n\n\nclass EpicsSignalTests(unittest.TestCase):\n def test_rw_removal(self):\n # rw kwarg is no longer used\n with self.assertRaises(RuntimeError):\n EpicsSignal('readpv', rw=False)\n\n with self.assertRaises(RuntimeError):\n EpicsSignal('readpv', rw=True)\n\n def test_epicssignal_readonly(self):\n epics.PV = FakeEpicsPV\n\n signal = EpicsSignalRO('readpv')\n signal.wait_for_connection()\n\n signal.value\n\n with self.assertRaises(ReadOnlyError):\n signal.value = 10\n\n with self.assertRaises(ReadOnlyError):\n signal.put(10)\n\n # vestigial, to be removed\n with self.assertRaises(AttributeError):\n signal.setpoint_ts\n\n # vestigial, to be removed\n with self.assertRaises(AttributeError):\n signal.setpoint\n\n signal.precision\n signal.timestamp\n signal.limits\n\n signal.read()\n signal.describe()\n signal.read_configuration()\n signal.describe_configuration()\n\n eval(repr(signal))\n time.sleep(0.2)\n\n def test_epicssignal_readwrite_limits(self):\n epics.PV = FakeEpicsPV\n\n signal = EpicsSignal('readpv', write_pv='readpv',\n limits=True)\n\n signal.wait_for_connection()\n signal.check_value((signal.low_limit + signal.high_limit) / 2)\n\n try:\n signal.check_value(None)\n except ValueError:\n pass\n else:\n raise ValueError('value=None')\n\n try:\n signal.check_value(signal.low_limit - 1)\n except ValueError:\n pass\n else:\n raise ValueError('lower limit %s' % (signal.limits, ))\n\n try:\n signal.check_value(signal.high_limit + 1)\n except ValueError:\n pass\n else:\n raise ValueError('upper limit')\n\n def test_epicssignal_readwrite(self):\n epics.PV = FakeEpicsPV\n\n signal = EpicsSignal('readpv', write_pv='writepv')\n signal.wait_for_connection()\n\n self.assertEquals(signal.setpoint_pvname, 'writepv')\n self.assertEquals(signal.pvname, 'readpv')\n signal.value\n\n signal._update_rate = 2\n time.sleep(0.2)\n\n value = 10\n signal.value = value\n signal.setpoint = value\n self.assertEquals(signal.setpoint, value)\n signal.setpoint_ts\n\n signal.limits\n signal.precision\n signal.timestamp\n\n signal.read()\n signal.describe()\n signal.read_configuration()\n signal.describe_configuration()\n\n eval(repr(signal))\n time.sleep(0.2)\n\n def test_epicssignal_waveform(self):\n epics.PV = FakeEpicsWaveform\n\n def update_cb(value=None, **kwargs):\n self.assertIn(value, FakeEpicsWaveform.strings)\n\n signal = EpicsSignal('readpv', string=True)\n signal.wait_for_connection()\n\n signal.subscribe(update_cb)\n self.assertIn(signal.value, FakeEpicsWaveform.strings)\n\n def test_no_connection(self):\n epics.PV = FakeEpicsPV\n # special case in FakeEpicsPV that returns false in wait_for_connection\n sig = EpicsSignal('does_not_connect')\n self.assertRaises(TimeoutError, sig.wait_for_connection)\n\n sig = EpicsSignal('does_not_connect')\n self.assertRaises(TimeoutError, sig.put, 0.0)\n self.assertRaises(TimeoutError, sig.get)\n\n sig = EpicsSignal('connects', write_pv='does_not_connect')\n self.assertRaises(TimeoutError, sig.wait_for_connection)\n\n def test_enum_strs(self):\n epics.PV = FakeEpicsPV\n sig = EpicsSignal('connects')\n sig.wait_for_connection()\n\n enums = ['enum_strs']\n\n # hack this onto the FakeEpicsPV\n sig._read_pv.enum_strs = enums\n\n self.assertEquals(sig.enum_strs, enums)\n\n def test_setpoint(self):\n epics.PV = FakeEpicsPV\n sig = EpicsSignal('connects')\n sig.wait_for_connection()\n\n sig.get_setpoint()\n sig.get_setpoint(as_string=True)\n\n def test_epicssignalro(self):\n # not in initializer parameters anymore\n self.assertRaises(TypeError, EpicsSignalRO, 'test',\n write_pv='nope_sorry')\n\n\nfrom . import main\nis_main = (__name__ == '__main__')\nmain(is_main)\n"
]
| [
[
"numpy.array"
]
]
|
kenmcmil/nnitp | [
"aa2ed7286a675f3943ca5b9405066b78f7858fd9"
]
| [
"nnitp/mpl_editor.py"
]
| [
"#\n# Copyright (c) Microsoft Corporation.\n#\n\nfrom matplotlib.backends.qt_compat import QtCore, QtWidgets\nfrom matplotlib.backends.backend_qt4agg import (\n FigureCanvas, NavigationToolbar2QT as NavigationToolbar)\nfrom matplotlib.figure import Figure\n\nfrom traits.api import Any, Instance\nfrom traitsui.qt4.editor import Editor\nfrom traitsui.qt4.basic_editor_factory import BasicEditorFactory\n\nclass _MPLFigureEditor(Editor):\n\n scrollable = True\n\n def init(self, parent):\n self.control = self._create_canvas(parent)\n self.set_tooltip()\n\n def update_editor(self):\n pass\n\n def _create_canvas(self, parent):\n \"\"\" Create the MPL canvas. \"\"\"\n return FigureCanvas(self.value)\n\nclass MPLFigureEditor(BasicEditorFactory):\n\n klass = _MPLFigureEditor\n\n\n"
]
| [
[
"matplotlib.backends.backend_qt4agg.FigureCanvas"
]
]
|
phamduchoangeee/number-plate-dectect | [
"1f72485d0e6a87d20206d1864091e68174ca7aa5"
]
| [
"PlateDetection/Preprocess.py"
]
| [
"# Preprocess.py\n\nimport cv2\nimport numpy as np\n\n# module level variables\nGAUSSIAN_SMOOTH_FILTER_SIZE = (5, 5)\nADAPTIVE_THRESH_BLOCK_SIZE = 19\nADAPTIVE_THRESH_WEIGHT = 9\n\n\ndef preprocess(imgOriginal):\n imgGrayscale = extractValue(imgOriginal)\n\n imgMaxContrastGrayscale = maximizeContrast(imgGrayscale)\n\n height, width = imgGrayscale.shape\n\n imgBlurred = np.zeros((height, width, 1), np.uint8)\n\n imgBlurred = cv2.GaussianBlur(imgMaxContrastGrayscale, GAUSSIAN_SMOOTH_FILTER_SIZE, 0)\n\n imgThresh = cv2.adaptiveThreshold(imgBlurred, 255.0, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV,\n ADAPTIVE_THRESH_BLOCK_SIZE, ADAPTIVE_THRESH_WEIGHT)\n\n return imgGrayscale, imgThresh\n\n\ndef extractValue(imgOriginal):\n height, width, numChannels = imgOriginal.shape\n\n imgHSV = np.zeros((height, width, 3), np.uint8)\n\n imgHSV = cv2.cvtColor(imgOriginal, cv2.COLOR_BGR2HSV)\n\n imgHue, imgSaturation, imgValue = cv2.split(imgHSV)\n\n return imgValue\n\n\ndef maximizeContrast(imgGrayscale):\n height, width = imgGrayscale.shape\n\n imgTopHat = np.zeros((height, width, 1), np.uint8)\n imgBlackHat = np.zeros((height, width, 1), np.uint8)\n\n structuringElement = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))\n\n imgTopHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_TOPHAT, structuringElement)\n imgBlackHat = cv2.morphologyEx(imgGrayscale, cv2.MORPH_BLACKHAT, structuringElement)\n\n imgGrayscalePlusTopHat = cv2.add(imgGrayscale, imgTopHat)\n imgGrayscalePlusTopHatMinusBlackHat = cv2.subtract(imgGrayscalePlusTopHat, imgBlackHat)\n\n return imgGrayscalePlusTopHatMinusBlackHat\n"
]
| [
[
"numpy.zeros"
]
]
|
realshallow/DeepFakeTorch | [
"33b6f65e77aeba4ad3c500b23cfd239c2a079fe5"
]
| [
"face_detect.py"
]
| [
"from facenet_pytorch import MTCNN\r\nimport torch\r\nimport numpy as np\r\nimport cv2\r\nfrom PIL import Image\r\nfrom img_rotate import rotate\r\nfrom loguru import logger\r\nimport os\r\nimport argparse\r\n\r\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\r\nprint('Running on device: {}'.format(device))\r\nmtcnn = MTCNN(keep_all=True, device=device, margin=50, select_largest=True, image_size=256)\r\n\r\n\r\[email protected]()\r\ndef extract_face(frame, align=True, margin=5):\r\n if align:\r\n frame = rotate(np.array(frame))\r\n frame = Image.fromarray(frame)\r\n # mtcnn(frame, save_path=name)\r\n boxes, _ = mtcnn.detect(frame)\r\n for box in boxes:\r\n box_list = box.tolist()\r\n # bounding box coordinated\r\n x1 = int(box_list[0])\r\n y1 = int(box_list[1])\r\n x2 = int(box_list[2])\r\n y2 = int(box_list[3])\r\n # find the middle of the image to get a perfect square, mtcnn gives a rectangle image of the face so making\r\n # the image a square makes it easier to train\r\n y1 += margin\r\n y2 -= margin\r\n diff = abs(y1 - y2)\r\n mid_x = (x2 + x1) // 2\r\n # mid_y = (y2 + y1) // 2\r\n x1 = mid_x - (diff // 2)\r\n x2 = mid_x + (diff // 2)\r\n return frame.crop((x1, y1, x2, y2)) # sends back only the square around the face, possible no face detected\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument('-video_src', type=str, required=True, help='where to save the images')\r\n parser.add_argument('-out_name', type=str, required=True, help='The name of the output movie')\r\n parser.add_argument('-margin', type=int, default=5, help='margin around the detected face box')\r\n parser.add_argument('-align_faces', type=int, default=5, help='align the faces')\r\n\r\n args = parser.parse_args()\r\n full_dir = os.path.join(args.out_name, 'aligned_faces')\r\n\r\n if not os.path.exists(full_dir):\r\n os.makedirs(full_dir)\r\n\r\n cap = cv2.VideoCapture(args.video_src)\r\n i = 0\r\n while cap.isOpened():\r\n ret, frame = cap.read()\r\n if ret:\r\n try:\r\n crop_img = extract_face(frame, margin=args.margin)\r\n crop_img.save(full_dir + \"/{}.png\".format(str(i).zfill(4)))\r\n print('\\rTracking frame: {}'.format(i + 1), end='')\r\n i += 1\r\n # No face found, not good code\r\n except Exception as e:\r\n print(\"ERROR\",e)\r\n else:\r\n break\r\n"
]
| [
[
"numpy.array",
"torch.cuda.is_available"
]
]
|
DevTheDev/C-SSAW | [
"023bcc5b09b1a49447537dd63de4158b09f235b5"
]
| [
"Vision/characterPosition.py"
]
| [
"import csv\nimport cv2\nimport pytesseract as pt\nimport numpy as np\nfrom io import StringIO\n\nimageFile = 'stop.jpg'\nimg = cv2.imread(imageFile)\n# img = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)\ngrayscaled = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\nthreshold = cv2.bitwise_not(cv2.adaptiveThreshold(grayscaled, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 5011, 1))\ncv2.imshow('step1', threshold)\nboxArr = pt.image_to_boxes(threshold, config='psm 1')\n# print(boxArr)\n# To read the coordinates\nboxes = []\nf = StringIO(boxArr)\nreader = csv.reader(f, delimiter = ' ')\nfor row in reader:\n if(len(row)==6):\n boxes.append(row)\n\n# print(boxes)\n# # Draw the bounding box\nimg = threshold\n# cv2.imshow('input',img)\nh, w = img.shape\nfor b in boxes:\n cv2.rectangle(img,(int(b[1]),h-int(b[2])),(int(b[3]),h-int(b[4])),(100,np.random.randint(255),np.random.randint(255)),1)\ncv2.imshow('output',img)\ncv2.waitKey(0)\ncv2.destroyAllWindows()\n\n#Problem: The rectangles are too big or something.\n"
]
| [
[
"numpy.random.randint"
]
]
|
federicopozzi33/vision | [
"b969cca783cfe6c1009b7bf60609e28d83c973a6"
]
| [
"torchvision/io/video.py"
]
| [
"import gc\nimport math\nimport os\nimport re\nimport warnings\nfrom fractions import Fraction\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\nimport numpy as np\nimport torch\n\nfrom ..utils import _log_api_usage_once\nfrom . import _video_opt\n\n\ntry:\n import av\n\n av.logging.set_level(av.logging.ERROR)\n if not hasattr(av.video.frame.VideoFrame, \"pict_type\"):\n av = ImportError(\n \"\"\"\\\nYour version of PyAV is too old for the necessary video operations in torchvision.\nIf you are on Python 3.5, you will have to build from source (the conda-forge\npackages are not up-to-date). See\nhttps://github.com/mikeboers/PyAV#installation for instructions on how to\ninstall PyAV on your system.\n\"\"\"\n )\nexcept ImportError:\n av = ImportError(\n \"\"\"\\\nPyAV is not installed, and is necessary for the video operations in torchvision.\nSee https://github.com/mikeboers/PyAV#installation for instructions on how to\ninstall PyAV on your system.\n\"\"\"\n )\n\n\ndef _check_av_available() -> None:\n if isinstance(av, Exception):\n raise av\n\n\ndef _av_available() -> bool:\n return not isinstance(av, Exception)\n\n\n# PyAV has some reference cycles\n_CALLED_TIMES = 0\n_GC_COLLECTION_INTERVAL = 10\n\n\ndef write_video(\n filename: str,\n video_array: torch.Tensor,\n fps: float,\n video_codec: str = \"libx264\",\n options: Optional[Dict[str, Any]] = None,\n audio_array: Optional[torch.Tensor] = None,\n audio_fps: Optional[float] = None,\n audio_codec: Optional[str] = None,\n audio_options: Optional[Dict[str, Any]] = None,\n) -> None:\n \"\"\"\n Writes a 4d tensor in [T, H, W, C] format in a video file\n\n Args:\n filename (str): path where the video will be saved\n video_array (Tensor[T, H, W, C]): tensor containing the individual frames,\n as a uint8 tensor in [T, H, W, C] format\n fps (Number): video frames per second\n video_codec (str): the name of the video codec, i.e. \"libx264\", \"h264\", etc.\n options (Dict): dictionary containing options to be passed into the PyAV video stream\n audio_array (Tensor[C, N]): tensor containing the audio, where C is the number of channels\n and N is the number of samples\n audio_fps (Number): audio sample rate, typically 44100 or 48000\n audio_codec (str): the name of the audio codec, i.e. \"mp3\", \"aac\", etc.\n audio_options (Dict): dictionary containing options to be passed into the PyAV audio stream\n \"\"\"\n if not torch.jit.is_scripting() and not torch.jit.is_tracing():\n _log_api_usage_once(write_video)\n _check_av_available()\n video_array = torch.as_tensor(video_array, dtype=torch.uint8).numpy()\n\n # PyAV does not support floating point numbers with decimal point\n # and will throw OverflowException in case this is not the case\n if isinstance(fps, float):\n fps = np.round(fps)\n\n with av.open(filename, mode=\"w\") as container:\n stream = container.add_stream(video_codec, rate=fps)\n stream.width = video_array.shape[2]\n stream.height = video_array.shape[1]\n stream.pix_fmt = \"yuv420p\" if video_codec != \"libx264rgb\" else \"rgb24\"\n stream.options = options or {}\n\n if audio_array is not None:\n audio_format_dtypes = {\n \"dbl\": \"<f8\",\n \"dblp\": \"<f8\",\n \"flt\": \"<f4\",\n \"fltp\": \"<f4\",\n \"s16\": \"<i2\",\n \"s16p\": \"<i2\",\n \"s32\": \"<i4\",\n \"s32p\": \"<i4\",\n \"u8\": \"u1\",\n \"u8p\": \"u1\",\n }\n a_stream = container.add_stream(audio_codec, rate=audio_fps)\n a_stream.options = audio_options or {}\n\n num_channels = audio_array.shape[0]\n audio_layout = \"stereo\" if num_channels > 1 else \"mono\"\n audio_sample_fmt = container.streams.audio[0].format.name\n\n format_dtype = np.dtype(audio_format_dtypes[audio_sample_fmt])\n audio_array = torch.as_tensor(audio_array).numpy().astype(format_dtype)\n\n frame = av.AudioFrame.from_ndarray(audio_array, format=audio_sample_fmt, layout=audio_layout)\n\n frame.sample_rate = audio_fps\n\n for packet in a_stream.encode(frame):\n container.mux(packet)\n\n for packet in a_stream.encode():\n container.mux(packet)\n\n for img in video_array:\n frame = av.VideoFrame.from_ndarray(img, format=\"rgb24\")\n frame.pict_type = \"NONE\"\n for packet in stream.encode(frame):\n container.mux(packet)\n\n # Flush stream\n for packet in stream.encode():\n container.mux(packet)\n\n\ndef _read_from_stream(\n container: \"av.container.Container\",\n start_offset: float,\n end_offset: float,\n pts_unit: str,\n stream: \"av.stream.Stream\",\n stream_name: Dict[str, Optional[Union[int, Tuple[int, ...], List[int]]]],\n) -> List[\"av.frame.Frame\"]:\n global _CALLED_TIMES, _GC_COLLECTION_INTERVAL\n _CALLED_TIMES += 1\n if _CALLED_TIMES % _GC_COLLECTION_INTERVAL == _GC_COLLECTION_INTERVAL - 1:\n gc.collect()\n\n if pts_unit == \"sec\":\n # TODO: we should change all of this from ground up to simply take\n # sec and convert to MS in C++\n start_offset = int(math.floor(start_offset * (1 / stream.time_base)))\n if end_offset != float(\"inf\"):\n end_offset = int(math.ceil(end_offset * (1 / stream.time_base)))\n else:\n warnings.warn(\"The pts_unit 'pts' gives wrong results. Please use pts_unit 'sec'.\")\n\n frames = {}\n should_buffer = True\n max_buffer_size = 5\n if stream.type == \"video\":\n # DivX-style packed B-frames can have out-of-order pts (2 frames in a single pkt)\n # so need to buffer some extra frames to sort everything\n # properly\n extradata = stream.codec_context.extradata\n # overly complicated way of finding if `divx_packed` is set, following\n # https://github.com/FFmpeg/FFmpeg/commit/d5a21172283572af587b3d939eba0091484d3263\n if extradata and b\"DivX\" in extradata:\n # can't use regex directly because of some weird characters sometimes...\n pos = extradata.find(b\"DivX\")\n d = extradata[pos:]\n o = re.search(rb\"DivX(\\d+)Build(\\d+)(\\w)\", d)\n if o is None:\n o = re.search(rb\"DivX(\\d+)b(\\d+)(\\w)\", d)\n if o is not None:\n should_buffer = o.group(3) == b\"p\"\n seek_offset = start_offset\n # some files don't seek to the right location, so better be safe here\n seek_offset = max(seek_offset - 1, 0)\n if should_buffer:\n # FIXME this is kind of a hack, but we will jump to the previous keyframe\n # so this will be safe\n seek_offset = max(seek_offset - max_buffer_size, 0)\n try:\n # TODO check if stream needs to always be the video stream here or not\n container.seek(seek_offset, any_frame=False, backward=True, stream=stream)\n except av.AVError:\n # TODO add some warnings in this case\n # print(\"Corrupted file?\", container.name)\n return []\n buffer_count = 0\n try:\n for _idx, frame in enumerate(container.decode(**stream_name)):\n frames[frame.pts] = frame\n if frame.pts >= end_offset:\n if should_buffer and buffer_count < max_buffer_size:\n buffer_count += 1\n continue\n break\n except av.AVError:\n # TODO add a warning\n pass\n # ensure that the results are sorted wrt the pts\n result = [frames[i] for i in sorted(frames) if start_offset <= frames[i].pts <= end_offset]\n if len(frames) > 0 and start_offset > 0 and start_offset not in frames:\n # if there is no frame that exactly matches the pts of start_offset\n # add the last frame smaller than start_offset, to guarantee that\n # we will have all the necessary data. This is most useful for audio\n preceding_frames = [i for i in frames if i < start_offset]\n if len(preceding_frames) > 0:\n first_frame_pts = max(preceding_frames)\n result.insert(0, frames[first_frame_pts])\n return result\n\n\ndef _align_audio_frames(\n aframes: torch.Tensor, audio_frames: List[\"av.frame.Frame\"], ref_start: int, ref_end: float\n) -> torch.Tensor:\n start, end = audio_frames[0].pts, audio_frames[-1].pts\n total_aframes = aframes.shape[1]\n step_per_aframe = (end - start + 1) / total_aframes\n s_idx = 0\n e_idx = total_aframes\n if start < ref_start:\n s_idx = int((ref_start - start) / step_per_aframe)\n if end > ref_end:\n e_idx = int((ref_end - end) / step_per_aframe)\n return aframes[:, s_idx:e_idx]\n\n\ndef read_video(\n filename: str,\n start_pts: Union[float, Fraction] = 0,\n end_pts: Optional[Union[float, Fraction]] = None,\n pts_unit: str = \"pts\",\n) -> Tuple[torch.Tensor, torch.Tensor, Dict[str, Any]]:\n \"\"\"\n Reads a video from a file, returning both the video frames as well as\n the audio frames\n\n Args:\n filename (str): path to the video file\n start_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional):\n The start presentation time of the video\n end_pts (int if pts_unit = 'pts', float / Fraction if pts_unit = 'sec', optional):\n The end presentation time\n pts_unit (str, optional): unit in which start_pts and end_pts values will be interpreted,\n either 'pts' or 'sec'. Defaults to 'pts'.\n\n Returns:\n vframes (Tensor[T, H, W, C]): the `T` video frames\n aframes (Tensor[K, L]): the audio frames, where `K` is the number of channels and `L` is the number of points\n info (Dict): metadata for the video and audio. Can contain the fields video_fps (float) and audio_fps (int)\n \"\"\"\n if not torch.jit.is_scripting() and not torch.jit.is_tracing():\n _log_api_usage_once(read_video)\n\n from torchvision import get_video_backend\n\n if not os.path.exists(filename):\n raise RuntimeError(f\"File not found: {filename}\")\n\n if get_video_backend() != \"pyav\":\n return _video_opt._read_video(filename, start_pts, end_pts, pts_unit)\n\n _check_av_available()\n\n if end_pts is None:\n end_pts = float(\"inf\")\n\n if end_pts < start_pts:\n raise ValueError(f\"end_pts should be larger than start_pts, got start_pts={start_pts} and end_pts={end_pts}\")\n\n info = {}\n video_frames = []\n audio_frames = []\n audio_timebase = _video_opt.default_timebase\n\n try:\n with av.open(filename, metadata_errors=\"ignore\") as container:\n if container.streams.audio:\n audio_timebase = container.streams.audio[0].time_base\n if container.streams.video:\n video_frames = _read_from_stream(\n container,\n start_pts,\n end_pts,\n pts_unit,\n container.streams.video[0],\n {\"video\": 0},\n )\n video_fps = container.streams.video[0].average_rate\n # guard against potentially corrupted files\n if video_fps is not None:\n info[\"video_fps\"] = float(video_fps)\n\n if container.streams.audio:\n audio_frames = _read_from_stream(\n container,\n start_pts,\n end_pts,\n pts_unit,\n container.streams.audio[0],\n {\"audio\": 0},\n )\n info[\"audio_fps\"] = container.streams.audio[0].rate\n\n except av.AVError:\n # TODO raise a warning?\n pass\n\n vframes_list = [frame.to_rgb().to_ndarray() for frame in video_frames]\n aframes_list = [frame.to_ndarray() for frame in audio_frames]\n\n if vframes_list:\n vframes = torch.as_tensor(np.stack(vframes_list))\n else:\n vframes = torch.empty((0, 1, 1, 3), dtype=torch.uint8)\n\n if aframes_list:\n aframes = np.concatenate(aframes_list, 1)\n aframes = torch.as_tensor(aframes)\n if pts_unit == \"sec\":\n start_pts = int(math.floor(start_pts * (1 / audio_timebase)))\n if end_pts != float(\"inf\"):\n end_pts = int(math.ceil(end_pts * (1 / audio_timebase)))\n aframes = _align_audio_frames(aframes, audio_frames, start_pts, end_pts)\n else:\n aframes = torch.empty((1, 0), dtype=torch.float32)\n\n return vframes, aframes, info\n\n\ndef _can_read_timestamps_from_packets(container: \"av.container.Container\") -> bool:\n extradata = container.streams[0].codec_context.extradata\n if extradata is None:\n return False\n if b\"Lavc\" in extradata:\n return True\n return False\n\n\ndef _decode_video_timestamps(container: \"av.container.Container\") -> List[int]:\n if _can_read_timestamps_from_packets(container):\n # fast path\n return [x.pts for x in container.demux(video=0) if x.pts is not None]\n else:\n return [x.pts for x in container.decode(video=0) if x.pts is not None]\n\n\ndef read_video_timestamps(filename: str, pts_unit: str = \"pts\") -> Tuple[List[int], Optional[float]]:\n \"\"\"\n List the video frames timestamps.\n\n Note that the function decodes the whole video frame-by-frame.\n\n Args:\n filename (str): path to the video file\n pts_unit (str, optional): unit in which timestamp values will be returned\n either 'pts' or 'sec'. Defaults to 'pts'.\n\n Returns:\n pts (List[int] if pts_unit = 'pts', List[Fraction] if pts_unit = 'sec'):\n presentation timestamps for each one of the frames in the video.\n video_fps (float, optional): the frame rate for the video\n\n \"\"\"\n if not torch.jit.is_scripting() and not torch.jit.is_tracing():\n _log_api_usage_once(read_video_timestamps)\n from torchvision import get_video_backend\n\n if get_video_backend() != \"pyav\":\n return _video_opt._read_video_timestamps(filename, pts_unit)\n\n _check_av_available()\n\n video_fps = None\n pts = []\n\n try:\n with av.open(filename, metadata_errors=\"ignore\") as container:\n if container.streams.video:\n video_stream = container.streams.video[0]\n video_time_base = video_stream.time_base\n try:\n pts = _decode_video_timestamps(container)\n except av.AVError:\n warnings.warn(f\"Failed decoding frames for file {filename}\")\n video_fps = float(video_stream.average_rate)\n except av.AVError as e:\n msg = f\"Failed to open container for {filename}; Caught error: {e}\"\n warnings.warn(msg, RuntimeWarning)\n\n pts.sort()\n\n if pts_unit == \"sec\":\n pts = [x * video_time_base for x in pts]\n\n return pts, video_fps\n"
]
| [
[
"torch.empty",
"numpy.dtype",
"numpy.stack",
"numpy.round",
"numpy.concatenate",
"torch.jit.is_tracing",
"torch.jit.is_scripting",
"torch.as_tensor"
]
]
|
DreaaZamaa/CorePy | [
"64105751664e85a2106b71fcc5c124111c62ca0b"
]
| [
"Corepy Examples/Coreimage.py"
]
| [
"import numpy as np\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nimport os\nimport matplotlib.patches as patches\nimport pickle\nimport math\nimport corepytools as corepy\nimport json\n\nCoreOfStudy = 'Public'\n\nCorebeta=json.load(open(os.path.join(CoreOfStudy + '.json')))\n\n\nFormation_names = '-'.join(Corebeta[\"Formation\"]+Corebeta[\"Formation_2\"]) # this is used to make the directory specific to the formations\n\n\n#pipes the color dict file for consistent chemofacies coloring\ninfile = open('chemocolor','rb')\nchemofacies_color= pickle.load(infile)\ninfile.close()\n\n## Import datafiles\ncoredata = corepy.OutputXRF(Corebeta['corename'],Formation_names)\nTubes_dir = os.path.join(str('./CoreData/CoreTubes') + '/' + Corebeta['corename'] + '_tubes_vis')\ndirName=corepy.RootDir(Corebeta['corename'], Formation_names) \n\n\n#makes a list of the file names and sorts them top to bottom so they are called correctly in the loop\n#file_names=os.listdir(Tubes_dir)\nfile_names=corepy.natural_sort(os.listdir(Tubes_dir))\n\nrows=math.ceil(len(file_names)/Corebeta['noOfCols'])\nchunksize=100 # number of files to be processed. might fail if folder doesnt have 100 files\nnumber_chunks=math.ceil(len(file_names)/chunksize)\n\ndef chunks(l, n):\n # For item i in a range that is a length of l,\n for i in range(0, len(l), chunksize):\n # Create an index range for l of n items:\n yield l[i:i+chunksize]\n\na=list(chunks(file_names, chunksize)) #a list of files in each chunk\nfile_names=a[0] #manually select which chuck to process\nrows=math.ceil(len(file_names)/Corebeta['noOfCols']) # rows is re-written here to use number of rows in the chunked files\n\nfig, axs = plt.subplots(nrows=rows, ncols=Corebeta['noOfCols'], figsize=(10,10*rows),sharey=True)\nphoto_number=0 # starts counting photos at 0 in the file_names folder\n\nfor i in range(rows):\n for j in range(Corebeta['noOfCols']):\n photofile = file_names[photo_number]\n \n image=os.path.join(Tubes_dir,photofile)\n img = Image.open(image)\n axs[i,j].imshow(img)\n\n \n#section adding chemofacies patches\n depths=os.path.splitext(photofile)[0].split('_') # grabs the top depth and bottom depth from the file name\n photo_top=float(depths[1]) #1\n photo_bottom=float(depths[2]) #2\n\n XX = coredata [coredata [Corebeta['Depth_model']].between(photo_top, (photo_bottom))] # this should be working now\n \n # makes sure the rectangels are the same width\n arr = np.array(img) #converts the img to an array for pixel size information\n pixel_width=np.shape(arr)[1]*0.8\n pixel_height=np.shape(arr)[0]*0.8\n\n sticker_depth = XX[Corebeta['Depth_model']].values #depth of each sticker minus the top box depth\n pixel_depth =(sticker_depth-photo_top) / ((photo_top + Corebeta['coretube_length'])-photo_top)*len(arr) # convert sticker depth to pixel depth\n\n photo_number=photo_number+1 # this loops the images\n\n for k in range(len(pixel_depth)):\n\n rect = patches.Rectangle((pixel_width*0.9-50 , pixel_depth[k]) , pixel_width*0.15 , pixel_height*0.02 ,linewidth=1 ,edgecolor='w',facecolor=chemofacies_color[XX[Corebeta['RockClassification']].values[k]])\n axs[i,j].add_patch(rect) # Add the patch to the Axes\n\nplt.savefig(os.path.join(dirName + '/' + Corebeta['corename'] + '_' + Formation_names + '_' + str(photo_top) + '.png'),dpi = 300)"
]
| [
[
"matplotlib.patches.Rectangle",
"numpy.array",
"numpy.shape",
"matplotlib.pyplot.subplots"
]
]
|
sustcjudgement/Judgement_information_extraction | [
"c769eb1cb7ee695a157a981dbe9cd9d6559d072b"
]
| [
"clustering/KM.py"
]
| [
"from sklearn.cluster import KMeans\nfrom sklearn.cluster import *\nfrom sklearn import metrics\nimport numpy as np\nimport openpyxl\nimport matplotlib.pylab as plt\nimport pandas as pd\nfrom sklearn.cluster import Birch\nfrom sklearn.metrics import calinski_harabaz_score\n\nFILE_NAME = \"E:\\data_analysis\\Judgement_information_extraction\\database_xml\\่ดชๆฑกๅ่ดฟ็ฝช_ไธๅฎก_ๆๅ.xlsx\"\n\nfile = FILE_NAME\n\ndef K_Means():\n df = pd.read_excel(file)\n\n # ๆๅๅคๅณๆณๆก\n # x = df.iloc[4]\n # print(x)\n # y = df.iloc[:,-1]\n wb = openpyxl.load_workbook(file)\n ws = wb.worksheets[0]\n col = ws.max_column\n row = ws.max_row\n # row = 100\n data = []\n data_index = []\n for i in range(1, row + 1):\n data_index.append(int(ws.cell(row=i, column=1).value))\n data.append(list(str(ws.cell(row=i, column=3).value)))\n X = np.array(data)\n\n # ==============Ziyuan method====================\n # find out the suitable number of cluster\n # d = []\n # for i in range(1, 11): # kๅๅผ1~11๏ผๅkmeans่็ฑป๏ผ็ไธๅkๅผๅฏนๅบ็็ฐๅ
่ฏฏๅทฎๅนณๆนๅ\n # km = KMeans(n_clusters=i, init='k-means++', n_init=10, max_iter=300, random_state=0)\n # km.fit(X)\n # d.append(km.inertia_)\n # plt.axvline(x=4, linewidth=1.5, color='orangered', linestyle=\"--\", label=':\"knee\" point')\n # plt.plot(range(1,11), d, marker='o')\n # plt.xlabel('number of clusters')\n # plt.ylabel('distortions')\n # plt.legend(loc='upper right', prop={'size': 8})\n # plt.show()\n #\n #\n # three_cluster_model = KMeans(n_clusters=4, random_state=0)\n # three_cluster_model.fit(X)\n # label = list(three_cluster_model.labels_)\n # predict_model = three_cluster_model.predict(X)\n # # print(predict_model[4000:4200])\n # centres = three_cluster_model.cluster_centers_\n # # print(centres)\n # colors = ['r','c','b','y']\n # plt.figure\n # # print(X)\n # for j in range(4):\n # index_set = np.where(predict_model == j)\n # cluster = X[index_set]\n # print(cluster)\n # plt.scatter(cluster[:, 1], cluster[:, 2], c=colors[j], marker='.')\n # plt.plot(centres[j][0], centres[j][1], 'o', markerfacecolor=colors[j], markeredgecolor='k',\n # markersize=8) # ็ป็ฑปๅซไธญๅฟ\n # plt.show()\n #=====Evaluation index=====\n\n\n # inertias = three_cluster_model.inertia_\n # adjust_rand_index = metrics.adjusted_rand_score((y_))\n\n # ===============Peijun method===================\n kmeans = KMeans(n_clusters=4, init='k-means++', n_init=10, max_iter=300, random_state=0).fit(X)\n label = list(kmeans.labels_)\n num = np.zeros(4, dtype=int)\n for i in label:\n num[i] += 1\n print(num)\n for i in range(1,row+1):\n ws.cell(row=i,column=4).value=label[i-1]\n wb.save(filename='่ดชๆฑกๅ่ดฟ็ฝช_ไธๅฎก_ๆๅ.xlsx')\n\n\ndef spectral():\n # ๆๅๅคๅณๆณๆก\n # x = df.iloc[4]\n # print(x)\n # y = df.iloc[:,-1]\n wb = openpyxl.load_workbook(file)\n ws = wb.worksheets[0]\n col = ws.max_column\n row = ws.max_row\n # row = 100\n data = []\n data_index = []\n for i in range(1, row + 1):\n data_index.append(int(ws.cell(row=i, column=1).value))\n temp = list(str(ws.cell(row=i, column=3).value))\n temp = [int(x) for x in temp]\n data.append(temp)\n X = np.array(data)\n # y_pre = Birch(n_clusters=None).fit_predict(X)\n label = Birch(n_clusters=4).fit_predict(X)\n num = np.zeros(4, dtype=int)\n for i in label:\n num[i] += 1\n print(num)\n for i in range(1, row + 1):\n ws.cell(row=i, column=4).value = label[i - 1]\n wb.save(filename='่ดชๆฑกๅ่ดฟ็ฝช_ไธๅฎก_ๆๅ.xlsx')\n print(\"finish\")\n\nif __name__==\"__main__\":\n spectral()\n\n"
]
| [
[
"pandas.read_excel",
"sklearn.cluster.KMeans",
"sklearn.cluster.Birch",
"numpy.array",
"numpy.zeros"
]
]
|
okingjerryo/modelExperiment | [
"6e6a7b6055a2e4efff7d7e599fa8b79a2ca3270e"
]
| [
"fixGanExperment/util.py"
]
| [
"import os.path\n'''\nsunkejia\nfile loader\n'''\nimport args\nimport scipy\nimport os\nimport random\nimport numpy as np\nimport threading\nimport queue as Queue\nimport cv2\nfrom glob import glob\nimport glob\n\n#่ชๅฎไนๆฐๆฎ่ฏปๅ็ฑป\n'''\n่ฎพ่ฎกๆ่ทฏๆฏๅ่ฎพๅๅพๅ5็ฑปๅชๅฃฐๅ
ฑ่ฎก6็ฑป๏ผๅๅพๅ็ฌๅจไธไธชๆไปถๅคนไธญ๏ผๅชๅฃฐๅพๅๅจๆๅฎ็ๆไปถๅคนไธญ\nๆฏๆฌก่ฏปๅๆฐๆฎๅๅๅพไธๅผ ๅๅๆๅฎ็ๆไปถๅคนไธญ้ๆบ้ๆฉไธ็งๅชๅฃฐ่ฏปๅบๅพๅ๏ผๅถไฝไบๅ
็ป<Io,In>\n'''\nclass ImageReader_Customize(object):\n def __init__(self,original_path='',noise_path='',data_glob='',input_size=110,output_size=96,output_channal=3,random_crop=True\n ,thread_nums = 4,queue_size=256,batch_size=128,random_images=True):\n #่ทๅพๆไปถๅ่กจ\n self.output_channel = output_channal\n self.task = list()\n self.original_path=original_path\n self.noise_path=noise_path\n self.original_list=glob.glob(os.path.join(original_path,data_glob))\n #่ทๅพๅช้ณ็ฎๅฝ\n self.noise_name=[]\n for _,b,_ in os.walk(noise_path):\n self.noise_name=b\n break\n self.noise_count=len(self.noise_name)\n self.input_size=input_size\n self.output_size=output_size\n self.output_channal=output_channal\n self.batch_size=batch_size\n #้ๆบ่ฃๅช่ฟๆฏไธญๅฟ่ฃๅช\n self.random_crop=random_crop\n self.thread_nums=thread_nums\n\n #ๅพๅๆฏๅฆ่ฆ้ๆบๆไนฑ\n self.random_images=random_images\n self.q = Queue.Queue(queue_size)\n self.q_in=Queue.Queue(queue_size)\n #ๅญๅจๅๅงๅพๅๅ่กจ็จไบ้ๆบๆไนฑ\n self.random_original_list=np.asarray(self.original_list).copy()\n if self.random_images:\n self._random_image()\n self.im_count=len(self.original_list)\n self.epoch_batch = self.im_count * float(args.all_item_classes) / self.batch_size\n print(self.epoch_batch,'batchs/epoch')\n\n def _norm_img(self, img):\n '''\n ๅฝไธๅๅพๅ0-1\n :param img: 0-255ๅพๅ\n :return: 0-1ๅพๅ\n '''\n return np.array(img)/127.5 - 1\n\n def _im_read(self,path1,path2):\n '''\n ่ฏปๅๅพๅ\n :param imagepath:ๅพๅ่ทฏๅพ\n :return: 0-255็ๅพๅ\n '''\n im1 = cv2.imread(path1)\n im2 = cv2.imread(path2)\n return im1,im2\n\n def _random_image(self):\n '''\n ๆไนฑๆดไธชๅๅงๆฐๆฎๅ่กจ\n :return:\n '''\n rng_state = np.random.get_state()\n np.random.shuffle(self.random_original_list)\n\n def read_data_batch(self):\n '''\n ่ฐๅๆฐๆฎbatch็ๆนๆณ\n :return: ไธไธชๆฐๆฎbatch\n '''\n return self.q.get()\n\n\n def _get_images(self,path,path2):\n '''\n ่ฏปๅๅพๅ\n :param path:\n :return:\n '''\n im,im2 = self._im_read(path,path2)\n return self._transform(im,im2)\n\n def _transform(self,image,image2):\n '''\n ๅฐๅพๅๅชๅๆๆพ็ผฉ\n :param image:\n :return: ๅค็ๅฅฝ็ๅพๅ\n '''\n if self.random_crop and self.input_size!=self.output_size:\n cropped_image_1,cropped_image_2 = self._random_crop(image,image2)\n elif not self.random_crop and self.input_size!=self.output_size:\n crop_pix = int(round(self.input_size-self.output_size)/2.0)\n cropped_image_1 = scipy.misc.imresize(image[crop_pix:crop_pix+self.output_size,crop_pix:crop_pix+self.output_size]\n ,[self.output_size,self.output_size])\n cropped_image_2 = scipy.misc.imresize(\n image2[crop_pix:crop_pix + self.output_size, crop_pix:crop_pix + self.output_size]\n , [self.output_size, self.output_size])\n else:\n cropped_image_1 = cv2.resize(image,dsize=(self.output_size,self.output_size),interpolation=cv2.INTER_CUBIC)\n cropped_image_2 = cv2.resize(image, dsize=(self.output_size, self.output_size), interpolation=cv2.INTER_CUBIC)\n # todo: norm img ๅฝๆฐๆชๅฎไน\n return self._norm_img(cropped_image_1.reshape([self.output_size,self.output_size,self.output_channel])), \\\n self._norm_img(cropped_image_2.reshape([self.output_size, self.output_size, self.output_channel]))\n\n def _random_crop(self,images,images2):\n # if images.shape[0]>self.input_size:\n images = cv2.resize(images,dsize=(self.input_size,self.input_size),interpolation=cv2.INTER_CUBIC)\n images2 = cv2.resize(images2, dsize=(self.input_size, self.input_size), interpolation=cv2.INTER_CUBIC)\n # images=images.reshape([self.input_size,self.input_size,self.output_channel])\n # images2 = images2.reshape([self.input_size, self.input_size, self.output_channel])\n\n offsetmax=self.input_size-self.output_size\n random_w=np.random.randint(0,offsetmax)\n random_h=np.random.randint(0,offsetmax)\n\n return images[random_w:random_w+self.output_size,random_h:random_h+self.output_size,:], \\\n images2[random_w:random_w + self.output_size, random_h:random_h + self.output_size, :]\n\n\n #todo: ็่งฃๅฝๆฐ\n def _mkdual_batch(self):\n while True:\n imagebatch = np.zeros([self.batch_size, self.output_size, self.output_size, self.output_channel])\n for i in range(int(self.batch_size / 2)):\n im_index = random.randint(0, self.im_count - 1)\n noise_index = random.randint(0, self.noise_count - 1)\n path = self.random_original_list[im_index]\n noise_path = path.replace(self.original_path+\"original\",\n os.path.join(self.noise_path, self.noise_name[noise_index])) # todo:็ฑไบ็ฎๅฝ็ปๆไธๅ ๆพๅฐๅ
ถไปๅฐๆนๆถ้่ฆๆณจๆ\n try:\n im, im2 = self._get_images(path, noise_path)\n imagebatch[i, :, :, :] = im\n imagebatch[i + int(self.batch_size / 2), :, :] = im2\n\n except:\n a = 1\n print('ERRO:_mkdual_bath', path)\n self.q.put((imagebatch))\n\n def Dual_enqueueStart(self):\n for _ in range(self.thread_nums):\n t_out = threading.Thread(target=self._mkdual_batch,args=())\n t_out.daemon =True\n t_out.start()\n self.task.append(t_out) # ๆทปๅ ไบ list\n\ndef ensure_dir(file_path):\n directory = os.path.dirname(file_path)\n if not os.path.exists(directory):\n os.makedirs(directory)\n\ndef restore_img(image):\n return (np.array(image) +1) *127.5"
]
| [
[
"numpy.random.get_state",
"scipy.misc.imresize",
"numpy.asarray",
"numpy.random.shuffle",
"numpy.array",
"numpy.zeros",
"numpy.random.randint"
]
]
|
larsbratholm/global_fchl | [
"f99065c5d9a5c24eaaa45245ad338e373ae8f18f"
]
| [
"plotting.py"
]
| [
"import numpy as np\nfrom scipy import interpolate\nimport matplotlib.pyplot as plt\nfrom matplotlib.collections import LineCollection\nfrom matplotlib.gridspec import GridSpec\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom mpl_toolkits.mplot3d.art3d import Line3DCollection\nfrom matplotlib.ticker import FormatStrFormatter\n\ndef _update_limits(ax, x, y, z=None, add_xrange=True, first_plot=True, same_axis=False):\n # Update limits\n yrange_ = y.max() - y.min()\n xmin = x.min()\n xmax = x.max()\n if add_xrange:\n xrange_ = x.max() - x.min()\n xmin -= 0.1*xrange_\n xmax += 0.1*xrange_\n ymin = y.min()-0.1*yrange_\n ymax = y.max()+0.1*yrange_\n if z is not None:\n zrange_ = z.max() - z.min()\n zmin = x.min() - 0.1*zrange_\n zmax = x.max() + 0.1*zrange_\n if not first_plot:\n xlim = ax.get_xlim()\n ylim = ax.get_ylim()\n xmin = min(xmin, xlim[0])\n xmax = max(xmax, xlim[1])\n ymin = min(ymin, ylim[0])\n ymax = max(ymax, ylim[1])\n if z is not None:\n zlim = ax.get_zlim()\n zmin = min(zmin, zlim[0])\n zmax = max(zmax, zlim[1])\n if same_axis:\n if z is None:\n xmin = min(xmin, ymin)\n ymin = xmin\n xmax = max(xmax, ymax)\n ymax = xmax\n else:\n xmin = min(xmin, ymin, zmin)\n ymin = xmin\n zmin = xmin\n xmax = max(xmax, ymax, zmax)\n ymax = xmax\n zmax = xmax\n\n ax.set_xlim([xmin, xmax])\n ax.set_ylim([ymin, ymax])\n if z is not None:\n ax.set_zlim([zmin, zmax])\n return ax\n\n\ndef _plot_1d(x, smooth=False, fig=None, same_axis=False):\n \"\"\"\n Plots a 1D plot of x vs the frame number. Colors the datapoints from yellow to purple \n to show time progression. Can be called multiple times by passing the return\n figure as input.\n \"\"\"\n if fig is None:\n fig = plt.figure(figsize=(8,4))\n first_plot = True\n else:\n first_plot = False\n ax = fig.gca()\n ax.yaxis.grid(True, alpha=0.4)\n ax.set_xlabel('Frame', fontsize=16)\n ax.set_ylabel('PC', fontsize=16)\n ax.tick_params(axis='both', labelsize=12)\n\n if smooth:\n k = 2\n else:\n k = 1\n\n tck, u = interpolate.splprep([np.arange(x.shape[0]), x], k=k, s=0.0)\n x_i, y_i = interpolate.splev(np.linspace(0, 1, 1000), tck)\n\n # Gradient color change magic\n z = np.linspace(0.0, 1.0, x_i.shape[0])\n points = np.array([x_i, y_i]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n lc = LineCollection(segments, array=z, cmap='viridis', norm=plt.Normalize(0.0, 1.0), alpha=0.8, linewidth=2)\n ax.add_collection(lc)\n\n ax = _update_limits(ax, x_i, y_i, add_xrange=False, first_plot=first_plot, same_axis=same_axis)\n\n return fig\n\ndef _plot_2d(x, y, smooth=False, fig=None, same_axis=False):\n \"\"\"\n Plots a 2D plot of x vs y. Colors the datapoints from yellow to purple \n to show time progression. Can be called multiple times by passing the return\n figure as input.\n \"\"\"\n if fig is None:\n fig = plt.figure(figsize=(5, 5))\n #gs = GridSpec(1, 2)\n #ax0 = fig.add_subplot(gs[0])\n first_plot = True\n else:\n first_plot = False\n ax0 = fig.gca()\n ax0.grid(True, alpha=0.4)\n\n ax0.set_xlabel('PC1', fontsize=16)\n ax0.set_ylabel('PC2', fontsize=16)\n ax0.tick_params(axis='both', labelsize=12)\n\n if smooth:\n k = 2\n else:\n k = 1\n\n tck, u = interpolate.splprep([x, y], k=k, s=0.0)\n x_i, y_i = interpolate.splev(np.linspace(0, 1, 1000), tck)\n\n # Gradient color change magic\n z = np.linspace(0.0, 1.0, x_i.shape[0])\n points = np.array([x_i, y_i]).T.reshape(-1, 1, 2)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n lc = LineCollection(segments, array=z, cmap='viridis', norm=plt.Normalize(0.0, 1.0), alpha=0.8, linewidth=2)\n ax0.add_collection(lc)\n\n ax0 = _update_limits(ax0, x_i, y_i, first_plot=first_plot, same_axis=same_axis)\n\n return fig\n\ndef _plot_3d(x, y, z, smooth=False, fig=None, same_axis=False):\n \"\"\"\n Plots a 3D plot of x, y, z. Colors the datapoints from yellow to purple \n to show time progression. Can be called multiple times by passing the return\n figure as input.\n \"\"\"\n if fig is None:\n fig = plt.figure(figsize=(5, 5))\n #gs = GridSpec(1, 2)\n #ax0 = fig.add_subplot(gs[0])\n ax0 = fig.add_subplot(111, projection='3d')\n first_plot = True\n else:\n ax0 = fig.axes[0]\n first_plot = False\n ax0.grid(True, alpha=0.4)\n\n ax0.set_xlabel('PC1', fontsize=16, labelpad=10)\n ax0.set_ylabel('PC2', fontsize=16, labelpad=10)\n ax0.set_zlabel('PC3', fontsize=16, labelpad=10)\n ax0.tick_params(axis='both', labelsize=12)\n #ax0.ticklabel_format(style='sci', scilimits=(-3,3))\n\n if smooth:\n k = 2\n else:\n k = 1\n\n tck, u = interpolate.splprep([x, y, z], k=k, s=0.0)\n x_i, y_i, z_i = interpolate.splev(np.linspace(0, 1, 1000), tck)\n\n # Gradient color change magic\n t = np.linspace(0.0, 1.0, x_i.shape[0])\n points = np.array([x_i, y_i, z_i]).T.reshape(-1, 1, 3)\n segments = np.concatenate([points[:-1], points[1:]], axis=1)\n lc = Line3DCollection(segments, array=t, cmap='viridis', norm=plt.Normalize(0.0, 1.0), alpha=0.8, linewidth=2)\n ax0.add_collection(lc)\n\n ax0 = _update_limits(ax0, x_i, y_i, z_i, first_plot=first_plot, same_axis=same_axis)\n\n return fig\n\n# TODO support for multiple subplots\ndef colorplot(x, smooth=False, image_name=None, same_axis=False):\n \"\"\"\n Create a 1-3D plot.\n\n :param x: Data to plot. Should be of shape (n,m), with m being between 1 and 3.\n :type x: array\n :param smooth: Whether or not to smooth the line between data points with a spline.\n :type smooth: bool\n :param image_name: Full location to store the image. If `None`, the image will be displayed\n instead.\n :type image_name: string\n :param same_axis: Force the same limits to be used on all axes in the plot\n :type same_axis: bool\n \"\"\"\n def get_dimensionality(x):\n if isinstance(x, list) or (isinstance(x, np.ndarray) and (x.dtype == object or x.ndim == 3)):\n if len(x) > 0 and isinstance(x[0], np.ndarray):\n array_sizes = [array.ndim for array in x]\n if len(set(array_sizes)) > 1:\n raise SystemExit(\"Error. Expected and 1D or 2D array or list of arrays of similar shape.\")\n if array_sizes[0] > 2 or array_sizes[0] < 1:\n raise SystemExit(\"Error. Expected an 1D or 2D array. Got %dD.\" % x.ndim)\n if array_sizes[0] == 1:\n m = 1\n else:\n dimension_sizes = [array.shape[1] for array in x]\n if len(set(dimension_sizes)) > 1:\n raise SystemExit(\"Error. Inconsistent dimensionality of arrays.\")\n\n m = x[0].shape[1]\n return m, True\n else:\n raise SystemExit(\"Error. Expected an 1D or 2D array or list of arrays of similar shape.\")\n elif x.ndim > 2 or x.ndim == 0:\n raise SystemExit(\"Error. Expected an 1D or 2D array. Got %dD.\" % x.ndim)\n elif x.ndim == 1:\n m = 1\n else:\n m = x.shape[1]\n\n return m, False\n\n m, multi_array = get_dimensionality(x)\n\n fig = None\n if m == 1:\n if multi_array:\n for array in x:\n fig = _plot_1d(array.ravel(), smooth=smooth, fig=fig, same_axis=same_axis)\n else:\n fig = _plot_1d(x.ravel(), smooth=smooth, same_axis=same_axis)\n elif m == 2:\n if multi_array:\n for array in x:\n fig = _plot_2d(array[:,0] + 1, array[:,1], smooth=smooth, fig=fig, same_axis=same_axis)\n else:\n fig = _plot_2d(x[:,0], x[:,1], smooth=smooth, same_axis=same_axis)\n elif m == 3:\n if multi_array:\n for array in x:\n fig = _plot_3d(array[:,0], array[:,1], array[:,2], fig=fig, same_axis=same_axis)\n else:\n fig = _plot_3d(x[:,0], x[:,1], x[:,2], same_axis=same_axis)\n else:\n raise SystemExit(\"Error. Only 1-3D plots are supported, while the given input \\\n had %d dimension.\" % m)\n\n fig.tight_layout(pad=5)\n fig.subplots_adjust(top=0.88, wspace=0.02)\n\n if image_name is None:\n plt.show()\n else:\n plt.savefig(image_name, dpi=600)\n plt.clf()\n"
]
| [
[
"numpy.linspace",
"numpy.arange",
"scipy.interpolate.splprep",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.Normalize",
"numpy.concatenate",
"matplotlib.pyplot.clf",
"numpy.array",
"matplotlib.pyplot.show",
"matplotlib.pyplot.figure"
]
]
|
jackapbutler/Genetics | [
"fe581898ce151fc7f9bc357b6c330e2b824d4d16"
]
| [
"lung-cancer/lung-cancer.py"
]
| [
"# Data from https://www.kaggle.com/josemauricioneuro/lung-cancer-patients-mrna-microarray\nDATA_PATH = \"./data/complete_dataframe.csv\"\n\n\nimport pandas as pd\nfrom sklearn.ensemble import AdaBoostClassifier\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\n\nimport utils\n\ndf = pd.read_csv(DATA_PATH)\ndf = df.dropna(thresh=int(0.05 * len(df)))\ndf = df.drop(\n [\n \"BlindedIDs\",\n \"PATIENT_ID\",\n \"Unnamed: 0\",\n \"WARNING\",\n \"DC_STUDY_ID\",\n \"LABORATORY_BATCH\",\n \"MONTHS_TO_LAST_CONTACT_OR_DEATH\",\n \"target\",\n \"MTHS_TO_LAST_CLINICAL_ASSESSMENT\",\n \"MONTHS_TO_FIRST_PROGRESSION\",\n ],\n axis=1,\n)\n\nPATIENT_COLS = [\n \"Stratagene\",\n \"SITE\",\n \"TESTTYPE\",\n \"IN_DC_STUDY\",\n \"GENDER\",\n \"AGE_AT_DIAGNOSIS\",\n \"RACE\",\n \"ADJUVANT_CHEMO\",\n \"ADJUVANT_RT\",\n \"VITAL_STATUS\",\n \"FIRST_PROGRESSION_OR_RELAPSE\",\n \"MONTHS_TO_FIRST_PROGRESSION\",\n \"MTHS_TO_LAST_CLINICAL_ASSESSMENT\",\n \"MONTHS_TO_LAST_CONTACT_OR_DEATH\",\n \"SMOKING_HISTORY\",\n \"SURGICAL_MARGINS\",\n \"PATHOLOGIC_N_STAGE\",\n \"PATHOLOGIC_T_STAGE\",\n \"MEDIAN_INTENSITY_UNNORMALIZED\",\n \"PCT_ARRAY_OUTLIER\",\n \"PCT_SINGLE_OUTLIER\",\n \"LABORATORY_BATCH\",\n \"Histologic grade\",\n]\nTARGET_COL = \"High_risk\" # look at months since dead/contact for more information\nGENE_COLS = list(set(list(df.columns)) - set(PATIENT_COLS) - set([TARGET_COL]))\n\ndf = utils.one_hot_encode(df)\ndf = utils.cast_to_floats(df)\n\nutils.missing_values_report(df)\n\ny = df.pop(TARGET_COL)\ndf = StandardScaler().fit_transform(df)\n\nX_train, X_test, y_train, y_test = train_test_split(df, y, test_size=0.20)\n\nlog = LogisticRegression(C=0.05, solver=\"lbfgs\", max_iter=500)\nsvm = SVC(probability=True)\nknn = KNeighborsClassifier(n_neighbors=10)\nadaboost = AdaBoostClassifier(n_estimators=50, learning_rate=0.01)\n\nLABELS = [\"High risk\", \" Low risk\"]\n\nfor model, name in zip(\n [log, svm, adaboost, knn], [\"Logistic Regression\", \"SVM\", \"AdaBoost\", \"KNN\"]\n):\n utils.model_algorithm(model, X_train, y_train, X_test, y_test, name, LABELS)\n"
]
| [
[
"pandas.read_csv",
"sklearn.linear_model.LogisticRegression",
"sklearn.model_selection.train_test_split",
"sklearn.neighbors.KNeighborsClassifier",
"sklearn.ensemble.AdaBoostClassifier",
"sklearn.svm.SVC",
"sklearn.preprocessing.StandardScaler"
]
]
|
jaidevshriram/cross-view | [
"844b4ded335e31fe3144adb412792221703d5246"
]
| [
"test.py"
]
| [
"import argparse\nimport glob\nimport os\n\nimport PIL.Image as pil\n\nimport cv2\n\nfrom crossView import model, CrossViewTransformer, CycledViewProjection\n\nimport numpy as np\n\nimport torch\n\nfrom torchvision import transforms\n\nfrom easydict import EasyDict as edict\nimport matplotlib.pyplot as PLT\n\n\ndef get_args():\n parser = argparse.ArgumentParser(\n description=\"Testing options\")\n parser.add_argument(\"--image_path\", type=str,\n help=\"path to folder of images\", required=True)\n parser.add_argument(\"--model_path\", type=str,\n help=\"path to MonoLayout model\", required=True)\n parser.add_argument(\n \"--ext\",\n type=str,\n default=\"png\",\n help=\"extension of images in the folder\")\n parser.add_argument(\"--out_dir\", type=str,\n default=\"output directory to save topviews\")\n parser.add_argument(\"--type\", type=str,\n default=\"static/dynamic/both\")\n parser.add_argument(\"--view\", type=str, default=1, help=\"view number\")\n parser.add_argument(\n \"--split\",\n type=str,\n choices=[\n \"argo\",\n \"3Dobject\",\n \"odometry\",\n \"raw\"],\n help=\"Data split for training/validation\")\n\n configs = edict(vars(parser.parse_args()))\n return configs\n\n\ndef save_topview(idx, tv, name_dest_im):\n tv_np = tv.squeeze().cpu().numpy()\n true_top_view = np.zeros((tv_np.shape[1], tv_np.shape[2]))\n true_top_view[tv_np[1] > tv_np[0]] = 255\n dir_name = os.path.dirname(name_dest_im)\n if not os.path.exists(dir_name):\n os.makedirs(dir_name)\n cv2.imwrite(name_dest_im, true_top_view)\n\n print(\"Saved prediction to {}\".format(name_dest_im))\n\n\ndef test(args):\n models = {}\n device = torch.device(\"cuda\")\n encoder_path = os.path.join(args.model_path, \"encoder.pth\")\n encoder_dict = torch.load(encoder_path, map_location=device)\n feed_height = encoder_dict[\"height\"]\n feed_width = encoder_dict[\"width\"]\n models[\"encoder\"] = model.Encoder(18, feed_width, feed_height, False)\n filtered_dict_enc = {\n k: v for k,\n v in encoder_dict.items() if k in models[\"encoder\"].state_dict()}\n models[\"encoder\"].load_state_dict(filtered_dict_enc)\n\n CVP_path = os.path.join(args.model_path, \"CycledViewProjection.pth\")\n CVP_dict = torch.load(CVP_path, map_location=device)\n models['CycledViewProjection'] = CycledViewProjection(in_dim=8)\n filtered_dict_cvp = {\n k: v for k,\n v in CVP_dict.items() if k in models[\"CycledViewProjection\"].state_dict()}\n models[\"CycledViewProjection\"].load_state_dict(filtered_dict_cvp)\n\n CVT_path = os.path.join(args.model_path, \"CrossViewTransformer.pth\")\n CVT_dict = torch.load(CVT_path, map_location=device)\n models['CrossViewTransformer'] = CrossViewTransformer(128)\n filtered_dict_cvt = {\n k: v for k,\n v in CVT_dict.items() if k in models[\"CrossViewTransformer\"].state_dict()}\n models[\"CrossViewTransformer\"].load_state_dict(filtered_dict_cvt)\n\n decoder_path = os.path.join(args.model_path, \"decoder.pth\")\n DEC_dict = torch.load(decoder_path, map_location=device)\n models[\"decoder\"] = model.Decoder(\n models[\"encoder\"].resnet_encoder.num_ch_enc)\n filtered_dict_dec = {\n k: v for k,\n v in DEC_dict.items() if k in models[\"decoder\"].state_dict()}\n models[\"decoder\"].load_state_dict(filtered_dict_dec)\n\n transform_decoder_path = os.path.join(args.model_path, \"transform_decoder.pth\")\n TRDEC_dict = torch.load(transform_decoder_path, map_location=device)\n models[\"transform_decoder\"] = model.Decoder(\n models[\"encoder\"].resnet_encoder.num_ch_enc)\n filtered_dict_trdec = {\n k: v for k,\n v in TRDEC_dict.items() if k in models[\"transform_decoder\"].state_dict()}\n models[\"transform_decoder\"].load_state_dict(filtered_dict_trdec)\n\n for key in models.keys():\n models[key].to(device)\n models[key].eval()\n\n if os.path.isfile(args.image_path):\n # Only testing on a single image\n paths = [args.image_path]\n output_directory = os.path.dirname(args.image_path)\n elif os.path.isdir(args.image_path):\n # Searching folder for images\n if args.split == \"argo\":\n paths = glob.glob(os.path.join(\n args.image_path, '*/ring_front_center/*.{}'.format(args.ext)))\n else:\n paths = glob.glob(os.path.join(\n args.image_path, '*.{}'.format(args.ext)))\n\n output_directory = args.out_dir\n try:\n os.mkdir(output_directory)\n except BaseException:\n pass\n else:\n raise Exception(\n \"Can not find args.image_path: {}\".format(\n args.image_path))\n\n print(\"-> Predicting on {:d} test images\".format(len(paths)))\n\n # PREDICTING ON EACH IMAGE IN TURN\n with torch.no_grad():\n for idx, image_path in enumerate(paths):\n\n # Load image and preprocess\n input_image = pil.open(image_path).convert('RGB')\n original_width, original_height = input_image.size\n input_image = input_image.resize(\n (feed_width, feed_height), pil.LANCZOS)\n input_image = transforms.ToTensor()(input_image).unsqueeze(0)\n # PREDICTION\n input_image = input_image.to(device)\n\n features = models[\"encoder\"](input_image)\n\n transform_feature, retransform_features = models[\"CycledViewProjection\"](features)\n features = models[\"CrossViewTransformer\"](features, transform_feature, retransform_features)\n\n output_name = os.path.splitext(os.path.basename(image_path))[0]\n print(\"Processing {:d} of {:d} images- \".format(idx + 1, len(paths)))\n tv = models[\"decoder\"](features, is_training=False)\n transform_tv = models[\"transform_decoder\"](transform_feature, is_training=False)\n\n save_topview(\n idx,\n tv,\n os.path.join(\n args.out_dir,\n args.type,\n \"{}.png\".format(output_name)))\n\n print('-> Done!')\n\n\nif __name__ == \"__main__\":\n args = get_args()\n test(args)\n"
]
| [
[
"torch.device",
"torch.no_grad",
"numpy.zeros",
"torch.load"
]
]
|
WLM1ke/aiomoex | [
"dd7f6c4cb9482d0a3185c340274a4d4d42e15a9f"
]
| [
"tests/test_history.py"
]
| [
"import pytest\nimport pandas as pd\n\nfrom aiomoex import history\n\n\[email protected]\nasync def test_get_board_dates(http_session):\n data = await history.get_board_dates(http_session)\n assert isinstance(data, list)\n assert len(data) == 1\n assert data[0][\"from\"] == \"1997-03-24\"\n assert data[0][\"till\"] >= \"2018-11-27\"\n\n\[email protected]\nasync def test_get_board_securities(http_session):\n data = await history.get_board_securities(http_session)\n assert isinstance(data, list)\n assert len(data) > 200\n df = pd.DataFrame(data)\n df.set_index(\"SECID\", inplace=True)\n assert df.loc[\"AKRN\", \"SHORTNAME\"] == \"ะะบัะพะฝ\"\n assert df.loc[\"GAZP\", \"REGNUMBER\"] == \"1-02-00028-A\"\n assert df.loc[\"TTLK\", \"LOTSIZE\"] == 10000\n assert df.loc[\"MRSB\", \"SHORTNAME\"] == \"ะะพัะดะญะฝะกะฑ\"\n assert df.loc[\"MRSB\", \"REGNUMBER\"] == \"1-01-55055-E\"\n assert df.loc[\"MRSB\", \"LOTSIZE\"] == 10000\n assert df.index[0] == \"ABRD\"\n assert df[\"SHORTNAME\"].iat[0] == \"ะะฑัะฐัะัััะพ\"\n assert df[\"REGNUMBER\"].iat[0] == \"1-02-12500-A\"\n assert df[\"LOTSIZE\"].iat[0] == 10\n assert df[\"SHORTNAME\"].iat[-1] == \"ะะะะะะ ะฐะพ\"\n assert df[\"REGNUMBER\"].iat[-1] == \"1-01-00169-D\"\n assert df[\"LOTSIZE\"].iat[-1] == 1000\n assert df.index[-1] == \"ZVEZ\"\n\n\[email protected]\nasync def test_get_market_history_from_beginning(http_session):\n data = await history.get_market_history(http_session, \"AKRN\", end=\"2006-12-01\")\n assert isinstance(data, list)\n assert data[0][\"TRADEDATE\"] == \"2006-10-11\"\n assert data[-1][\"TRADEDATE\"] == \"2006-12-01\"\n assert len(data[-2]) == 5\n assert \"CLOSE\" in data[2]\n assert \"VOLUME\" in data[3]\n\n\[email protected]\nasync def test_get_market_history_to_end(http_session):\n data = await history.get_market_history(http_session, \"MOEX\", start=\"2017-10-02\")\n assert isinstance(data, list)\n assert len(data) > 100\n assert data[0][\"TRADEDATE\"] == \"2017-10-02\"\n assert data[-1][\"TRADEDATE\"] >= \"2018-11-19\"\n\n\[email protected]\nasync def test_get_board_history_from_beginning(http_session):\n data = await history.get_board_history(http_session, \"LSNGP\", end=\"2014-08-01\")\n df = pd.DataFrame(data)\n df.set_index(\"TRADEDATE\", inplace=True)\n assert len(df.columns) == 4\n assert df.index[0] == \"2014-06-09\"\n assert df.at[\"2014-06-09\", \"CLOSE\"] == pytest.approx(14.7)\n assert df.at[\"2014-08-01\", \"VOLUME\"] == 4000\n\n\[email protected]\nasync def test_get_board_history_to_end(http_session):\n data = await history.get_board_history(http_session, \"LSRG\", start=\"2018-08-07\")\n df = pd.DataFrame(data)\n df.set_index(\"TRADEDATE\", inplace=True)\n assert len(df.columns) == 4\n assert df.index[0] == \"2018-08-07\"\n assert df.index[-1] >= \"2018-11-19\"\n assert df.at[\"2018-08-07\", \"CLOSE\"] == 777\n assert df.at[\"2018-08-10\", \"VOLUME\"] == 11313\n assert df.at[\"2018-08-10\", \"BOARDID\"] == \"TQBR\"\n assert df.at[\"2018-08-10\", \"VALUE\"] == pytest.approx(8_626_464.5)\n assert df.at[\"2018-09-06\", \"CLOSE\"] == pytest.approx(660)\n assert df.at[\"2018-08-28\", \"VOLUME\"] == 47428\n"
]
| [
[
"pandas.DataFrame"
]
]
|
mbirkholzupc/urlproj | [
"bace4bc0462acab3ee29d2a9f9ef583747f7bc30"
]
| [
"data/household_preprocess.py"
]
| [
"\"\"\"\n.. module:: pamap2_preprocess.py\n\n*************\n\n:Description: Script to preprocess the household power consumption dataset. In particular,\n the preprocessing is:\n - Deal with missing values marked with '?'\n - Drop date/time columns\n\n:Authors: birkholz\n\n:License: BSD 3 clause\n\n:Version:\n\n:Created on:\n\n\"\"\"\nimport sys\n\nsys.path.insert(1, '../kemlglearn/')\n\nimport argparse\nimport csv\nimport math\n\nimport pandas as pd\nimport numpy as np\nfrom scipy.spatial import distance, distance_matrix\nimport matplotlib.pyplot as plt\nfrom sklearn.datasets import make_blobs, make_moons\nfrom sklearn.decomposition import PCA\nfrom sklearn.preprocessing import MinMaxScaler\n\n\nfrom kemlglearn.cluster.DBSCAN import DBSCAN\n\n# Random-number generator\nthe_rng = np.random.default_rng()\n\n__author__ = 'birkholz'\n\n# Helper function to plot DBSCAN results based on DBSCAN example in scikit-learn user guide\n# If data has more than two dimensions, the first two will be used\ndef plot_dbscan_results(x, labels, core_sample_indices):\n core_samples_mask=np.zeros_like(labels, dtype=bool)\n core_samples_mask[core_sample_indices] = True\n n_clusters_=len(set(labels))-(1 if -1 in labels else 0)\n n_noise_ = list(labels).count(-1)\n\n unique_labels = set(labels)\n colors = [plt.cm.Spectral(each) for each in np.linspace(0, 1, len(unique_labels))]\n\n for k, col in zip(unique_labels, colors):\n if k == -1:\n col = [0, 0, 0, 1] # Black for noise\n\n class_member_mask = (labels == k)\n\n xy = x[class_member_mask & core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n markeredgecolor='k', markersize=14)\n\n xy = x[class_member_mask & ~core_samples_mask]\n plt.plot(xy[:, 0], xy[:, 1], 'o', markerfacecolor=tuple(col),\n markeredgecolor='k', markersize=6)\n\n # Show clusters (and noise)\n plt.title(f'Estimated number of clusters: {n_clusters_}')\n plt.show()\n\nif __name__ == '__main__':\n ap=argparse.ArgumentParser()\n ap.add_argument(\"-f\", \"--filename\", required=True, help=\"path to input data file household_power_consumption.txt. Can be downloaded from: https://archive.ics.uci.edu/ml/machine-learning-databases/00235/household_power_consumption.zip\")\n #ap.add_argument(\"-g\", \"--generate\", help=\"type of data to generate on the fly\")\n #ap.add_argument(\"-c\", \"--count\", help=\"limit to count samples(file input only)\")\n ap.add_argument(\"-s\", \"--seed\", help=\"random seed (only applicable with count)\")\n args=vars(ap.parse_args())\n\n # Set random seed, if specified. Otherwise, will default to rng with unspecified seed.\n if args['seed']:\n the_rng=np.random.default_rng(int(args['seed']))\n\n # Read in data file\n df = pd.read_csv(args['filename'], delimiter=';')\n print(df)\n\n # Drop date and time columns\n df=df.drop('Date',axis=1)\n df=df.drop('Time',axis=1)\n print(df)\n\n # Drop any rows still containing non-numeric measurements\n before_rows=df.shape[0]\n df=df.apply(pd.to_numeric, errors='coerce')\n df=df.dropna()\n df=df.reset_index(drop=True)\n after_rows=df.shape[0]\n percent_dropped=100*(before_rows-after_rows)/before_rows\n print(f'Dropped {percent_dropped:1.2f}% of data')\n print(df)\n\n # Normalize each feature to range [0, 1e5]\n nparr=df.to_numpy()\n scaler=MinMaxScaler((0,1e5))\n scaler.fit(nparr)\n nparr=scaler.transform(nparr)\n\n df=pd.DataFrame(nparr)\n df.to_csv('householdpreprocessed.csv', header=False, index=False, float_format='%1.1f')\n\n exit(0)\n"
]
| [
[
"matplotlib.pyplot.cm.Spectral",
"pandas.read_csv",
"matplotlib.pyplot.title",
"pandas.DataFrame",
"numpy.zeros_like",
"sklearn.preprocessing.MinMaxScaler",
"matplotlib.pyplot.show",
"numpy.random.default_rng"
]
]
|
tmtenbrink/rustfrc | [
"e5bdebb60f6fd3064f120229649b5165d017e7e3"
]
| [
"test.py"
]
| [
"import python.rustfrc as r\nimport numpy as np\nimport time\n\ninit_x = (np.ones((900, 700, 100))*24.31)\ninit_y = (np.ones((900, 700, 100))*30).astype(np.int32)\ninit_z = np.ones((900, 700, 50))*30\n\n\n# start = time.perf_counter()\n# x = r.binom_split(init_x)\n# end = time.perf_counter()\n# print(str(end - start) + \" s\")\n#\n#\n# start2 = time.perf_counter()\n# rng = np.random.default_rng()\n# y = rng.binomial(init_y, 0.5)\n# end2 = time.perf_counter()\n# print(str(end2 - start2) + \" s\")"
]
| [
[
"numpy.ones"
]
]
|
bihanli/yolactBH | [
"756bc91c5110e532abe75729c905f70cfb988c23"
]
| [
"data/coco/annotations/cocosplit.py"
]
| [
"import json\nimport argparse\nimport funcy\nfrom sklearn.model_selection import train_test_split\n\nparser = argparse.ArgumentParser(description='Splits COCO annotations file into training and test sets.')\nparser.add_argument('annotations', metavar='coco_annotations', type=str,\n help='Path to COCO annotations file.')\nparser.add_argument('train', type=str, help='Where to store COCO training annotations')\nparser.add_argument('test', type=str, help='Where to store COCO test annotations')\nparser.add_argument('-s', dest='split', type=float, required=True,\n help=\"A percentage of a split; a number in (0, 1)\")\nparser.add_argument('--having-annotations', dest='having_annotations', action='store_true',\n help='Ignore all images without annotations. Keep only these with at least one annotation')\n\nargs = parser.parse_args()\n\ndef save_coco(file, images, annotations, categories):\n with open(file, 'wt', encoding='UTF-8') as coco:\n json.dump({ 'images': images, 'annotations': annotations, 'categories': categories}, coco, indent=2, sort_keys=True)\n\ndef filter_annotations(annotations, images):\n image_ids = funcy.lmap(lambda i: int(i['id']), images)\n return funcy.lfilter(lambda a: int(a['image_id']) in image_ids, annotations)\n\ndef main(args):\n with open(args.annotations, 'rt', encoding='UTF-8') as annotations:\n coco = json.load(annotations)\n #info = coco['info']\n #licenses = coco['licenses']\n images = coco['images']\n annotations = coco['annotations']\n categories = coco['categories']\n\n number_of_images = len(images)\n\n images_with_annotations = funcy.lmap(lambda a: int(a['image_id']), annotations)\n\n if args.having_annotations:\n images = funcy.lremove(lambda i: i['id'] not in images_with_annotations, images)\n\n x, y = train_test_split(images, train_size=args.split)\n\n save_coco(args.train, x, filter_annotations(annotations, x), categories)\n save_coco(args.test, y, filter_annotations(annotations, y), categories)\n\n print(\"Saved {} entries in {} and {} in {}\".format(len(x), args.train, len(y), args.test))\n\n\nif __name__ == \"__main__\":\n main(args)"
]
| [
[
"sklearn.model_selection.train_test_split"
]
]
|
ShanRaye/sqlalchemy-challenge | [
"7f8d71cd73ad16a37c5412ba407acba1197b26be"
]
| [
"app.py"
]
| [
"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\nimport pandas as pd\nimport datetime as dt\n\nfrom flask import Flask, jsonify\n\nengine = create_engine(\"sqlite:///Resources/hawaii.sqlite\")\n\n# reflect an existing database into a new model\nBase = automap_base()\n# reflect the tables\nBase.prepare(engine, reflect=True)\n\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\n\napp = Flask(__name__)\n\[email protected](\"/\")\ndef welcome():\n \"\"\"List all available api routes.\"\"\"\n return (\n f\"Available Routes:<br/>\"\n f\"/api/v1.0/precipitation<br/>\"\n f\"/api/v1.0/stations<br/>\"\n f\"/api/v1.0/tobs<br/>\"\n f\"/api/v1.0/<start><br/>\"\n f\"/api/v1.0/<start>/<end>\"\n )\n\[email protected](\"/api/v1.0/precipitation\")\ndef precipitation():\n latest_date = dt.date(2017, 8 ,23)\n a_year_ago = latest_date - dt.timedelta(days=365)\n session = Session(engine)\n date_prcp = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date.between(a_year_ago, latest_date)).all()\n session.close()\n date_precipitation = {date: prcp for date, prcp in date_prcp}\n return jsonify(date_precipitation)\n\[email protected](\"/api/v1.0/stations\")\ndef stations():\n session = Session(engine)\n all_stations = session.query(Station.station).all()\n session.close()\n return jsonify(all_stations)\n\[email protected](\"/api/v1.0/tobs\")\ndef tobs():\n latest_date = dt.date(2017, 8 ,23)\n a_year_ago = latest_date - dt.timedelta(days=365)\n session = Session(engine)\n date_tobs = session.query(Measurement.tobs).\\\n filter(Measurement.station == \"USC00519281\").\\\n filter(Measurement.date.between(a_year_ago, latest_date)).all()\n session.close()\n return jsonify(date_tobs)\n\[email protected](\"/api/v1.0/<start>\")\ndef statrt(start = None):\n latest_date = dt.date(2017, 8 ,23)\n session = Session(engine)\n tobs_start_only = session.query(Measurement.tobs).filter(Measurement.date.between(start, latest_date)).all()\n session.close()\n tobs_start_only_df = pd.DataFrame(tobs_start_only)\n tmin = tobs_start_only_df[\"tobs\"].min()\n tmax = tobs_start_only_df[\"tobs\"].max()\n tavg = tobs_start_only_df[\"tobs\"].mean()\n return jsonify(tmin, tmax, tavg)\n\[email protected](\"/api/v1.0/<start>/<end>\")\ndef startend(start = None, end = None):\n session = Session(engine)\n tobs_start_only = session.query(Measurement.tobs).filter(Measurement.date.between(start, end)).all()\n session.close()\n tobs_start_only_df = pd.DataFrame(tobs_start_only)\n tmin = tobs_start_only_df[\"tobs\"].min()\n tmax = tobs_start_only_df[\"tobs\"].max()\n tavg = tobs_start_only_df[\"tobs\"].mean()\n return jsonify(tmin, tmax, tavg)\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n"
]
| [
[
"pandas.DataFrame"
]
]
|
bundocka/fast-carpenter | [
"fa90ba6fb28a73c5de4be53daebc7af9889f2478"
]
| [
"fast_carpenter/expressions.py"
]
| [
"import numpy as np\nimport re\nimport numexpr\nimport tokenize\nimport awkward\nimport logging\ntry:\n from StringIO import StringIO\nexcept ImportError:\n from io import StringIO\n\nlogger = logging.getLogger(__name__)\n\n\n__all__ = [\"get_branches\", \"evaluate\"]\n\n\nconstants = {\"nan\": np.nan,\n \"inf\": np.inf,\n \"pi\": np.pi,\n \"e\": np.e,\n }\n\n\ndef get_branches(cut, valid):\n valid = [v.decode(\"utf-8\") for v in valid]\n\n branches = []\n string = StringIO(cut).readline\n tokens = tokenize.generate_tokens(string)\n current_branch = []\n for toknum, tokval, _, _, _ in tokens:\n if toknum == tokenize.NAME:\n if \".\".join(current_branch + [tokval]) in valid:\n current_branch.append(tokval)\n continue\n if tokval == \".\":\n continue\n if current_branch:\n branches.append(\".\".join(current_branch))\n current_branch = []\n return branches\n\n\ndef deconstruct_jaggedness(array, counts):\n if not isinstance(array, awkward.array.base.AwkwardArrayWithContent):\n return array, counts\n\n array = array.compact()\n counts.insert(0, array.counts)\n return deconstruct_jaggedness(array.content, counts)\n\n\ndef reconstruct_jaggedness(array, counts):\n for count in counts:\n array = awkward.JaggedArray.fromcounts(count, array)\n return array\n\n\nclass TreeToDictAdaptor():\n \"\"\"\n Make an uproot tree look like a dict for numexpr\n \"\"\"\n def __init__(self, tree, alias_dict, needed_variables):\n self.tree = tree\n self.aliases = alias_dict\n self.vars, self.counts = self.broadcast_variables(needed_variables)\n\n def broadcast_variables(self, variables):\n arrays = {}\n most_jagged = (-1, None)\n for var in variables:\n if var in constants:\n continue\n array = self.get_raw(var)\n contents, counts = deconstruct_jaggedness(array, counts=[])\n arrays[var] = (contents, counts, array)\n if len(counts) > most_jagged[0]:\n most_jagged = (len(counts), var)\n most_jagged = most_jagged[1]\n\n broadcast_to = arrays[most_jagged][1]\n broadcast_vars = {most_jagged: arrays[most_jagged]}\n for var, (contents, counts, raw) in arrays.items():\n if var == most_jagged:\n continue\n\n # Check broadcastable\n for left, right in zip(broadcast_to, counts):\n if not np.array_equal(left, right):\n raise ValueError(\"Unable to broadcast all values\")\n for copies in broadcast_to[len(counts):]:\n contents = np.repeat(contents, copies)\n\n broadcast_vars[var] = (contents, broadcast_to, raw)\n return broadcast_vars, broadcast_to\n\n def __getitem__(self, item):\n if item in constants:\n return constants[item]\n result = self.vars[item][0]\n return result\n\n def get_raw(self, item):\n if item in constants:\n return constants[item]\n full_item = self.aliases.get(item, item)\n array = self.tree.array(full_item)\n return array\n\n def __contains__(self, item):\n return item in self.vars\n\n def __iter__(self):\n for i in self.vars:\n yield i\n\n def apply_jaggedness(self, array):\n if self.counts is None:\n return array\n result = reconstruct_jaggedness(array, self.counts)\n return result\n\n\nattribute_re = re.compile(r\"([a-zA-Z]\\w*)\\s*(\\.\\s*(\\w+))+\")\n\n\ndef preprocess_expression(expression):\n alias_dict = {}\n replace_dict = {}\n for match in attribute_re.finditer(expression):\n original = match.group(0)\n alias = original.replace('.', '__DOT__')\n alias_dict[alias] = original\n replace_dict[original] = alias\n clean_expr = attribute_re.sub(lambda x: replace_dict[x.group(0)], expression)\n return clean_expr, alias_dict\n\n\ndef evaluate(tree, expression):\n cleaned_expression, alias_dict = preprocess_expression(expression)\n context = numexpr.necompiler.getContext({}, frame_depth=1)\n variables = numexpr.necompiler.getExprNames(cleaned_expression, context)[0]\n try:\n adaptor = TreeToDictAdaptor(tree, alias_dict, variables)\n except ValueError:\n msg = \"Cannot broadcast all variables in expression: %s\" % expression\n logger.error(msg)\n raise ValueError(msg)\n result = numexpr.evaluate(cleaned_expression, local_dict=adaptor)\n result = adaptor.apply_jaggedness(result)\n return result\n"
]
| [
[
"numpy.repeat",
"numpy.array_equal"
]
]
|
akmeraki/deep-learning- | [
"ba4302a8d65ac8b63627bcfa8e3b23871fa2c390"
]
| [
"yadlt/core/model.py"
]
| [
"\"\"\"Model scheleton.\"\"\"\n\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport tensorflow as tf\n\nfrom .config import Config\n\n\nclass Model(object):\n \"\"\"Class representing an abstract Model.\"\"\"\n\n def __init__(self, name):\n \"\"\"Constructor.\n\n :param name: name of the model, used as filename.\n string, default 'dae'\n \"\"\"\n self.name = name\n self.model_path = os.path.join(Config().models_dir, self.name)\n\n self.input_data = None\n self.input_labels = None\n self.keep_prob = None\n self.layer_nodes = [] # list of layers of the final network\n self.train_step = None\n self.cost = None\n\n # tensorflow objects\n self.tf_graph = tf.Graph()\n self.tf_session = None\n self.tf_saver = None\n self.tf_merged_summaries = None\n self.tf_summary_writer = None\n\n def pretrain_procedure(self, layer_objs, layer_graphs, set_params_func,\n train_set, validation_set=None):\n \"\"\"Perform unsupervised pretraining of the model.\n\n :param layer_objs: list of model objects (autoencoders or rbms)\n :param layer_graphs: list of model tf.Graph objects\n :param set_params_func: function used to set the parameters after\n pretraining\n :param train_set: training set\n :param validation_set: validation set\n :return: return data encoded by the last layer\n \"\"\"\n next_train = train_set\n next_valid = validation_set\n\n for l, layer_obj in enumerate(layer_objs):\n print('Training layer {}...'.format(l + 1))\n next_train, next_valid = self._pretrain_layer_and_gen_feed(\n layer_obj, set_params_func, next_train, next_valid,\n layer_graphs[l])\n\n return next_train, next_valid\n\n def _pretrain_layer_and_gen_feed(self, layer_obj, set_params_func,\n train_set, validation_set, graph):\n \"\"\"Pretrain a single autoencoder and encode the data for the next layer.\n\n :param layer_obj: layer model\n :param set_params_func: function used to set the parameters after\n pretraining\n :param train_set: training set\n :param validation_set: validation set\n :param graph: tf object for the rbm\n :return: encoded train data, encoded validation data\n \"\"\"\n layer_obj.fit(train_set, train_set,\n validation_set, validation_set, graph=graph)\n\n with graph.as_default():\n set_params_func(layer_obj, graph)\n\n next_train = layer_obj.transform(train_set, graph=graph)\n if validation_set is not None:\n next_valid = layer_obj.transform(validation_set, graph=graph)\n else:\n next_valid = None\n\n return next_train, next_valid\n\n def get_layers_output(self, dataset):\n \"\"\"Get output from each layer of the network.\n\n :param dataset: input data\n :return: list of np array, element i is the output of layer i\n \"\"\"\n layers_out = []\n\n with self.tf_graph.as_default():\n with tf.Session() as self.tf_session:\n self.tf_saver.restore(self.tf_session, self.model_path)\n for l in self.layer_nodes:\n layers_out.append(l.eval({self.input_data: dataset,\n self.keep_prob: 1}))\n\n if layers_out == []:\n raise Exception(\"This method is not implemented for this model\")\n else:\n return layers_out\n\n def get_parameters(self, params, graph=None):\n \"\"\"Get the parameters of the model.\n\n :param params: dictionary of keys (str names) and values (tensors).\n :return: evaluated tensors in params\n \"\"\"\n g = graph if graph is not None else self.tf_graph\n\n with g.as_default():\n with tf.Session() as self.tf_session:\n self.tf_saver.restore(self.tf_session, self.model_path)\n out = {}\n for par in params:\n if type(params[par]) == list:\n for i, p in enumerate(params[par]):\n out[par + '-' + str(i+1)] = p.eval()\n else:\n out[par] = params[par].eval()\n return out\n"
]
| [
[
"tensorflow.Graph",
"tensorflow.Session"
]
]
|
ultrons/apex | [
"ebcd7f084bba96bdb0c3fdf396c3c6b02e745042"
]
| [
"apex/contrib/multihead_attn/fast_self_multihead_attn_func.py"
]
| [
"import torch\nimport fast_self_multihead_attn\nimport fast_self_multihead_attn_bias\nimport fast_self_multihead_attn_bias_additive_mask\n\nclass FastSelfAttnFunc(torch.autograd.Function) :\n @staticmethod\n def forward(ctx, use_time_mask, is_training, heads, inputs, input_weights, output_weights, input_biases, output_biases, pad_mask, mask_additive, dropout_prob):\n use_biases_t = torch.tensor([input_biases is not None])\n heads_t = torch.tensor([heads])\n dropout_prob_t = torch.tensor([dropout_prob])\n null_tensor = torch.tensor([])\n use_mask = (pad_mask is not None)\n mask_additive_t= torch.tensor([mask_additive])\n\n if use_biases_t[0]:\n if not mask_additive:\n input_lin_results, \\\n softmax_results, \\\n dropout_results, \\\n dropout_mask, \\\n matmul2_results, \\\n outputs = \\\n fast_self_multihead_attn_bias.forward( \\\n use_mask, \\\n use_time_mask, \\\n is_training, \\\n heads, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n input_biases, \\\n output_biases, \\\n pad_mask if use_mask else null_tensor, \\\n dropout_prob)\n ctx.save_for_backward(use_biases_t, \\\n heads_t, \\\n matmul2_results, \\\n dropout_results, \\\n softmax_results, \\\n null_tensor, \\\n null_tensor, \\\n mask_additive_t, \\\n input_lin_results, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n dropout_mask, \\\n dropout_prob_t)\n\n else:\n input_lin_results, \\\n bmm1_results, \\\n dropout_results, \\\n dropout_mask, \\\n matmul2_results, \\\n outputs = \\\n fast_self_multihead_attn_bias_additive_mask.forward( \\\n use_mask, \\\n use_time_mask, \\\n is_training, \\\n heads, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n input_biases, \\\n output_biases, \\\n pad_mask if use_mask else null_tensor, \\\n dropout_prob)\n ctx.save_for_backward(use_biases_t, \\\n heads_t, \\\n matmul2_results, \\\n dropout_results, \\\n null_tensor, \\\n bmm1_results, \\\n pad_mask, \\\n mask_additive_t, \\\n input_lin_results, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n dropout_mask, \\\n dropout_prob_t)\n\n\n else:\n input_lin_results, \\\n softmax_results, \\\n dropout_results, \\\n dropout_mask, \\\n matmul2_results, \\\n outputs = \\\n fast_self_multihead_attn.forward( \\\n use_mask, \\\n use_time_mask, \\\n is_training, \\\n heads, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n pad_mask if use_mask else null_tensor, \\\n dropout_prob)\n ctx.save_for_backward(use_biases_t, \\\n heads_t, \\\n matmul2_results, \\\n dropout_results, \\\n softmax_results, \\\n null_tensor, \\\n null_tensor, \\\n mask_additive_t, \\\n input_lin_results, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n dropout_mask, \\\n dropout_prob_t)\n return outputs.detach()\n\n @staticmethod\n def backward(ctx, output_grads):\n use_biases_t, \\\n heads_t, \\\n matmul2_results, \\\n dropout_results, \\\n softmax_results, \\\n bmm1_results, \\\n pad_mask, \\\n mask_additive_t, \\\n input_lin_results, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n dropout_mask, \\\n dropout_prob_t = ctx.saved_tensors\n\n if use_biases_t[0]:\n if not mask_additive_t[0]:\n input_grads, \\\n input_weight_grads, \\\n output_weight_grads, \\\n input_bias_grads, \\\n output_bias_grads = \\\n fast_self_multihead_attn_bias.backward( \\\n heads_t[0], \\\n output_grads, \\\n matmul2_results, \\\n dropout_results, \\\n softmax_results, \\\n input_lin_results, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n dropout_mask, \\\n dropout_prob_t[0])\n\n else:\n input_grads, \\\n input_weight_grads, \\\n output_weight_grads, \\\n input_bias_grads, \\\n output_bias_grads = \\\n fast_self_multihead_attn_bias_additive_mask.backward( \\\n heads_t[0], \\\n output_grads, \\\n matmul2_results, \\\n dropout_results, \\\n bmm1_results, \\\n pad_mask, \\\n input_lin_results, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n dropout_mask, \\\n dropout_prob_t[0])\n \n else:\n input_bias_grads = None \n output_bias_grads = None\n input_grads, \\\n input_weight_grads, \\\n output_weight_grads = \\\n fast_self_multihead_attn.backward( \\\n heads_t[0], \\\n output_grads, \\\n matmul2_results, \\\n dropout_results, \\\n softmax_results, \\\n input_lin_results, \\\n inputs, \\\n input_weights, \\\n output_weights, \\\n dropout_mask, \\\n dropout_prob_t[0])\n return None, None, None, input_grads, input_weight_grads, output_weight_grads,input_bias_grads, output_bias_grads, None, None, None\n\nfast_self_attn_func = FastSelfAttnFunc.apply\n"
]
| [
[
"torch.tensor"
]
]
|
danifranco/UNetPlusPlus | [
"869063cd53ad7f7e81dc268605671b39365f7f76"
]
| [
"pytorch/nnunet/training/network_training/nnUNet_variants/profiling/nnUNetTrainerV2_2epochs.py"
]
| [
"# Copyright 2020 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany\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.\nfrom typing import Tuple\nimport numpy as np\nimport torch\n\nfrom nnunet.training.loss_functions.crossentropy import RobustCrossEntropyLoss\nfrom nnunet.training.network_training.nnUNetTrainerV2 import nnUNetTrainerV2\nfrom nnunet.training.network_training.nnUNetTrainerV2_DDP import nnUNetTrainerV2_DDP\nfrom nnunet.training.network_training.nnUNet_variants.architectural_variants.nnUNetTrainerV2_noDeepSupervision import \\\n nnUNetTrainerV2_noDeepSupervision\nfrom nnunet.utilities.to_torch import maybe_to_torch, to_cuda\nfrom torch.cuda.amp import autocast\n\n\nclass nnUNetTrainerV2_2epochs(nnUNetTrainerV2):\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, fp16=False):\n super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, fp16)\n self.max_num_epochs = 2\n\n def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5,\n save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True,\n validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False,\n segmentation_export_kwargs=None):\n pass\n\n def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True,\n mirror_axes: Tuple[int] = None,\n use_sliding_window: bool = True, step_size: float = 0.5,\n use_gaussian: bool = True, pad_border_mode: str = 'constant',\n pad_kwargs: dict = None, all_in_gpu: bool = True,\n verbose: bool = True, mixed_precision=True) -> Tuple[np.ndarray, np.ndarray]:\n pass\n\n def save_checkpoint(self, fname, save_optimizer=True):\n pass\n\n\nclass nnUNetTrainerV2_5epochs(nnUNetTrainerV2):\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, fp16=False):\n super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, fp16)\n self.max_num_epochs = 5\n\n def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5,\n save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True,\n validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False,\n segmentation_export_kwargs=None):\n pass\n\n def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True,\n mirror_axes: Tuple[int] = None,\n use_sliding_window: bool = True, step_size: float = 0.5,\n use_gaussian: bool = True, pad_border_mode: str = 'constant',\n pad_kwargs: dict = None, all_in_gpu: bool = True,\n verbose: bool = True, mixed_precision=True) -> Tuple[np.ndarray, np.ndarray]:\n pass\n\n def save_checkpoint(self, fname, save_optimizer=True):\n pass\n\n\nclass nnUNetTrainerV2_5epochs_CEnoDS(nnUNetTrainerV2_noDeepSupervision):\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, fp16=False):\n super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, fp16)\n self.max_num_epochs = 5\n self.loss = RobustCrossEntropyLoss()\n\n def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5,\n save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True,\n validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False,\n segmentation_export_kwargs=None):\n pass\n\n def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True,\n mirror_axes: Tuple[int] = None,\n use_sliding_window: bool = True, step_size: float = 0.5,\n use_gaussian: bool = True, pad_border_mode: str = 'constant',\n pad_kwargs: dict = None, all_in_gpu: bool = True,\n verbose: bool = True, mixed_precision=True) -> Tuple[np.ndarray, np.ndarray]:\n pass\n\n def save_checkpoint(self, fname, save_optimizer=True):\n pass\n\n def run_iteration(self, data_generator, do_backprop=True, run_online_evaluation=False):\n data_dict = next(data_generator)\n data = data_dict['data']\n target = data_dict['target']\n\n data = maybe_to_torch(data)\n target = maybe_to_torch(target).long()[:, 0]\n\n if torch.cuda.is_available():\n data = to_cuda(data)\n target = to_cuda(target)\n\n self.optimizer.zero_grad()\n\n if self.fp16:\n with autocast():\n output = self.network(data)\n del data\n l = self.loss(output, target)\n\n if do_backprop:\n self.amp_grad_scaler.scale(l).backward()\n self.amp_grad_scaler.unscale_(self.optimizer)\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.amp_grad_scaler.step(self.optimizer)\n self.amp_grad_scaler.update()\n else:\n output = self.network(data)\n del data\n l = self.loss(output, target)\n\n if do_backprop:\n l.backward()\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.optimizer.step()\n\n if run_online_evaluation:\n self.run_online_evaluation(output, target)\n\n del target\n\n return l.detach().cpu().numpy()\n\n def run_online_evaluation(self, output, target):\n pass\n\n def finish_online_evaluation(self):\n pass\n\n\nclass nnUNetTrainerV2_5epochs_noDS(nnUNetTrainerV2_noDeepSupervision):\n def __init__(self, plans_file, fold, output_folder=None, dataset_directory=None, batch_dice=True, stage=None,\n unpack_data=True, deterministic=True, fp16=False):\n super().__init__(plans_file, fold, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, fp16)\n self.max_num_epochs = 5\n\n def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5,\n save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True,\n validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False,\n segmentation_export_kwargs=None):\n pass\n\n def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True,\n mirror_axes: Tuple[int] = None,\n use_sliding_window: bool = True, step_size: float = 0.5,\n use_gaussian: bool = True, pad_border_mode: str = 'constant',\n pad_kwargs: dict = None, all_in_gpu: bool = True,\n verbose: bool = True, mixed_precision=True) -> Tuple[np.ndarray, np.ndarray]:\n pass\n\n def save_checkpoint(self, fname, save_optimizer=True):\n pass\n\n def run_iteration(self, data_generator, do_backprop=True, run_online_evaluation=False):\n data_dict = next(data_generator)\n data = data_dict['data']\n target = data_dict['target']\n\n data = maybe_to_torch(data)\n target = maybe_to_torch(target)\n\n if torch.cuda.is_available():\n data = to_cuda(data)\n target = to_cuda(target)\n\n self.optimizer.zero_grad()\n\n if self.fp16:\n with autocast():\n output = self.network(data)\n del data\n l = self.loss(output, target)\n\n if do_backprop:\n self.amp_grad_scaler.scale(l).backward()\n self.amp_grad_scaler.unscale_(self.optimizer)\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.amp_grad_scaler.step(self.optimizer)\n self.amp_grad_scaler.update()\n else:\n output = self.network(data)\n del data\n l = self.loss(output, target)\n\n if do_backprop:\n l.backward()\n torch.nn.utils.clip_grad_norm_(self.network.parameters(), 12)\n self.optimizer.step()\n\n if run_online_evaluation:\n self.run_online_evaluation(output, target)\n\n del target\n\n return l.detach().cpu().numpy()\n\n def run_online_evaluation(self, output, target):\n pass\n\n def finish_online_evaluation(self):\n pass\n\n\n\nclass nnUNetTrainerV2_DDP_5epochs(nnUNetTrainerV2_DDP):\n def __init__(self, plans_file, fold, local_rank, output_folder=None, dataset_directory=None, batch_dice=True,\n stage=None,\n unpack_data=True, deterministic=True, distribute_batch_size=False, fp16=False):\n super().__init__(plans_file, fold, local_rank, output_folder, dataset_directory, batch_dice, stage, unpack_data,\n deterministic, distribute_batch_size, fp16)\n self.max_num_epochs = 5\n\n def validate(self, do_mirroring: bool = True, use_sliding_window: bool = True, step_size: float = 0.5,\n save_softmax: bool = True, use_gaussian: bool = True, overwrite: bool = True,\n validation_folder_name: str = 'validation_raw', debug: bool = False, all_in_gpu: bool = False,\n segmentation_export_kwargs=None):\n pass\n\n def predict_preprocessed_data_return_seg_and_softmax(self, data: np.ndarray, do_mirroring: bool = True,\n mirror_axes: Tuple[int] = None,\n use_sliding_window: bool = True, step_size: float = 0.5,\n use_gaussian: bool = True, pad_border_mode: str = 'constant',\n pad_kwargs: dict = None, all_in_gpu: bool = True,\n verbose: bool = True, mixed_precision=True) -> Tuple[np.ndarray, np.ndarray]:\n pass\n\n def save_checkpoint(self, fname, save_optimizer=True):\n pass"
]
| [
[
"torch.cuda.is_available",
"torch.cuda.amp.autocast"
]
]
|
fabianzoepf/cross_section | [
"69a26d4f73873a95504120666ecc594ef86595c0"
]
| [
"analyze_scale.py"
]
| [
"\"\"\"Analyze fish scales: extract their cross section and count the rings.\"\"\"\nimport argparse\nimport os\nimport glob\nimport imghdr\n\nimport pandas as pd\nimport cv2\nfrom tqdm import tqdm\n\nimport cross_section\nimport count_rings\n\n\ndef export(scale_data: pd.DataFrame, out_file: str) -> None:\n \"\"\"\n Export date to file. File type can either be json or feather: this\n depends on the extenstion of the out_file argument.\n\n Args:\n scale_data (pd.DataFrame): data to be written to file\n\n out_file (str): path to the output file. Only json or feather extension allowed\n \"\"\"\n _, ext = os.path.splitext(out_file)\n\n if ext == '.json':\n with open(out_file, 'w') as f:\n scale_data.to_json(f, orient='records')\n elif ext == '.feather':\n scale_data.to_feather(out_file)\n else:\n raise ValueError('Output file type not available. Use json or feather.')\n\n\ndef convert_to_mm(data: float, dpi: int, power: int=1) -> pd.DataFrame:\n \"\"\"\n Convert pixel data to mm.\n\n Args:\n data (float): data in pixel\n\n dpi (int): dots per inch\n\n power (int): power to be used to convert higher dimensions\n\n Returns:\n data (float): data in mm\n \"\"\"\n inches = data / (dpi**power)\n mm = (25.4**power) * inches\n\n return mm\n\n\ndef get_files(path: str) -> list:\n \"\"\"\n Get all files image files within in the path.\n\n Args:\n path (str): path to image or folder\n\n Returns:\n files (list): paths to all image files in folder and subfolders\n \"\"\"\n if os.path.isfile(path):\n files = [path]\n elif os.path.isdir(path):\n files = glob.glob(os.path.join(path, '*'))\n else:\n files = []\n\n # filter out non-images\n image_files = [x for x in files if imghdr.what(x) is not None]\n\n return image_files\n\n\ndef main(path: str, min_box_size: int, out_file: str, dpi: int=0) -> None:\n \"\"\"\n Analyze fish scales: extract their cross section and count the rings as well as the pixel\n distance between detected rings.\n Data can be exported to either json or feather files for further use.\n\n Args:\n path (str): path to input images. Can be a single image or a folder, in the latter case all\n images contained in the folder and subfolders will be analyzed.\n\n min_box_size (int): minimum bounding box size of a scale in the image in pixel.\n Used to filter out noise.\n\n out_file (str): path to the output file. Only json or feather extension allowed.\n\n dpi (int): dots per inch, if specified, all output data will be in mm, otherwise in pixel\n \"\"\"\n files = get_files(path)\n\n scale_data = []\n\n for image_path in tqdm(files):\n #TODO: logging if something fails\n image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)\n\n cross_sections = cross_section.main(image, min_box_size)\n\n for cs, cnt in cross_sections:\n num_rings, diff = count_rings.main(cs)\n area = cv2.contourArea(cnt)\n perimeter = cv2.arcLength(cnt,True)\n\n if 0 < dpi:\n diff = convert_to_mm(diff, dpi)\n area = convert_to_mm(area, dpi, power=2)\n perimeter = convert_to_mm(perimeter, dpi)\n\n scale_data.append([image_path, cs, num_rings, diff, area, perimeter])\n\n scale_data = pd.DataFrame(scale_data,\n columns=['image', 'gray values', '# rings',\n 'ring distance', 'area', 'perimeter'])\n\n export(scale_data, out_file)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('path', help='path to image or folder to be analyzed')\n parser.add_argument('--min_box_size', help='minimal bounding box height/width',\n type=int, default=200, required=False)\n parser.add_argument('--out_file',\n help='output path, determines the type also. Use .json or .feather extension',\n default=os.path.join(os.getcwd(),'scale_data.feather'), required=False)\n parser.add_argument('--dpi',\n help='dots per inch. If specified, all output data will be in mm, otherwise in pixel',\n type=int, default=0, required=False)\n args = parser.parse_args()\n\n main(args.path, args.min_box_size, args.out_file, args.dpi)\n"
]
| [
[
"pandas.DataFrame"
]
]
|
ndey96/lucent | [
"d868d8ca52520bd245c1e5fcf3b026782f77e561"
]
| [
"lucent/optvis/transform.py"
]
| [
"# Copyright 2020 The Lucent 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\nfrom __future__ import absolute_import, division, print_function\n\nimport torch\nimport torch.nn.functional as F\nfrom torchvision.transforms import Normalize\nimport numpy as np\nimport kornia\nfrom kornia.geometry.transform import translate\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef jitter(d):\n assert d > 1, \"Jitter parameter d must be more than 1, currently {}\".format(d)\n def inner(image_t):\n dx = np.random.choice(d)\n dy = np.random.choice(d)\n return translate(image_t, torch.tensor([[dx, dy]]).float().to(device))\n return inner\n\n\ndef pad(w, mode=\"reflect\", constant_value=0.5):\n if mode != \"constant\":\n constant_value = 0\n def inner(image_t):\n return F.pad(\n image_t,\n [w]*4,\n mode=mode,\n value=constant_value,\n )\n return inner\n\n\ndef random_scale(scales):\n def inner(image_t):\n scale = np.random.choice(scales)\n shp = image_t.shape[2:]\n scale_shape = [_roundup(scale * d) for d in shp]\n pad_x = max(0, _roundup((shp[1] - scale_shape[1])/2))\n pad_y = max(0, _roundup((shp[0] - scale_shape[0])/2))\n upsample = torch.nn.Upsample(size=scale_shape, mode='bilinear', align_corners=True)\n return F.pad(upsample(image_t), [pad_y, pad_x]*2)\n return inner\n\n\ndef random_rotate(angles, units=\"degrees\"):\n def inner(image_t):\n b, _, h, w = image_t.shape\n # kornia takes degrees\n alpha = _rads2angle(np.random.choice(angles), units)\n angle = torch.ones(b) * alpha\n scale = torch.ones(b)\n center = torch.ones(b, 2)\n center[..., 0] = (image_t.shape[3] - 1) / 2\n center[..., 1] = (image_t.shape[2] - 1) / 2\n M = kornia.get_rotation_matrix2d(center, angle, scale).to(device)\n rotated_image = kornia.warp_affine(image_t.float(), M, dsize=(h, w))\n return rotated_image\n return inner\n\n\ndef compose(transforms):\n def inner(x):\n for transform in transforms:\n x = transform(x)\n return x\n return inner\n\n\ndef _roundup(value):\n return np.ceil(value).astype(int)\n\n\ndef _rads2angle(angle, units):\n if units.lower() == \"degrees\":\n return angle\n if units.lower() in [\"radians\", \"rads\", \"rad\"]:\n angle = angle * 180. / np.pi\n return angle\n\n\ndef normalize():\n # ImageNet normalization for torchvision models\n # see https://pytorch.org/docs/stable/torchvision/models.html\n normal = Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n def inner(image_t):\n return torch.stack([normal(t) for t in image_t])\n return inner\n\n\ndef preprocess_inceptionv1():\n # Original Tensorflow's InceptionV1 model\n # takes in [-117, 138]\n # See https://github.com/tensorflow/lucid/blob/master/lucid/modelzoo/other_models/InceptionV1.py#L56\n # Thanks to ProGamerGov for this!\n return lambda x: x * 255 - 117\n\n\nstandard_transforms = [\n pad(12, mode=\"constant\", constant_value=.5),\n jitter(8),\n random_scale([1 + (i - 5) / 50. for i in range(11)]),\n random_rotate(list(range(-10, 11)) + 5 * [0]),\n jitter(4),\n]\n"
]
| [
[
"torch.ones",
"numpy.random.choice",
"torch.tensor",
"numpy.ceil",
"torch.nn.Upsample",
"torch.cuda.is_available",
"torch.nn.functional.pad"
]
]
|
TomMonks/basecast | [
"312c2c2a80a4cd15257be4b53ced87d5d5fa5ec7"
]
| [
"tests/test_naive.py"
]
| [
"'''\nTests for Naive benchmark classes\n\nTests currently cover:\n\n1. Forecast horizons\n2. Allowable input types: np.ndarray, pd.DataFrame, pd.Series\n3. Failure paths for abnormal input such as np.nan, non numeric,\n empty arrays and np.Inf\n4. Predictions\n - naive1 - carries forward last value\n - snaive - carries forward previous h values\n - average - flat forecast of average\n - drift - previous value + gradient\n - ensemble naive - the average of all of the methods\n - Test fit_predict()\n\n5. Prediction intervals\n - horizon\n - sets i.e. 2 sets of intervals (0.8 and 0.95)\n - width\n - bootstrapped prediction intervals\n - length of horizon\n - number of sets of intervals returned.\n\n6. Fitted values\n - expected length\n - count of NaN\n'''\n\nimport pytest\nimport pandas as pd\nimport numpy as np\n\nimport forecast_tools.baseline as b\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_naive1_forecast_horizon(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Naive1()\n model.fit(pd.Series(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_naive1_fit_predict(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Naive1()\n # fit_predict for point forecasts only\n preds = model.fit_predict(pd.Series(data), horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_snaive_forecast_horizon(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.SNaive(1)\n model.fit(pd.Series(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_snaive_fit_predict(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.SNaive(1)\n # fit_predict for point forecasts only\n preds = model.fit_predict(pd.Series(data), horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_drift_forecast_horizon(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Drift()\n model.fit(np.array(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_drift_fit_predict(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Drift()\n # fit_predict for point forecasts only\n preds = model.fit_predict(pd.Series(data), horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_average_forecast_horizon(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Average()\n model.fit(pd.Series(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_average_fit_predict(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Average()\n # fit_predict for point forecasts only\n preds = model.fit_predict(pd.Series(data), horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_average_forecast_input_numpy(data, horizon, expected):\n '''\n test the average class accepts numpy array\n '''\n model = b.Average()\n model.fit(np.array(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_average_forecast_input_series(data, horizon, expected):\n '''\n test the average class accepts pandas series\n '''\n model = b.Average()\n model.fit(pd.Series(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_average_forecast_input_dataframe(data, horizon, expected):\n '''\n test the average baseline class accept dataframe\n '''\n model = b.Average()\n model.fit(pd.DataFrame(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_naive1_forecast_input_dataframe(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Naive1()\n model.fit(pd.DataFrame(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_naive1_forecast_input_series(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Naive1()\n model.fit(pd.Series(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_naive1_forecast_input_numpy(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Naive1()\n model.fit(np.array(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_snaive_forecast_input_series(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.SNaive(1)\n model.fit(pd.Series(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_snaive_forecast_input_dataframe(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.SNaive(1)\n model.fit(pd.DataFrame(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_drift_forecast_input_numpy(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Drift()\n model.fit(np.array(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_drift_forecast_input_series(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Drift()\n model.fit(pd.Series(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_drift_forecast_input_dataframe(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Drift()\n model.fit(pd.DataFrame(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_ensemble_forecast_input_dataframe(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.EnsembleNaive(2)\n model.fit(pd.DataFrame(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_ensemble_forecast_input_series(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.EnsembleNaive(2)\n model.fit(pd.Series(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, horizon, expected\",\n [([1, 2, 3, 4, 5], 12, 12),\n ([1, 2, 3, 4, 5], 24, 24),\n ([1, 2, 3], 8, 8)\n ])\ndef test_ensemble_forecast_input_numpy(data, horizon, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.EnsembleNaive(2)\n model.fit(np.array(data))\n # point forecasts only\n preds = model.predict(horizon)\n assert len(preds) == expected\n\n\[email protected](\"data, exception\",\n [(np.array([]), ValueError),\n (1.0, TypeError),\n (np.array(['foo', 'bar', 'spam', 'eggs']),\n TypeError),\n (np.array([1, 2, 3, 4, 5, 6, np.NAN]), TypeError),\n (np.array([1, 2, 3, 4, np.Inf, 5, 6]), TypeError)])\ndef test_ensemble_abnormal_input(data, exception):\n '''\n test naive1 raises correct exceptions on abnormal input\n '''\n model = b.EnsembleNaive(2)\n with pytest.raises(exception):\n model.fit(data)\n\n\[email protected](\"data, expected\",\n [([1, 2, 3, 4, 5], 3.0),\n ([139, 32, 86, 123, 61, 51, 108,\n 137, 33, 25], 79.5),\n ([1, 2, 3], 2.0)\n ])\ndef test_average_forecast_output(data, expected):\n '''\n test the correct number of error metric functions are returned.\n '''\n model = b.Average()\n model.fit(pd.DataFrame(data))\n # point forecasts only\n preds = model.predict(1)\n assert preds[0] == expected\n\n\[email protected](\"data, expected\",\n [([1, 2, 3, 4, 5], 5.0),\n ([139, 32, 86, 123, 61, 51,\n 108, 137, 33, 25], 25.0),\n ([1, 2, 3], 3.0)\n ])\ndef test_naive1_forecast_output(data, expected):\n '''\n test naive1 carries forward the last value in the series\n '''\n model = b.Naive1()\n model.fit(pd.DataFrame(data))\n # point forecasts only\n preds = model.predict(1)\n assert preds[0] == expected\n\n\[email protected](\"data, period, expected\",\n [(np.resize(np.arange(12), 24), 12, np.arange(12)),\n (np.resize(np.arange(24), 48), 24, np.arange(24)),\n (pd.Series(np.resize(np.arange(12), 24)),\n 12, pd.Series(np.arange(12)))\n ])\ndef test_snaive_forecast_output(data, period, expected):\n '''\n test naive1 carries forward the last value in the series\n '''\n model = b.SNaive(period)\n model.fit(data)\n # point forecasts only\n preds = model.predict(period)\n assert np.array_equal(preds, expected)\n\n\[email protected](\"data, period, expected\",\n [(np.resize(np.arange(12), 24), 12, np.full(12,\n np.arange(12).mean())),\n (np.resize(np.arange(24), 48), 24,\n np.full(24, np.arange(24).mean())),\n (pd.Series(np.resize(np.arange(12), 24)),\n 12, np.full(12, np.arange(12).mean()))\n ])\ndef test_average_forecast_output_longer_horizon(data, period, expected):\n '''\n test naive1 carries forward the last value in the series\n '''\n model = b.Average()\n model.fit(data)\n # point forecasts only\n preds = model.predict(period)\n assert np.array_equal(preds, expected)\n\n\[email protected](\"data, exception\",\n [(np.array([]), ValueError),\n (1.0, TypeError),\n (np.array(['foo', 'bar', 'spam', 'eggs']),\n TypeError),\n (np.array([1, 2, 3, 4, 5, 6, np.NAN]), TypeError),\n (np.array([1, 2, 3, 4, np.Inf, 5, 6]), TypeError)])\ndef test_naive1_abnormal_input(data, exception):\n '''\n test naive1 raises correct exceptions on abnormal input\n '''\n model = b.Naive1()\n with pytest.raises(exception):\n model.fit(data)\n\n\[email protected](\"data, exception\",\n [(np.array([]), ValueError),\n (1.0, TypeError),\n (np.array(['foo', 'bar', 'spam', 'eggs']),\n TypeError),\n (np.array([1, 2, 3, 4, 5, 6, np.nan]), TypeError),\n (np.array([1, 2, 3, 4, np.Inf, 5, 6]), TypeError)\n ])\ndef test_snaive_abnormal_input(data, exception):\n '''\n test snaive raises correct exceptions on abnormal input\n '''\n model = b.SNaive(1)\n with pytest.raises(exception):\n model.fit(data)\n\n\[email protected](\"data, exception\",\n [(np.array([]), ValueError),\n (1.0, TypeError),\n (np.array(['foo', 'bar', 'spam', 'eggs']),\n TypeError),\n (np.array([1, 2, 3, 4, 5, 6, np.nan]), TypeError),\n (np.array([1, 2, 3, 4, np.Inf, 5, 6]), TypeError)])\ndef test_average_abnormal_input(data, exception):\n '''\n test average raises correct exceptions on abnormal input\n '''\n model = b.Average()\n with pytest.raises(exception):\n model.fit(data)\n\n\[email protected](\"data, exception\",\n [(np.array([]), ValueError),\n (1.0, TypeError),\n (np.array(['foo', 'bar', 'spam', 'eggs']),\n TypeError),\n (np.array([1, 2, 3, 4, 5, 6, np.nan]), TypeError),\n (np.array([1, 2, 3, 4, np.Inf, 5, 6]), TypeError)])\ndef test_drift_abnormal_input(data, exception):\n '''\n test drift raises correct exceptions on abnormal input\n '''\n model = b.Drift()\n with pytest.raises(exception):\n model.fit(data)\n\n\[email protected](\"data, horizon, alpha, expected\",\n [([1, 2, 3, 4, 5], 12, [0.2, 0.05], 12),\n ([1, 2, 3, 4, 5], 24, [0.2, 0.10, 0.05], 24),\n ([1, 2, 3], 8, [0.8], 8)\n ])\ndef test_naive1_pi_horizon(data, horizon, alpha, expected):\n '''\n test the correct forecast horizon is returned for prediction interval\n for Naive1\n '''\n model = b.Naive1()\n model.fit(pd.Series(data))\n # point forecasts only\n _, intervals = model.predict(horizon, return_predict_int=True, alpha=alpha)\n assert len(intervals[0]) == expected\n\n\[email protected](\"data, horizon, alpha, expected\",\n [([1, 2, 3, 4, 5], 12, [0.2, 0.05], 12),\n ([1, 2, 3, 4, 5], 24, [0.2, 0.10, 0.05], 24),\n ([1, 2, 3], 8, [0.8], 8)\n ])\ndef test_snaive_pi_horizon(data, horizon, alpha, expected):\n '''\n test the correct forecast horizon is returned for prediction\n interval for SNaive\n '''\n model = b.SNaive(1)\n model.fit(pd.Series(data))\n # point forecasts only\n _, intervals = model.predict(horizon, return_predict_int=True, alpha=alpha)\n assert len(intervals[0]) == expected\n\n\[email protected](\"data, horizon, alpha, expected\",\n [([1, 2, 3, 4, 5], 12, [0.2, 0.05], 12),\n ([1, 2, 3, 4, 5], 24, [0.2, 0.10, 0.05], 24),\n ([1, 2, 3], 8, [0.8], 8)\n ])\ndef test_drift_pi_horizon(data, horizon, alpha, expected):\n '''\n test the correct forecast horizon is returned for prediction\n interval for Drift\n '''\n model = b.Drift()\n model.fit(pd.Series(data))\n # point forecasts only\n _, intervals = model.predict(\n horizon, return_predict_int=True, alpha=alpha)\n assert len(intervals[0]) == expected\n\n\[email protected](\"data, horizon, alpha, expected\",\n [([1, 2, 3, 4, 5], 12, [0.2, 0.05], 12),\n ([1, 2, 3, 4, 5], 24, [0.2, 0.10, 0.05], 24),\n ([1, 2, 3], 8, [0.8], 8)\n ])\ndef test_average_pi_horizon(data, horizon, alpha, expected):\n '''\n test the correct forecast horizon is returned for prediction\n interval for Average\n '''\n model = b.Average()\n model.fit(pd.Series(data))\n # point forecasts only\n _, intervals = model.predict(\n horizon, return_predict_int=True, alpha=alpha)\n assert len(intervals[0]) == expected\n\n\[email protected](\"model, data, horizon, alpha, expected\",\n [(b.Naive1(), [1, 2, 3, 4, 5], 12, [0.2, 0.05], 2),\n (b.Naive1(), [1, 2, 3, 4, 5],\n 24, [0.2, 0.10, 0.05], 3),\n (b.SNaive(1), [1, 2, 3], 8, [0.8], 1),\n (b.SNaive(1), [1, 2, 3, 4, 5],\n 24, [0.2, 0.10, 0.05], 3),\n (b.Naive1(), [1, 2, 3], 8, None, 2),\n (b.SNaive(1), [1, 2, 3], 8, None, 2),\n (b.Average(), [1, 2, 3], 8, None, 2),\n (b.Drift(), [1, 2, 3], 8, None, 2),\n (b.Drift(), [1, 2, 3], 8, [0.8], 1),\n (b.Drift(), [1, 2, 3], 8, None, 2),\n (b.Average(), [1, 2, 3, 4, 5],\n 24, [0.2, 0.10, 0.05], 3)\n ])\ndef test_naive_pi_set_number(model, data, horizon, alpha, expected):\n '''\n test the correct number of Prediction intervals are\n returned for prediction interval for all Naive forecasting classes\n '''\n model.fit(pd.Series(data))\n # point forecasts only\n _, intervals = model.predict(\n horizon, return_predict_int=True, alpha=alpha)\n assert len(intervals) == expected\n\n\[email protected](\"data, period, expected\",\n [(np.arange(1, 7), 6, np.arange(7, 13)),\n (pd.Series(np.arange(1, 7)), 6, np.arange(7, 13)),\n (pd.DataFrame(np.arange(1, 7)), 6, np.arange(7, 13)),\n (pd.DataFrame(np.arange(1.0, 7.0,\n dtype=np.float64)), 6,\n np.arange(7.0, 13.0, dtype=np.float64))\n ])\ndef test_drift_forecast_output_longer_horizon(data, period, expected):\n '''\n test drift forecast predictions\n '''\n model = b.Drift()\n model.fit(data)\n # point forecasts only\n preds = model.predict(period)\n assert np.array_equal(preds, expected)\n\n\ndef test_naive1_prediction_interval_low():\n '''\n test naive 80% lower prediction interval\n '''\n\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n low = [29.56885, 24.005, 19.73657, 16.13770, 12.96704]\n # high = [56.43115, 61.99451, 66.26343, 69.86230, 73.03296]\n\n model = b.Naive1()\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.2])\n print(intervals[0].T[0])\n assert pytest.approx(intervals[0].T[0], rel=1e-6, abs=0.1) == low\n\n\ndef test_naive1_prediction_interval_high():\n '''\n test naive 80% upper prediction interval\n '''\n\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [29.56885, 24.005, 19.73657, 16.13770, 12.96704]\n high = [56.43115, 61.99451, 66.26343, 69.86230, 73.03296]\n\n model = b.Naive1()\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.2])\n\n print(intervals[0].T[1])\n assert pytest.approx(intervals[0].T[1], rel=1e-6, abs=0.1) == high\n\n\ndef test_naive1_se():\n '''\n standard error of naive1 is root mean squared.\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [29.56885, 24.005, 19.73657, 16.13770, 12.96704]\n # high = [56.43115, 61.99451, 66.26343, 69.86230, 73.03296]\n\n model = b.Naive1()\n model.fit(train)\n\n expected = 10.48038\n\n assert pytest.approx(model._resid_std) == expected\n\n\ndef test_average_prediction_interval_high():\n '''\n test average 80% upper prediction interval\n '''\n\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [40.97369, 40.97369, 40.97369, 40.97369, 40.97369]\n high = [59.34631, 59.34631, 59.34631, 59.34631, 59.34631]\n\n model = b.Average()\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.2])\n\n print(intervals[0].T[1])\n # assert np.array_equal(intervals[0].T[1], high)\n assert pytest.approx(intervals[0].T[1]) == high\n\n\ndef test_average_prediction_interval_low():\n '''\n test average 80% lower prediction interval\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n low = [40.97369, 40.97369, 40.97369, 40.97369, 40.97369]\n # high = [59.34631, 59.34631, 59.34631, 59.34631, 59.34631]\n\n model = b.Average()\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.2])\n\n print(intervals[0].T[1])\n\n assert pytest.approx(intervals[0].T[0]) == low\n\n\ndef test_naive1_prediction_interval_95_high():\n '''\n test naive1 95% upper prediction interval\n '''\n\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [22.458831, 13.950400, 7.421651, 1.917662, -2.931450]\n high = [63.54117, 72.04960, 78.57835, 84.08234, 88.93145]\n\n model = b.Naive1()\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.05])\n\n print(intervals[0].T[1])\n assert pytest.approx(intervals[0].T[1], rel=1e-6, abs=0.1) == high\n\n\ndef test_naive1_prediction_interval_95_low():\n '''\n test naive1 95% lower prediction interval\n '''\n\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n low = [22.458831, 13.950400, 7.421651, 1.917662, -2.931450]\n # high = [63.54117, 72.04960, 78.57835, 84.08234, 88.93145]\n\n model = b.Naive1()\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.05])\n\n print(intervals[0].T[0])\n assert pytest.approx(intervals[0].T[0], rel=1e-6, abs=0.1) == low\n\n\ndef test_snaive_prediction_interval_80_low():\n '''\n test snaive 80% lower prediction interval\n intervals are matched from R forecast package\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n low = [32.00420, 57.00420, 49.00420, 30.00420, 26.62116]\n # high = [57.99580, 82.99580, 74.99580, 55.99580, 63.37884]\n\n # quarterly data\n model = b.SNaive(period=4)\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.2])\n\n print(intervals[0].T[0])\n assert pytest.approx(intervals[0].T[0]) == low\n\n\ndef test_snaive_prediction_interval_80_high():\n '''\n test snaive 80% upper prediction interval\n intervals are matched from R forecast package\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [32.00420, 57.00420, 49.00420, 30.00420, 26.62116]\n high = [57.99580, 82.99580, 74.99580, 55.99580, 63.37884]\n\n # quarterly data\n model = b.SNaive(period=4)\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.2])\n\n print(intervals[0].T[1])\n assert pytest.approx(intervals[0].T[1]) == high\n\n\ndef test_snaive_prediction_interval_95_high():\n '''\n test snaive 95% upper prediction interval\n intervals are matched from R forecast package\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [25.12464, 50.12464, 42.12464, 23.12464, 16.89199]\n high = [64.87536, 89.87536, 81.87536, 62.87536, 73.10801]\n\n # quarterly data\n model = b.SNaive(period=4)\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.05])\n\n print(intervals[0].T[1])\n assert pytest.approx(intervals[0].T[1]) == high\n\n\ndef test_snaive_prediction_interval_95_low():\n '''\n test snaive 95% lower prediction interval\n intervals are matched from R forecast package\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n low = [25.12464, 50.12464, 42.12464, 23.12464, 16.89199]\n # high = [64.87536, 89.87536, 81.87536, 62.87536, 73.10801]\n\n # quarterly data\n model = b.SNaive(period=4)\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.05])\n\n print(intervals[0].T[0])\n assert pytest.approx(intervals[0].T[0]) == low\n\n\ndef test_drift_prediction_interval_95_low():\n '''\n test drift 95% lower prediction interval\n intervals are matched from R forecast package\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n low = [22.2100359, 13.2828923, 6.2277574, 0.1124247, -5.4196405]\n # high = [63.70916, 72.55549, 79.52982, 85.56434, 91.01560]\n\n # quarterly data\n model = b.Drift()\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.05])\n\n print(intervals[0].T[0])\n # not ideal due to not adjusting for drift i think,\n assert pytest.approx(intervals[0].T[0], rel=1e-6, abs=1.2) == low\n\n\ndef test_drift_prediction_interval_95_high():\n '''\n test drift 95% lower prediction interval\n intervals are matched from R forecast package\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [22.2100359, 13.2828923, 6.2277574, 0.1124247, -5.4196405]\n high = [63.70916, 72.55549, 79.52982, 85.56434, 91.01560]\n\n # quarterly data\n model = b.Drift()\n model.fit(train)\n _, intervals = model.predict(5, return_predict_int=True, alpha=[0.05])\n\n print(intervals[0].T[1])\n # not ideal due to not adjusting for drift i think,\n assert pytest.approx(intervals[0].T[1], rel=1e-6, abs=1.2) == high\n\n\ndef test_bootstrap_prediction_interval_length():\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [22.2100359, 13.2828923, 6.2277574, 0.1124247, -5.4196405]\n # high = [63.70916, 72.55549, 79.52982, 85.56434, 91.01560]\n\n # quarterly data\n model = b.Naive1()\n model.fit(train)\n preds = model.predict(horizon=5)\n\n expected = 5\n\n y_intervals = b.boot_prediction_intervals(preds, model.resid,\n horizon=expected,\n levels=[0.8], boots=10)\n\n assert expected == len(y_intervals[0])\n\n\[email protected](\"intervals, expected\",\n [([0.8, 0.90, 0.95], 3),\n ([0.8, 0.90], 2),\n ([0.8], 1),\n ([0.7, 0.8, 0.9, 0.95], 4)\n ])\ndef test_bootstrap_prediction_interval_sets_returned(intervals, expected):\n '''\n Test the number of bootstrap prediction intervals returned\n\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=100)\n # low = [22.2100359, 13.2828923, 6.2277574, 0.1124247, -5.4196405]\n # high = [63.70916, 72.55549, 79.52982, 85.56434, 91.01560]\n\n # quarterly data\n model = b.Naive1()\n model.fit(train)\n preds = model.predict(horizon=5)\n horizon = 5\n y_intervals = b.boot_prediction_intervals(preds, model.resid,\n horizon=horizon,\n levels=intervals, boots=10)\n\n assert expected == len(y_intervals)\n\n\[email protected](\"training_length\",\n [(100),\n (999),\n (1000),\n (10),\n (20000)\n ])\ndef test_drift_fitted_values_length(training_length):\n '''\n test drift .fittedvalues\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=training_length)\n\n model = b.Drift()\n model.fit(train)\n\n expected = training_length\n\n assert len(model.fittedvalues) == expected\n\n\[email protected](\"training_length\",\n [(100),\n (999),\n (1000),\n (10),\n (20000)\n ])\ndef test_naive1_fitted_values_length(training_length):\n '''\n test naive1 .fittedvalues length is as expected\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=training_length)\n\n model = b.Naive1()\n model.fit(train)\n\n expected = training_length\n\n assert len(model.fittedvalues) == expected\n\n\[email protected](\"training_length\",\n [(100),\n (999),\n (1000),\n (10),\n (20000)\n ])\ndef test_snaive_fitted_values_length(training_length):\n '''\n test SNaive .fittedvalues length is as expected\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=training_length)\n\n model = b.SNaive(7)\n model.fit(train)\n\n expected = training_length\n\n assert len(model.fittedvalues) == expected\n\n\[email protected](\"training_length\",\n [(100),\n (999),\n (1000),\n (10),\n (20000)\n ])\ndef test_average_fitted_values_length(training_length):\n '''\n test Average forecaster .fittedvalues length is as expected\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=training_length)\n\n model = b.Average()\n model.fit(train)\n\n expected = training_length\n\n assert len(model.fittedvalues) == expected\n\n\[email protected](\"period\",\n [(7),\n (14),\n (24),\n (1),\n (12),\n (4)\n ])\ndef test_snaive_fitted_values_nan_length(period):\n '''\n test SNaive .fittedvalues has the correct number of NaNs\n i.e. = to the seasonal period.\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=200)\n\n model = b.SNaive(period)\n model.fit(train)\n\n expected = period\n n_nan = np.isnan(model.fittedvalues).sum()\n\n assert n_nan == expected\n\n\ndef test_naive1_fitted_values_nan_length():\n '''\n test Naive1 .fittedvalues has the correct number of NaNs\n i.e. = 1\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=200)\n\n model = b.Naive1()\n model.fit(train)\n\n expected = 1\n n_nan = np.isnan(model.fittedvalues).sum()\n\n assert n_nan == expected\n\n\ndef test_drift_fitted_values_nan_length():\n '''\n test Drift .fittedvalues has the correct number of NaNs\n i.e. = 1\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=200)\n\n model = b.Drift()\n model.fit(train)\n\n expected = 1\n n_nan = np.isnan(model.fittedvalues).sum()\n\n assert n_nan == expected\n\n\ndef test_average_fitted_values_nan_length():\n '''\n test Average forecast .fittedvalues has the correct number of NaNs\n i.e. = 1\n '''\n np.random.seed(1066)\n train = np.random.poisson(lam=50, size=200)\n\n model = b.Average()\n model.fit(train)\n\n expected = 0\n n_nan = np.isnan(model.fittedvalues).sum()\n\n assert n_nan == expected\n\n\ndef test_snaive_call_predict_before_fit():\n '''\n test SNaive raises correct exceptions when\n predict is called before fit\n '''\n model = b.SNaive(7)\n with pytest.raises(UnboundLocalError):\n model.predict(10)\n\n\ndef test_drift_call_predict_before_fit():\n '''\n test Drift raises correct exceptions when\n predict is called before fit\n '''\n model = b.Drift()\n with pytest.raises(UnboundLocalError):\n model.predict(10)\n"
]
| [
[
"pandas.Series",
"numpy.random.seed",
"numpy.array_equal",
"numpy.isnan",
"numpy.arange",
"pandas.DataFrame",
"numpy.random.poisson",
"numpy.array"
]
]
|
kafkasl/hpc.fassr | [
"9608dc1a9ca01951230dc006777be7cc379769b5"
]
| [
"src/plots/boxplot_3.py"
]
| [
"from glob import glob\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom matplotlib.patches import Polygon\nimport matplotlib\n\nfrom utils import load_obj\n\nshow_plot = False\ncols = [\"dataset\", \"period\", \"clf\", \"magic\", \"model_params\", \"k\", \"bot_thresh\",\n \"top_thresh\", \"mode\", \"trade_frequency\", \"start_trade\", \"final_trade\",\n \"time\", \"min\", \"max\", \"mean\", \"last\"]\n\n\ndef add_legend(fig):\n # Finally, add a basic legend\n fig.text(0.8005, 0.135, '-', color='red', backgroundcolor='silver',\n weight='roman', size='medium')\n fig.text(0.825, 0.135, ' S&P 500 Index', color='black',\n weight='roman',\n size='x-small')\n\n fig.text(0.8005, 0.17, '*', color='white', backgroundcolor='silver',\n weight='roman', size='medium')\n fig.text(0.825, 0.17, ' Average Value', color='black', weight='roman',\n size='x-small')\n\ndef plot_by_k(results):\n # plot by model\n ks = [10, 25, 50]\n data = [results[pd.to_numeric(results.k) == k]['last'].values / 1e6 for k in ks]\n\n\n k_names = [20, 50, 100]\n\n fig, ax1 = plt.subplots(figsize=(5, 9))\n fig.canvas.set_window_title('Revenues per different portfolio sizes')\n fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)\n\n bp = ax1.boxplot(data, notch=0, sym='+', vert=1, whis=1.5)\n plt.setp(bp['boxes'], color='black')\n plt.setp(bp['whiskers'], color='black')\n plt.setp(bp['fliers'], color='red', marker='+')\n plt.setp(bp['medians'], color='black')\n\n\n # Add a horizontal grid to the plot, but make it very light in color\n # so we can use it for reading data values but not be distracting\n ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',\n alpha=0.5)\n\n # Hide these grid behind plot objects\n ax1.set_axisbelow(True)\n ax1.ticklabel_format(axis='y', style='plain')\n ax1.set_title('Comparison of total revenues by portfolio sizes')\n ax1.set_xlabel('Portfolio size')\n ax1.set_ylabel('Total revenue in million U.S. dollars')\n ax1.axhline(y=276480 / 1e6, color='red', linestyle='--', alpha=0.4)\n\n # Now fill the boxes with desired colors\n boxColors = ['royalblue', 'royalblue']\n numBoxes = len(data)\n medians = list(range(numBoxes))\n for i in range(numBoxes):\n box = bp['boxes'][i]\n boxX = []\n boxY = []\n for j in range(5):\n boxX.append(box.get_xdata()[j])\n boxY.append(box.get_ydata()[j])\n k = i % 2\n boxCoords = np.column_stack([boxX, boxY])\n boxPolygon = Polygon(boxCoords, facecolor=boxColors[k])\n ax1.add_patch(boxPolygon)\n # Now draw the median lines back over what we just filled in\n med = bp['medians'][i]\n medianX = []\n medianY = []\n for j in range(2):\n medianX.append(med.get_xdata()[j])\n medianY.append(med.get_ydata()[j])\n # ax1.plot(medianX, medianY, 'k')\n medians[i] = medianY[0]\n # Finally, overplot the sample averages, with horizontal alignment\n # in the center of each box\n ax1.plot([np.average(med.get_xdata())], [np.average(data[i])],\n color='w', marker='*', markeredgecolor='k')\n\n # Set the axes ranges and axes labels\n ax1.set_xlim(0.5, numBoxes + 0.5)\n top = max([max(x) for x in data if len(x) > 0]) * 1.1\n bottom = min([min(x) for x in data if len(x) > 0]) * 5\n\n ax1.set_ylim(-1, top)\n ax1.set_xticklabels(k_names, fontsize=10)\n\n # Due to the Y-axis scale being different across samples, it can be\n # hard to compare differences in medians across the samples. Add upper\n # X-axis tick labels with the sample medians to aid in comparison\n # (just use two decimal places of precision)\n pos = np.arange(numBoxes) + 1\n upperLabels = [str(np.round(s, 2)) for s in medians]\n weights = ['bold', 'semibold']\n for tick, label in zip(range(numBoxes), ax1.get_xticklabels()):\n k = tick % 2\n ax1.text(pos[tick], top - (top * 0.05), upperLabels[tick],\n horizontalalignment='center', size='x-small',\n weight=weights[k],\n color=boxColors[k])\n\n\n add_legend(fig)\n plt.gcf().subplots_adjust(left=0.1)\n\n # plt.tight_layout()\n plt.savefig('ks', bbox_inches='tight')\n if show_plot:\n plt.show()\n\n\ndef plot_by_model(results):\n # plot by model\n models = ['SVR', 'RFR', 'MLPR', 'AdaBR']\n data = [results[results.clf == clf]['last'].values / 1e6 for clf in models]\n\n model_names = ['SVM', 'Random Forest', 'Neural Network',\n 'AdaBoost']\n\n fig, ax1 = plt.subplots(figsize=(7, 9))\n fig.canvas.set_window_title('Revenues per model')\n fig.subplots_adjust(left=0.075, right=0.95, top=0.9, bottom=0.25)\n\n bp = ax1.boxplot(data, notch=0, sym='+', vert=1, whis=1.5)\n plt.setp(bp['boxes'], color='black')\n plt.setp(bp['whiskers'], color='black')\n plt.setp(bp['fliers'], color='red', marker='+')\n plt.setp(bp['medians'], color='black')\n\n\n # Add a horizontal grid to the plot, but make it very light in color\n # so we can use it for reading data values but not be distracting\n ax1.yaxis.grid(True, linestyle='-', which='major', color='lightgrey',\n alpha=0.5)\n\n # Hide these grid behind plot objects\n ax1.set_axisbelow(True)\n ax1.ticklabel_format(axis='y', style='plain')\n ax1.set_title('Comparison of total revenues for different models')\n ax1.set_xlabel('Models')\n ax1.set_ylabel('Total revenue in million U.S. dollars')\n ax1.axhline(y=276480 / 1e6, color='red', linestyle='--', alpha=0.4)\n\n # Now fill the boxes with desired colors\n boxColors = ['royalblue', 'royalblue']\n numBoxes = len(data)\n medians = list(range(numBoxes))\n for i in range(numBoxes):\n box = bp['boxes'][i]\n boxX = []\n boxY = []\n for j in range(5):\n boxX.append(box.get_xdata()[j])\n boxY.append(box.get_ydata()[j])\n k = i % 2\n boxCoords = np.column_stack([boxX, boxY])\n boxPolygon = Polygon(boxCoords, facecolor=boxColors[k])\n ax1.add_patch(boxPolygon)\n # Now draw the median lines back over what we just filled in\n med = bp['medians'][i]\n medianX = []\n medianY = []\n for j in range(2):\n medianX.append(med.get_xdata()[j])\n medianY.append(med.get_ydata()[j])\n # ax1.plot(medianX, medianY, 'k')\n medians[i] = medianY[0]\n # Finally, overplot the sample averages, with horizontal alignment\n # in the center of each box\n ax1.plot([np.average(med.get_xdata())], [np.average(data[i])],\n color='w', marker='*', markeredgecolor='k')\n\n # Set the axes ranges and axes labels\n ax1.set_xlim(0.5, numBoxes + 0.5)\n top = max([max(x) for x in data if len(x) > 0]) * 1.1\n bottom = min([min(x) for x in data if len(x) > 0]) * 5\n\n ax1.set_ylim(-1, top)\n ax1.set_xticklabels(model_names, fontsize=10)\n\n # Due to the Y-axis scale being different across samples, it can be\n # hard to compare differences in medians across the samples. Add upper\n # X-axis tick labels with the sample medians to aid in comparison\n # (just use two decimal places of precision)\n pos = np.arange(numBoxes) + 1\n upperLabels = [str(np.round(s, 2)) for s in medians]\n weights = ['bold', 'semibold']\n for tick, label in zip(range(numBoxes), ax1.get_xticklabels()):\n k = tick % 2\n ax1.text(pos[tick], top - (top * 0.05), upperLabels[tick],\n horizontalalignment='center', size='x-small',\n weight=weights[k],\n color=boxColors[k])\n\n\n add_legend(fig)\n plt.gcf().subplots_adjust(left=0.1)\n\n # plt.tight_layout()\n plt.savefig('models', bbox_inches='tight')\n if show_plot:\n plt.show()\n\ndef to_df_col(pfs, name):\n index = [p._day_str for p in pfs]\n data = [(p.total_money - p.fees) / 1e6 for p in pfs]\n return pd.DataFrame(data=data, index=index, columns=[name])\n\n\ndef get_trends_df(results):\n best = results.groupby('clf')[['last']].max()\n worst = results.groupby('clf')[['last']].min()\n\n sp500 = pd.read_csv('../sp500.csv').set_index('Date')\n sp500.index = pd.to_datetime(sp500.index)\n sp500 = sp500[['Adj Close']].rename(columns={'Adj Close': 'S&P 500'})\n ratio = 100000 / sp500.iloc[0]\n\n b_found = []\n w_found = []\n b_trends = []\n w_trends = []\n import ipdb\n for file in glob('./*/clean_results_*'):\n print(\"Processing: %s\" % file)\n result = load_obj(file[:-4])\n # prices =\n for i, (clf, price) in enumerate(best.itertuples()):\n print(\" * searching for best: %s\" % clf)\n trend = [r for r in result if\n '%.1f' % r[1][-1].total_money == str(price)]\n if len(trend) > 0 and clf not in b_found:\n ipdb.set_trace()\n print('found! %s' % list(trend[0]))\n b_found.append(clf)\n b_trends.append(to_df_col(trend[0][1], clf))\n for i, (clf, price) in enumerate(worst.itertuples()):\n print(\" * searching for worst: %s\" % clf)\n trend = [r for r in result if\n '%.1f' % r[1][-1].total_money == str(price)]\n if len(trend) > 0 and clf not in w_found:\n ipdb.set_trace()\n print('found! %s' % list(trend[0]))\n w_found.append(clf)\n w_trends.append(to_df_col(trend[0][1], clf))\n\n sptrend = (sp500 * ratio) / 1e6\n sptrend = sptrend.resample('1W').last()\n b_t = sptrend[sptrend.index.isin(b_trends[0].index)]\n b_trends.append(b_t)\n w_t = sptrend[sptrend.index.isin(w_trends[0].index)]\n w_trends.append(w_t)\n best_df = pd.concat(b_trends, axis=1).interpolate()\n worst_df = pd.concat(w_trends, axis=1).interpolate()\n\n best_df = best_df.reindex(sorted(best_df.columns), axis=1)\n worst_df = worst_df.reindex(sorted(worst_df.columns), axis=1)\n\n best_df.index = pd.to_datetime(best_df.index)\n worst_df.index = pd.to_datetime(worst_df.index)\n\n return best_df, worst_df\n\n\ndef plot_historicals(best, worst):\n names = ['SVM', 'RF', 'NN', 'AdaBoost', 'S&P 500']\n regs = ['SVR', 'RFR', 'MLPR', 'AdaBR', 'S&P 500']\n\n # plot\n fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(15, 5))\n\n best.rename(columns={regs[i]: names[i] for i in range(len(regs))}).plot(ax=axes[0])\n worst.rename(columns={regs[i]: names[i] for i in range(len(regs))}).plot(ax=axes[1])\n\n [ax1.set_ylabel('Total revenue in million U.S. dollars') for ax1 in axes]\n axes[0].set_xlabel('Best')\n axes[1].set_xlabel('Worst')\n # [ax1.set_ylim(0, 2) for ax1 in axes]\n plt.tight_layout()\n plt.savefig('historicals')\n\n\nif __name__ == '__main__':\n print(\"Loading ../../results/res3.csv\")\n\n results = pd.read_csv('../../results/res3.csv', names=cols).sort_values(\n 'last').drop(\n 'time', 1).drop_duplicates()\n\n # r = r[(r.clf == 'AdaBC') | (r.clf == 'MLPC') | (r.clf == 'RFC') | (r.clf == 'SVC') | (r.clf == 'graham')]\n\n # results = r[(r.trade_frequency == 52) | (r.trade_frequency == 26)]\n\n plot_by_model(results)\n\n plot_by_k(results)\n\n best_df, worst_df = get_trends_df(results)\n plot_historicals(best_df, worst_df)\n # plot_by_frequency(results)\n # plot_by_training(results)\n # plot_by_threshold(results)\n # plot_by_mode(results)\n"
]
| [
[
"pandas.concat",
"pandas.to_datetime",
"matplotlib.pyplot.tight_layout",
"pandas.read_csv",
"pandas.to_numeric",
"numpy.arange",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"pandas.DataFrame",
"numpy.round",
"matplotlib.pyplot.gcf",
"numpy.average",
"matplotlib.pyplot.setp",
"numpy.column_stack",
"matplotlib.pyplot.show",
"matplotlib.patches.Polygon"
]
]
|
iesus/thesis-production-models | [
"38bf703db513ffeed5a533590fbae747235a60ba"
]
| [
"rnn/prodSRNN_UID.py"
]
| [
"import theano,numpy,os\nfrom theano import tensor as T\nfrom collections import OrderedDict\n\nimport rnn.prodSRNN_notBPTT_mon\n\n'''\n RecurentNeuralNetwork to model UID, receives a probability distribution of possible word productions and a DSS, and outputs a new probability distribution per time step that hopefully follows UID\n Essentially, it reranks the distribution that is given as input.\n'''\n\nclass model(object): \n def __init__(self,productionModelPath, vocabSize,hiddenDimensProd,hiddenDimensRerank,dssDimens):\n \n self.loadProductionModel(productionModelPath, dssDimens, hiddenDimensProd, vocabSize)\n \n #PARAMETERS OUTPUT COMBINATION LAYER\n self.probSlope=-1\n self.probIntercept=3.5\n self.derLenSlope=1\n self.derLenIntercept=-2.5\n \n \n def sample_weights(sizeX, sizeY):\n values = numpy.ndarray([sizeX, sizeY], dtype=theano.config.floatX) # @UndefinedVariable\n for dx in xrange(sizeX):\n vals=numpy.random.normal(loc=0.0, scale=0.1,size=(sizeY,))\n values[dx,:] = vals\n return values\n\n # parameters of the model\n self.W_wh = theano.shared(sample_weights(vocabSize,hiddenDimensRerank))\n self.W_dssh = theano.shared(sample_weights(dssDimens,hiddenDimensRerank))\n self.W_hh = theano.shared(sample_weights(hiddenDimensRerank,hiddenDimensRerank))\n self.W_hy = theano.shared(sample_weights(hiddenDimensRerank,vocabSize))\n \n self.bh = theano.shared(numpy.zeros(hiddenDimensRerank, dtype=theano.config.floatX)) # @UndefinedVariable\n self.b = theano.shared(numpy.zeros(vocabSize, dtype=theano.config.floatX)) # @UndefinedVariable\n \n self.h0R = numpy.zeros(hiddenDimensRerank, dtype=theano.config.floatX) # @UndefinedVariable\n self.o0 = numpy.zeros(vocabSize, dtype=theano.config.floatX) # @UndefinedVariable\n \n # bundle\n self.params = [self.W_wh,self.W_dssh, self.W_hh, self.W_hy, self.bh, self.b]\n self.names = ['W_wh','W_dssh','W_hh', 'W_hy', 'bh', 'b']\n softIn = T.vector(\"softIn\") # \n softOut = T.vector(\"y\") #words in localist representation\n h_tm1 = T.vector(\"h_tm1\")\n dss = T.vector(\"dss\")\n\n h_t = T.nnet.sigmoid(T.dot(softIn, self.W_wh) + T.dot(h_tm1, self.W_hh) + T.dot(dss,self.W_dssh)+ self.bh)\n predOutDistro = T.nnet.softmax(T.dot(h_t, self.W_hy) + self.b)\n\n # cost and gradients and learning rate\n lr = T.scalar('lr')\n loss = -T.mean(softOut * T.log(predOutDistro) + (1.- softOut) * T.log(1. - predOutDistro)) #Cross entropy \n #loss=T.nnet.categorical_crossentropy(predOutDistro,softOut)\n \n gradients = T.grad(loss, self.params )\n updates = OrderedDict(( p, p-lr*g ) for p, g in zip( self.params , gradients))\n \n # theano functions\n self.classify = theano.function(inputs=[dss,softIn,h_tm1], outputs=[h_t,predOutDistro[0]]) #predOutDistro at this time is the future o_tm1\n\n self.train = theano.function( inputs = [dss,softIn, softOut, lr,h_tm1],\n outputs = [loss,h_t,predOutDistro[0]],\n updates = updates )\n \n \n def loadProductionModel(self,productionModelPath,dssDimens,hiddenDimens,outputDimens):\n simpleProdModel= rnn.prodSRNN_notBPTT_mon.model(\n inputDimens=dssDimens,\n hiddenDimens = hiddenDimens,\n outputDimens= outputDimens\n ) \n simpleProdModel.load(productionModelPath)\n self.simpleProdModel=simpleProdModel\n \n \n def save(self, folder): \n for param, name in zip(self.params, self.names):\n numpy.save(os.path.join(folder, name + '.npy'), param.get_value())\n \n def load(self, folder):\n for param, name in zip(self.params, self.names):\n values =numpy.load(os.path.join(folder, name + '.npy'))\n param.set_value(values)\n \n \n def epochTrain(self,trainSet,learningRate):\n errors=[]\n for sentIndex in xrange(len(trainSet)):\n item=trainSet[sentIndex]\n expectedLengthVectors=numpy.asarray(item.lengthVectors)\n\n h_tm1LM=self.simpleProdModel.h0\n o_tm1=self.o0\n h_tm1RR=self.h0R\n errSent=0\n \n for i in xrange(len(item.wordsLocalist)):\n [_,h_tm1LM,o_tm1]=self.simpleProdModel.classify(item.input,h_tm1LM,o_tm1)\n [e,h_tm1RR,_]=self.train(item.input,o_tm1,expectedLengthVectors[i],learningRate,h_tm1RR)\n o_tm1=item.wordsLocalist[i]\n \n errSent+=e\n \n if sentIndex%25==0:\n errors.append(errSent) \n return errors\n \n def getModelPredictions(self,testSet,periods,combine=False):\n predictions_test=[] \n \n for sentIndex in xrange(len(testSet)):\n sentence=testSet[sentIndex] \n predSent=[]\n \n h_tm1=self.simpleProdModel.h0\n o_tm1=self.o0\n h_tm1R=self.h0R\n indexW=0\n \n if periods:\n while indexW<42 and len(predSent)<20:\n [_,h_tm1,o_tm1]=self.simpleProdModel.classify(sentence.input,h_tm1,o_tm1)\n [h_tm1R,predOutDistro]=self.classify(sentence.input,o_tm1,h_tm1R)\n \n if combine:score=self.combineScores(predOutDistro, o_tm1, sentence)\n else: score=predOutDistro\n\n indexW=numpy.argmax(score)\n o_tm1=self.o0.copy()\n o_tm1[indexW]=1.0\n \n predSent.append(indexW)\n else: \n for _ in xrange(len(sentence.wordsLocalist)):\n [_,h_tm1,o_tm1]=self.simpleProdModel.classify(sentence.input,h_tm1,o_tm1)\n [h_tm1R,predOutDistro]=self.classify(sentence.input,o_tm1,h_tm1R)\n\n if combine:score=self.combineScores(predOutDistro, o_tm1, sentence)\n else: score=predOutDistro\n\n indexW = numpy.argmax(score)\n o_tm1=self.o0.copy()\n o_tm1[indexW]=1.0\n \n predSent.append(indexW)\n \n predictions_test.append(predSent)\n return predictions_test\n \n def combineScores(self,lengthScores,probScores,trainingIt):\n p_dss=len(trainingIt.equivalents)*1.0/130\n \n probMultiplier=self.probSlope*p_dss+self.probIntercept\n derLenMultiplier=-self.derLenSlope*p_dss+self.derLenIntercept\n \n combination=derLenMultiplier*lengthScores+probScores*probMultiplier\n return combination\n \n \n \n \n \n\n"
]
| [
[
"numpy.asarray",
"numpy.ndarray",
"numpy.random.normal",
"numpy.argmax",
"numpy.zeros"
]
]
|
cqh6666/transfer_learning_code | [
"93225814b8225d9cd8e4addffba6a7d52203443b"
]
| [
"deep transfer learning/DAN/DAN.py"
]
| [
"from __future__ import print_function\nimport argparse\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.autograd import Variable\nimport os\nimport math\nimport data_loader\nimport ResNet as models\nfrom torch.utils import model_zoo\nos.environ[\"CUDA_VISIBLE_DEVICES\"] = \"0\"\n\n# Training settings\nbatch_size = 32\niteration=10000\nlr = 0.01\nmomentum = 0.9\nno_cuda =False\nseed = 8\nlog_interval = 10\nl2_decay = 5e-4\nroot_path = \"/data/zhuyc/OFFICE31/\"\nsrc_name = \"amazon\"\ntgt_name = \"dslr\"\n\ncuda = not no_cuda and torch.cuda.is_available()\n\ntorch.manual_seed(seed)\nif cuda:\n torch.cuda.manual_seed(seed)\n\nkwargs = {'num_workers': 1, 'pin_memory': True} if cuda else {}\n\nsrc_loader = data_loader.load_training(root_path, src_name, batch_size, kwargs)\ntgt_train_loader = data_loader.load_training(root_path, tgt_name, batch_size, kwargs)\ntgt_test_loader = data_loader.load_testing(root_path, tgt_name, batch_size, kwargs)\n\nsrc_dataset_len = len(src_loader.dataset)\ntgt_dataset_len = len(tgt_test_loader.dataset)\nsrc_loader_len = len(src_loader)\ntgt_loader_len = len(tgt_train_loader)\n\n\ndef train(model):\n src_iter = iter(src_loader)\n tgt_iter = iter(tgt_train_loader)\n correct = 0\n for i in range(1, iteration+1):\n model.train()\n LEARNING_RATE = lr / math.pow((1 + 10 * (i - 1) / (iteration)), 0.75)\n if (i-1)%100==0:\n print('learning rate{: .4f}'.format(LEARNING_RATE) )\n optimizer = torch.optim.SGD([\n {'params': model.sharedNet.parameters()},\n {'params': model.cls_fc.parameters(), 'lr': LEARNING_RATE},\n ], lr=LEARNING_RATE / 10, momentum=momentum, weight_decay=l2_decay)\n try:\n src_data, src_label = src_iter.next()\n tgt_data, _ = tgt_iter.next()\n except Exception as err:\n src_iter=iter(src_loader)\n src_data, src_label = src_iter.next()\n tgt_iter=iter(tgt_train_loader)\n tgt_data, _ = tgt_iter.next()\n \n if i % tgt_loader_len == 0:\n tgt_iter = iter(tgt_train_loader)\n if cuda:\n src_data, src_label = src_data.cuda(), src_label.cuda()\n tgt_data = tgt_data.cuda()\n\n optimizer.zero_grad()\n src_pred, mmd_loss = model(src_data, tgt_data)\n cls_loss = F.nll_loss(F.log_softmax(src_pred, dim=1), src_label)\n lambd = 2 / (1 + math.exp(-10 * (i) / iteration)) - 1\n loss = cls_loss + lambd * mmd_loss\n loss.backward()\n optimizer.step()\n if i % log_interval == 0:\n print('Train iter: {} [({:.0f}%)]\\tLoss: {:.6f}\\tsoft_Loss: {:.6f}\\tmmd_Loss: {:.6f}'.format(\n i, 100. * i / iteration, loss.item(), cls_loss.item(), mmd_loss.item()))\n\n if i%(log_interval*20)==0:\n t_correct = test(model)\n if t_correct > correct:\n correct = t_correct\n print('src: {} to tgt: {} max correct: {} max accuracy{: .2f}%\\n'.format(\n src_name, tgt_name, correct, 100. * correct / tgt_dataset_len ))\n \ndef test(model):\n model.eval()\n test_loss = 0\n correct = 0\n\n with torch.no_grad():\n for tgt_test_data, tgt_test_label in tgt_test_loader:\n if cuda:\n tgt_test_data, tgt_test_label = tgt_test_data.cuda(), tgt_test_label.cuda()\n tgt_test_data, tgt_test_label = Variable(tgt_test_data), Variable(tgt_test_label)\n tgt_pred, mmd_loss = model(tgt_test_data, tgt_test_data)\n test_loss += F.nll_loss(F.log_softmax(tgt_pred, dim = 1), tgt_test_label, reduction='sum').item() # sum up batch loss\n pred = tgt_pred.data.max(1)[1] # get the index of the max log-probability\n correct += pred.eq(tgt_test_label.data.view_as(pred)).cpu().sum()\n\n test_loss /= tgt_dataset_len\n print('\\n{} set: Average loss: {:.4f}, Accuracy: {}/{} ({:.2f}%)\\n'.format(\n tgt_name, test_loss, correct, tgt_dataset_len,\n 100. * correct / tgt_dataset_len))\n return 100. * correct / tgt_dataset_len\n\n\nif __name__ == '__main__':\n \n model = models.DANNet(num_classes=31)\n print(model)\n if cuda:\n model.cuda()\n train(model)\n \n"
]
| [
[
"torch.nn.functional.log_softmax",
"torch.cuda.manual_seed",
"torch.manual_seed",
"torch.no_grad",
"torch.cuda.is_available",
"torch.autograd.Variable"
]
]
|
kais-siala/rmnd-lca | [
"db00e65e520b59e7e85268cbefb5fef593139715"
]
| [
"premise/electricity.py"
]
| [
"import os\nfrom . import DATA_DIR\nfrom .activity_maps import InventorySet\nfrom .geomap import Geomap\nfrom wurst import searching as ws\nimport csv\nimport numpy as np\nimport uuid\nimport wurst\nfrom .utils import get_lower_heating_values\nfrom datetime import date\n\nPRODUCTION_PER_TECH = (\n DATA_DIR / \"electricity\" / \"electricity_production_volumes_per_tech.csv\"\n)\nLOSS_PER_COUNTRY = DATA_DIR / \"electricity\" / \"losses_per_country.csv\"\nLHV_FUELS = DATA_DIR / \"fuels_lower_heating_value.txt\"\n\n\nclass Electricity:\n \"\"\"\n Class that modifies electricity markets in ecoinvent based on IAM output data.\n\n :ivar scenario: name of an IAM pathway\n :vartype pathway: str\n\n \"\"\"\n\n def __init__(self, db, iam_data, model, pathway, year):\n self.db = db\n self.iam_data = iam_data\n self.model = model\n self.geo = Geomap(model=model)\n self.production_per_tech = self.get_production_per_tech_dict()\n self.losses = self.get_losses_per_country_dict()\n self.scenario = pathway\n self.year = year\n self.fuels_lhv = get_lower_heating_values()\n mapping = InventorySet(self.db)\n self.emissions_map = mapping.get_remind_to_ecoinvent_emissions()\n self.powerplant_map = mapping.generate_powerplant_map()\n self.powerplant_fuels_map = mapping.generate_powerplant_fuels_map()\n\n def get_suppliers_of_a_region(self, ecoinvent_regions, ecoinvent_technologies):\n \"\"\"\n Return a list of electricity-producing datasets, for which the location and name correspond to the region and name given,\n respectively.\n\n :param ecoinvent_regions: an ecoinvent region\n :type ecoinvent_regions: list\n :param ecoinvent_technologies: name of ecoinvent dataset\n :type ecoinvent_technologies: str\n :return: list of wurst datasets\n :rtype: list\n \"\"\"\n\n return ws.get_many(\n self.db,\n *[\n ws.either(\n *[\n ws.equals(\"name\", supplier)\n for supplier in ecoinvent_technologies\n ]\n ),\n ws.either(*[ws.equals(\"location\", loc) for loc in ecoinvent_regions]),\n ws.equals(\"unit\", \"kilowatt hour\"),\n ]\n )\n\n @staticmethod\n def get_losses_per_country_dict():\n \"\"\"\n Create a dictionary with ISO country codes as keys and loss ratios as values.\n :return: ISO country code to loss ratio dictionary\n :rtype: dict\n \"\"\"\n\n if not LOSS_PER_COUNTRY.is_file():\n raise FileNotFoundError(\n \"The production per country dictionary file could not be found.\"\n )\n\n with open(LOSS_PER_COUNTRY) as f:\n csv_list = [[val.strip() for val in r.split(\";\")] for r in f.readlines()]\n\n (_, *header), *data = csv_list\n csv_dict = {}\n for row in data:\n key, *values = row\n csv_dict[key] = {key: float(value) for key, value in zip(header, values)}\n\n return csv_dict\n\n @staticmethod\n def get_production_per_tech_dict():\n \"\"\"\n Create a dictionary with tuples (technology, country) as keys and production volumes as values.\n :return: technology to production volume dictionary\n :rtype: dict\n \"\"\"\n\n if not PRODUCTION_PER_TECH.is_file():\n raise FileNotFoundError(\n \"The production per technology dictionary file could not be found.\"\n )\n csv_dict = {}\n with open(PRODUCTION_PER_TECH) as f:\n input_dict = csv.reader(f, delimiter=\";\")\n for row in input_dict:\n csv_dict[(row[0], row[1])] = row[2]\n\n return csv_dict\n\n def get_production_weighted_share(self, supplier, suppliers):\n \"\"\"\n Return the share of production of an electricity-producing dataset in a specific location,\n relative to the summed production of similar technologies in locations contained in the same REMIND region.\n\n :param supplier: electricity-producing dataset\n :type supplier: wurst dataset\n :param suppliers: list of electricity-producing datasets\n :type suppliers: list of wurst datasets\n :return: share of production relative to the total population\n :rtype: float\n \"\"\"\n\n # Fetch the production volume of the supplier\n loc_production = float(\n self.production_per_tech.get((supplier[\"name\"], supplier[\"location\"]), 0)\n )\n\n # Fetch the total production volume of similar technologies in other locations\n # contained within the REMIND region.\n\n total_production = 0\n for loc in suppliers:\n total_production += float(\n self.production_per_tech.get((loc[\"name\"], loc[\"location\"]), 0)\n )\n\n # If a corresponding production volume is found.\n if total_production != 0:\n return loc_production / total_production\n else:\n # If not, we allocate an equal share of supply\n return 1 / len(suppliers)\n\n def get_production_weighted_losses(self, voltage, remind_region):\n \"\"\"\n Return the transformation, transmission and distribution losses at a given voltage level for a given location.\n A weighted average is made of the locations contained in the REMIND region.\n\n :param voltage: voltage level (high, medium or low)\n :type voltage: str\n :param remind_region: Remind region\n :type remind_region: str\n :return: tuple that contains transformation and distribution losses\n :rtype: tuple\n \"\"\"\n\n # Fetch locations contained in REMIND region\n locations = self.geo.iam_to_ecoinvent_location(remind_region)\n\n if voltage == \"high\":\n\n cumul_prod, transf_loss = 0, 0\n for loc in locations:\n dict_loss = self.losses.get(\n loc,\n {\"Transformation loss, high voltage\": 0, \"Production volume\": 0},\n )\n\n transf_loss += (\n dict_loss[\"Transformation loss, high voltage\"]\n * dict_loss[\"Production volume\"]\n )\n cumul_prod += dict_loss[\"Production volume\"]\n transf_loss /= cumul_prod\n return transf_loss\n\n if voltage == \"medium\":\n\n cumul_prod, transf_loss, distr_loss = 0, 0, 0\n for loc in locations:\n dict_loss = self.losses.get(\n loc,\n {\n \"Transformation loss, medium voltage\": 0,\n \"Transmission loss to medium voltage\": 0,\n \"Production volume\": 0,\n },\n )\n transf_loss += (\n dict_loss[\"Transformation loss, medium voltage\"]\n * dict_loss[\"Production volume\"]\n )\n distr_loss += (\n dict_loss[\"Transmission loss to medium voltage\"]\n * dict_loss[\"Production volume\"]\n )\n cumul_prod += dict_loss[\"Production volume\"]\n transf_loss /= cumul_prod\n distr_loss /= cumul_prod\n return transf_loss, distr_loss\n\n if voltage == \"low\":\n\n cumul_prod, transf_loss, distr_loss = 0, 0, 0\n\n for loc in locations:\n dict_loss = self.losses.get(\n loc,\n {\n \"Transformation loss, low voltage\": 0,\n \"Transmission loss to low voltage\": 0,\n \"Production volume\": 0,\n },\n )\n transf_loss += (\n dict_loss[\"Transformation loss, low voltage\"]\n * dict_loss[\"Production volume\"]\n )\n distr_loss += (\n dict_loss[\"Transmission loss to low voltage\"]\n * dict_loss[\"Production volume\"]\n )\n cumul_prod += dict_loss[\"Production volume\"]\n transf_loss /= cumul_prod\n distr_loss /= cumul_prod\n return transf_loss, distr_loss\n\n def create_new_markets_low_voltage(self):\n \"\"\"\n Create low voltage market groups for electricity, by receiving medium voltage market groups as inputs\n and adding transformation and distribution losses.\n Contribution from solar power is added here as well.\n Does not return anything. Modifies the database in place.\n \"\"\"\n\n # Loop through REMIND regions\n for region in self.iam_data.electricity_markets.coords[\"region\"].values:\n\n for period in range(0, 60, 10):\n\n mix = dict(\n zip(\n self.iam_data.electricity_markets.variables.values,\n self.iam_data.electricity_markets.sel(\n region=region,\n ).interp(year=np.arange(self.year, self.year + period + 1),\n kwargs={\"fill_value\": \"extrapolate\"}).mean(dim=\"year\").values))\n\n\n created_markets = []\n # Create an empty dataset\n\n if period == 0:\n new_dataset = {\n \"location\": region,\n \"name\": \"market group for electricity, low voltage\",\n \"reference product\": \"electricity, low voltage\",\n \"unit\": \"kilowatt hour\",\n \"database\": self.db[1][\"database\"],\n \"code\": str(uuid.uuid4().hex),\n \"comment\": \"Dataset produced from REMIND pathway output results\",\n }\n # First, add the reference product exchange\n new_exchanges = [\n {\n \"uncertainty type\": 0,\n \"loc\": 1,\n \"amount\": 1,\n \"type\": \"production\",\n \"production volume\": 0,\n \"product\": \"electricity, low voltage\",\n \"name\": \"market group for electricity, low voltage\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n ]\n\n else:\n\n new_dataset = {\n \"location\": region,\n \"name\": \"market group for electricity, low voltage, \" + str(period) + \"-year forecast\",\n \"reference product\": \"electricity, low voltage\",\n \"unit\": \"kilowatt hour\",\n \"database\": self.db[1][\"database\"],\n \"code\": str(uuid.uuid4().hex),\n \"comment\": \"Dataset produced from REMIND pathway output results. Average electricity\"\n \" mix forecast over a \" + str(period) + \"-year period (\"\n + str(self.year) + \"-\"\n + str(self.year + period) + \").\",\n }\n # First, add the reference product exchange\n new_exchanges = [\n {\n \"uncertainty type\": 0,\n \"loc\": 1,\n \"amount\": 1,\n \"type\": \"production\",\n \"production volume\": 0,\n \"product\": \"electricity, low voltage\",\n \"name\": \"market group for electricity, low voltage, \" + str(period) + \"-year forecast\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n ]\n\n # Second, add an input to of sulfur hexafluoride emission to compensate the transformer's leakage\n # And an emission of a corresponding amount\n # Third, transmission line\n new_exchanges.extend([\n {\n \"uncertainty type\": 0,\n \"loc\": 2.99e-9,\n \"amount\": 2.99e-9,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"sulfur hexafluoride, liquid\",\n \"name\": \"market for sulfur hexafluoride, liquid\",\n \"unit\": \"kilogram\",\n \"location\": \"RoW\",\n },\n {\n \"uncertainty type\": 0,\n \"loc\": 2.99e-9,\n \"amount\": 2.99e-9,\n \"type\": \"biosphere\",\n \"input\": (\"biosphere3\", \"35d1dff5-b535-4628-9826-4a8fce08a1f2\"),\n \"name\": \"Sulfur hexafluoride\",\n \"unit\": \"kilogram\",\n \"categories\": (\"air\", \"non-urban air or from high stacks\"),\n },\n {\n \"uncertainty type\": 0,\n \"loc\": 8.74e-8,\n \"amount\": 8.74e-8,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"distribution network, electricity, low voltage\",\n \"name\": \"distribution network construction, electricity, low voltage\",\n \"unit\": \"kilometer\",\n \"location\": \"RoW\",\n },\n ])\n\n # Fourth, add the contribution of solar power\n\n gen_tech = list(\n (\n tech\n for tech in self.iam_data.electricity_markets.coords[\"variables\"].values\n if \"solar\" in tech.lower()\n )\n )\n solar_amount = 0\n\n for technology in gen_tech:\n # If the solar power technology contributes to the mix\n if mix[technology] > 0:\n # Fetch ecoinvent regions contained in the REMIND region\n ecoinvent_regions = self.geo.iam_to_ecoinvent_location(region)\n\n # Contribution in supply\n amount = mix[technology]\n solar_amount += amount\n\n # Get the possible names of ecoinvent datasets\n ecoinvent_technologies = self.powerplant_map[\n self.iam_data.rev_electricity_market_labels[technology]\n ]\n\n # Fetch electricity-producing technologies contained in the REMIND region\n suppliers = list(\n self.get_suppliers_of_a_region(\n ecoinvent_regions, ecoinvent_technologies\n )\n )\n\n suppliers = self.check_for_production_volume(suppliers)\n\n # If no technology is available for the REMIND region\n if len(suppliers) == 0:\n # We fetch European technologies instead\n suppliers = list(\n self.get_suppliers_of_a_region(\n [\"RER\"], ecoinvent_technologies\n )\n )\n\n suppliers = self.check_for_production_volume(suppliers)\n\n # If, after looking for European technologies, no technology is available\n if len(suppliers) == 0:\n # We fetch RoW technologies instead\n suppliers = list(\n self.get_suppliers_of_a_region(\n [\"RoW\"], ecoinvent_technologies\n )\n )\n\n suppliers = self.check_for_production_volume(suppliers)\n\n for supplier in suppliers:\n share = self.get_production_weighted_share(supplier, suppliers)\n\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": (amount * share),\n \"amount\": (amount * share),\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": supplier[\"reference product\"],\n \"name\": supplier[\"name\"],\n \"unit\": supplier[\"unit\"],\n \"location\": supplier[\"location\"],\n }\n )\n\n if period == 0:\n created_markets.append(\n [\n \"low voltage, \" + self.scenario + \", \" + str(self.year),\n \"n/a\",\n region,\n 0,\n 0,\n supplier[\"name\"],\n supplier[\"location\"],\n share,\n (share * amount),\n ]\n )\n else:\n created_markets.append(\n [\n \"low voltage, \"\n + self.scenario\n + \", \"\n + str(self.year)\n + \", \"\n + str(period)\n +\"-year forecast\",\n \"n/a\",\n region,\n 0,\n 0,\n supplier[\"name\"],\n supplier[\"location\"],\n share,\n (share * amount),\n ]\n )\n\n # Fifth, add:\n # * an input from the medium voltage market minus solar contribution, including distribution loss\n # * an self-consuming input for transformation loss\n\n transf_loss, distr_loss = self.get_production_weighted_losses(\"low\", region)\n\n if period == 0:\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 0,\n \"amount\": (1 - solar_amount) * (1 + distr_loss),\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, medium voltage\",\n \"name\": \"market group for electricity, medium voltage\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 0,\n \"amount\": transf_loss,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, low voltage\",\n \"name\": \"market group for electricity, low voltage\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n created_markets.append(\n [\n \"low voltage, \" + self.scenario + \", \" + str(self.year),\n \"n/a\",\n region,\n transf_loss,\n distr_loss,\n \"low voltage, \" + self.scenario + \", \" + str(self.year),\n region,\n 1,\n (1 - solar_amount) * (1 + distr_loss),\n ]\n )\n\n else:\n\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 0,\n \"amount\": (1 - solar_amount) * (1 + distr_loss),\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, medium voltage\",\n \"name\": \"market group for electricity, medium voltage, \" + str(period) + \"-year forecast\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 0,\n \"amount\": transf_loss,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, low voltage\",\n \"name\": \"market group for electricity, low voltage, \" + str(period) + \"-year forecast\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n created_markets.append(\n [\n \"low voltage, \"\n + self.scenario\n + \", \"\n + str(self.year)\n + \", \"\n + str(period)\n +\"-year forecast\",\n \"n/a\",\n region,\n transf_loss,\n distr_loss,\n \"low voltage, \" + self.scenario + \", \" + str(self.year),\n region,\n 1,\n (1 - solar_amount) * (1 + distr_loss),\n ]\n )\n\n\n with open(\n DATA_DIR\n / \"logs/log created electricity markets {} {}-{}.csv\".format(\n self.scenario, self.year, date.today()\n ),\n \"a\",\n ) as csv_file:\n writer = csv.writer(csv_file, delimiter=\";\", lineterminator=\"\\n\")\n for line in created_markets:\n writer.writerow(line)\n\n new_dataset[\"exchanges\"] = new_exchanges\n self.db.append(new_dataset)\n\n def create_new_markets_medium_voltage(self):\n \"\"\"\n Create medium voltage market groups for electricity, by receiving high voltage market groups as inputs\n and adding transformation and distribution losses.\n Contribution from solar power is added in low voltage market groups.\n Does not return anything. Modifies the database in place.\n \"\"\"\n # Loop through REMIND regions\n gen_region = (\n region for region in self.iam_data.electricity_markets.coords[\"region\"].values\n )\n\n created_markets = []\n\n\n\n for region in gen_region:\n\n for period in range(0, 60, 10):\n\n # Create an empty dataset\n\n if period == 0:\n # this dataset is for one year\n new_dataset = {\n \"location\": region,\n \"name\": \"market group for electricity, medium voltage\",\n \"reference product\": \"electricity, medium voltage\",\n \"unit\": \"kilowatt hour\",\n \"database\": self.db[1][\"database\"],\n \"code\": str(uuid.uuid4().hex),\n \"comment\": \"Dataset produced from REMIND pathway output results\",\n }\n\n # First, add the reference product exchange\n new_exchanges = [\n {\n \"uncertainty type\": 0,\n \"loc\": 1,\n \"amount\": 1,\n \"type\": \"production\",\n \"production volume\": 0,\n \"product\": \"electricity, medium voltage\",\n \"name\": \"market group for electricity, medium voltage\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n ]\n\n else:\n # this dataset is for a period of time\n new_dataset = {\n \"location\": region,\n \"name\": \"market group for electricity, medium voltage, \" + str(period) + \"-year forecast\",\n \"reference product\": \"electricity, medium voltage\",\n \"unit\": \"kilowatt hour\",\n \"database\": self.db[1][\"database\"],\n \"code\": str(uuid.uuid4().hex),\n \"comment\": \"Dataset produced from REMIND pathway output results. Average electricity\"\n \" mix forecast over a \" + str(period) + \"-year period (\"\n + str(self.year) + \"-\"\n + str(self.year + period) + \").\",\n }\n\n # First, add the reference product exchange\n new_exchanges = [\n {\n \"uncertainty type\": 0,\n \"loc\": 1,\n \"amount\": 1,\n \"type\": \"production\",\n \"production volume\": 0,\n \"product\": \"electricity, medium voltage\",\n \"name\": \"market group for electricity, medium voltage, \" + str(period) + \"-year forecast\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n ]\n\n\n # Second, add:\n # * an input from the high voltage market, including transmission loss\n # * an self-consuming input for transformation loss\n\n transf_loss, distr_loss = self.get_production_weighted_losses(\n \"medium\", region\n )\n\n if period == 0:\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 0,\n \"amount\": 1 + distr_loss,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, high voltage\",\n \"name\": \"market group for electricity, high voltage\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 0,\n \"amount\": transf_loss,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, medium voltage\",\n \"name\": \"market group for electricity, medium voltage\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n else:\n\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 0,\n \"amount\": 1 + distr_loss,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, high voltage\",\n \"name\": \"market group for electricity, high voltage, \" + str(period) + \"-year forecast\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 0,\n \"amount\": transf_loss,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, medium voltage\",\n \"name\": \"market group for electricity, medium voltage, \" + str(period) + \"-year forecast\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n # Third, add an input to of sulfur hexafluoride emission to compensate the transformer's leakage\n # And an emission of a corresponding amount\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 5.4e-8,\n \"amount\": 5.4e-8,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"sulfur hexafluoride, liquid\",\n \"name\": \"market for sulfur hexafluoride, liquid\",\n \"unit\": \"kilogram\",\n \"location\": \"RoW\",\n }\n )\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 5.4e-8,\n \"amount\": 5.4e-8,\n \"type\": \"biosphere\",\n \"input\": (\"biosphere3\", \"35d1dff5-b535-4628-9826-4a8fce08a1f2\"),\n \"name\": \"Sulfur hexafluoride\",\n \"unit\": \"kilogram\",\n \"categories\": (\"air\", \"non-urban air or from high stacks\"),\n }\n )\n\n # Fourth, transmission line\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 1.8628e-8,\n \"amount\": 1.8628e-8,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"transmission network, electricity, medium voltage\",\n \"name\": \"transmission network construction, electricity, medium voltage\",\n \"unit\": \"kilometer\",\n \"location\": \"RoW\",\n }\n )\n\n new_dataset[\"exchanges\"] = new_exchanges\n\n if period == 0:\n\n created_markets.append(\n [\n \"medium voltage, \" + self.scenario + \", \" + str(self.year),\n \"n/a\",\n region,\n transf_loss,\n distr_loss,\n \"medium voltage, \" + self.scenario + \", \" + str(self.year),\n region,\n 1,\n 1 + distr_loss,\n ]\n )\n\n else:\n\n created_markets.append(\n [\n \"medium voltage, \"\n + self.scenario\n + \", \"\n + str(self.year)\n + \", \"\n + str(period)\n +\"-year forecast\",\n \"n/a\",\n region,\n transf_loss,\n distr_loss,\n \"medium voltage, \" + self.scenario + \", \" + str(self.year),\n region,\n 1,\n 1 + distr_loss,\n ]\n )\n\n\n self.db.append(new_dataset)\n\n with open(\n DATA_DIR\n / \"logs/log created electricity markets {} {}-{}.csv\".format(\n self.scenario, self.year, date.today()\n ),\n \"a\",\n ) as csv_file:\n writer = csv.writer(csv_file, delimiter=\";\", lineterminator=\"\\n\")\n for line in created_markets:\n writer.writerow(line)\n\n def create_new_markets_high_voltage(self):\n \"\"\"\n Create high voltage market groups for electricity, based on electricity mixes given by REMIND.\n Contribution from solar power is added in low voltage market groups.\n Does not return anything. Modifies the database in place.\n \"\"\"\n # Loop through REMIND regions\n gen_region = (\n region for region in self.iam_data.electricity_markets.coords[\"region\"].values\n )\n\n created_markets = []\n\n for region in gen_region:\n\n for period in range(0, 60, 10):\n\n mix = dict(\n zip(\n self.iam_data.electricity_markets.variables.values,\n self.iam_data.electricity_markets.sel(\n region=region,\n ).interp(year=np.arange(self.year, self.year + period + 1),\n kwargs={\"fill_value\": \"extrapolate\"}).mean(dim=\"year\").values\n )\n )\n\n # Fetch ecoinvent regions contained in the REMIND region\n ecoinvent_regions = self.geo.iam_to_ecoinvent_location(region)\n\n # Create an empty dataset\n if period == 0:\n # this dataset is for one year\n new_dataset = {\n \"location\": region,\n \"name\": \"market group for electricity, high voltage\",\n \"reference product\": \"electricity, high voltage\",\n \"unit\": \"kilowatt hour\",\n \"database\": self.db[1][\"database\"],\n \"code\": str(uuid.uuid4().hex),\n \"comment\": \"Dataset produced from REMIND pathway output results\",\n }\n\n # First, add the reference product exchange\n new_exchanges = [\n {\n \"uncertainty type\": 0,\n \"loc\": 1,\n \"amount\": 1,\n \"type\": \"production\",\n \"production volume\": 0,\n \"product\": \"electricity, high voltage\",\n \"name\": \"market group for electricity, high voltage\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n ]\n\n else:\n # this dataset is for a period of time\n new_dataset = {\n \"location\": region,\n \"name\": \"market group for electricity, high voltage, \" + str(period) + \"-year forecast\",\n \"reference product\": \"electricity, high voltage\",\n \"unit\": \"kilowatt hour\",\n \"database\": self.db[1][\"database\"],\n \"code\": str(uuid.uuid4().hex),\n \"comment\": \"Dataset produced from REMIND pathway output results. Average electricity\"\n \" mix forecast over a \" + str(period) + \"-year period (\"\n + str(self.year) + \"-\"\n + str(self.year + period) + \".\",\n }\n\n # First, add the reference product exchange\n new_exchanges = [\n {\n \"uncertainty type\": 0,\n \"loc\": 1,\n \"amount\": 1,\n \"type\": \"production\",\n \"production volume\": 0,\n \"product\": \"electricity, high voltage\",\n \"name\": \"market group for electricity, high voltage, \" + str(period) + \"-year forecast\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n ]\n\n # Second, add transformation loss\n transf_loss = self.get_production_weighted_losses(\"high\", region)\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": 1,\n \"amount\": transf_loss,\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": \"electricity, high voltage\",\n \"name\": \"market group for electricity, high voltage\",\n \"unit\": \"kilowatt hour\",\n \"location\": region,\n }\n )\n\n # Fetch solar contribution in the mix, to subtract it\n # as solar energy is an input of low-voltage markets\n\n solar_amount = 0\n for m in mix:\n if \"solar\" in m.lower():\n solar_amount += mix[m]\n\n # Loop through the REMIND technologies\n technologies = (tech for tech in mix if \"solar\" not in tech.lower())\n for technology in technologies:\n\n # If the given technology contributes to the mix\n if mix[technology] > 0:\n\n # Contribution in supply\n amount = mix[technology]\n\n # Get the possible names of ecoinvent datasets\n ecoinvent_technologies = self.powerplant_map[\n self.iam_data.rev_electricity_market_labels[technology]\n ]\n\n # Fetch electricity-producing technologies contained in the REMIND region\n suppliers = list(\n self.get_suppliers_of_a_region(\n ecoinvent_regions, ecoinvent_technologies\n )\n )\n\n suppliers = self.check_for_production_volume(suppliers)\n\n # If no technology is available for the REMIND region\n if len(suppliers) == 0:\n # We fetch European technologies instead\n suppliers = list(\n self.get_suppliers_of_a_region(\n [\"RER\"], ecoinvent_technologies\n )\n )\n\n suppliers = self.check_for_production_volume(suppliers)\n\n # If, after looking for European technologies, no technology is available\n if len(suppliers) == 0:\n # We fetch RoW technologies instead\n suppliers = list(\n self.get_suppliers_of_a_region(\n [\"RoW\"], ecoinvent_technologies\n )\n )\n\n suppliers = self.check_for_production_volume(suppliers)\n\n if len(suppliers) == 0:\n print(\n \"no suppliers for {} in {} with ecoinvent names {}\".format(\n technology, region, ecoinvent_technologies\n )\n )\n\n for supplier in suppliers:\n share = self.get_production_weighted_share(supplier, suppliers)\n\n new_exchanges.append(\n {\n \"uncertainty type\": 0,\n \"loc\": (amount * share) / (1 - solar_amount),\n \"amount\": (amount * share) / (1 - solar_amount),\n \"type\": \"technosphere\",\n \"production volume\": 0,\n \"product\": supplier[\"reference product\"],\n \"name\": supplier[\"name\"],\n \"unit\": supplier[\"unit\"],\n \"location\": supplier[\"location\"],\n }\n )\n\n if period == 0:\n\n created_markets.append(\n [\n \"high voltage, \"\n + self.scenario\n + \", \"\n + str(self.year),\n technology,\n region,\n transf_loss,\n 0.0,\n supplier[\"name\"],\n supplier[\"location\"],\n share,\n (amount * share) / (1 - solar_amount),\n ]\n )\n else:\n created_markets.append(\n [\n \"high voltage, \"\n + self.scenario\n + \", \"\n + str(self.year)\n + \", \"\n + str(period)\n +\"-year forecast\",\n technology,\n region,\n transf_loss,\n 0.0,\n supplier[\"name\"],\n supplier[\"location\"],\n share,\n (amount * share) / (1 - solar_amount),\n ]\n )\n\n new_dataset[\"exchanges\"] = new_exchanges\n\n self.db.append(new_dataset)\n\n # Writing log of created markets\n\n with open(\n DATA_DIR\n / \"logs/log created electricity markets {} {}-{}.csv\".format(\n self.scenario, self.year, date.today()\n ),\n \"w\",\n ) as csv_file:\n writer = csv.writer(csv_file, delimiter=\";\", lineterminator=\"\\n\")\n writer.writerow(\n [\n \"dataset name\",\n \"energy type\",\n \"IAM location\",\n \"Transformation loss\",\n \"Distr./Transmission loss\",\n \"Supplier name\",\n \"Supplier location\",\n \"Contribution within energy type\",\n \"Final contribution\",\n ]\n )\n for line in created_markets:\n writer.writerow(line)\n\n def check_for_production_volume(self, suppliers):\n\n # Remove suppliers that do not have a production volume\n return [\n supplier\n for supplier in suppliers\n if self.get_production_weighted_share(supplier, suppliers) != 0\n ]\n\n def relink_activities_to_new_markets(self):\n \"\"\"\n Links electricity input exchanges to new datasets with the appropriate IAM location:\n * \"market for electricity, high voltage\" --> \"market group for electricity, high voltage\"\n * \"market for electricity, medium voltage\" --> \"market group for electricity, medium voltage\"\n * \"market for electricity, low voltage\" --> \"market group for electricity, low voltage\"\n Does not return anything.\n \"\"\"\n\n # Filter all activities that consume electricity\n\n for ds in ws.get_many(\n self.db,\n ws.exclude(ws.contains(\"name\", \"market group for electricity\")),\n ws.doesnt_contain_any(\"name\", [\"cobalt industry\", \"aluminium industry\", \"coal mining\"])\n ):\n\n for name in [\n (\"market group for electricity, high voltage\", \"electricity, high voltage\"),\n (\"market group for electricity, medium voltage\", \"electricity, medium voltage\"),\n (\"market group for electricity, low voltage\", \"electricity, low voltage\"),\n ]:\n\n excs = list(ws.get_many(\n ds[\"exchanges\"],\n *[\n ws.either(\n *[\n ws.contains(\"name\", name[1]),\n ws.equals(\"unit\", \"kilowatt hour\"),\n ]\n ),\n ws.equals(\"type\", \"technosphere\"),\n ws.doesnt_contain_any(\"name\", [\"cobalt\", \"aluminium\", \"coal mining\"])\n ]\n ))\n\n amount = 0\n for exc in excs:\n amount += exc[\"amount\"]\n ds[\"exchanges\"].remove(exc)\n\n if amount > 0:\n new_exc = {\n 'name': name[0],\n 'product': name[1],\n 'amount': amount,\n 'type': 'technosphere',\n 'unit': 'kilowatt hour',\n 'location': self.geo.ecoinvent_to_iam_location(ds[\"location\"])\n }\n\n ds[\"exchanges\"].append(new_exc)\n\n\n def find_ecoinvent_fuel_efficiency(self, ds, fuel_filters):\n \"\"\"\n This method calculates the efficiency value set initially, in case it is not specified in the parameter\n field of the dataset. In Carma datasets, fuel inputs are expressed in megajoules instead of kilograms.\n\n :param ds: a wurst dataset of an electricity-producing technology\n :param fuel_filters: wurst filter to to filter fule input exchanges\n :return: the efficiency value set by ecoinvent\n \"\"\"\n\n def calculate_input_energy(fuel_name, fuel_amount, fuel_unit):\n\n if fuel_unit == \"kilogram\" or fuel_unit == \"cubic meter\":\n\n lhv = [\n self.fuels_lhv[k] for k in self.fuels_lhv if k in fuel_name.lower()\n ][0]\n return float(lhv) * fuel_amount / 3.6\n\n if fuel_unit == \"megajoule\":\n return fuel_amount / 3.6\n\n if fuel_unit == \"kilowatt hour\":\n return fuel_amount\n\n not_allowed = [\"thermal\"]\n key = list()\n if \"parameters\" in ds:\n key = list(\n key\n for key in ds[\"parameters\"]\n if \"efficiency\" in key and not any(item in key for item in not_allowed)\n )\n if len(key) > 0:\n return ds[\"parameters\"][key[0]]\n\n else:\n energy_input = np.sum(\n np.sum(\n np.asarray(\n [\n calculate_input_energy(\n exc[\"name\"], exc[\"amount\"], exc[\"unit\"]\n )\n for exc in ds[\"exchanges\"] if exc[\"name\"] in fuel_filters\n ]\n )\n\n )\n )\n\n current_efficiency = (\n float(ws.reference_product(ds)[\"amount\"]) / energy_input\n )\n\n if \"paramters\" in ds:\n ds[\"parameters\"][\"efficiency\"] = current_efficiency\n else:\n ds[\"parameters\"] = {\"efficiency\": current_efficiency}\n\n return current_efficiency\n\n def find_fuel_efficiency_scaling_factor(self, ds, fuel_filters, technology):\n \"\"\"\n This method calculates a scaling factor to change the process efficiency set by ecoinvent\n to the efficiency given by the IAM.\n\n :param ds: wurst dataset of an electricity-producing technology\n :param fuel_filters: wurst filter to filter the fuel input exchanges\n :param technology: label of an electricity-producing technology\n :return: a rescale factor to change from ecoinvent efficiency to the efficiency given by the IAM\n :rtype: float\n \"\"\"\n\n ecoinvent_eff = self.find_ecoinvent_fuel_efficiency(ds, fuel_filters)\n\n # If the current efficiency is too high, there's an issue, and the dataset is skipped.\n if ecoinvent_eff > 1.1:\n print(\n \"The current efficiency factor for the dataset {} has not been found.\"\n \"Its current efficiency will remain\".format(\n ds[\"name\"]\n )\n )\n return 1\n\n # If the current efficiency is precisely 1, it is because it is not the actual power generation dataset\n # but an additional layer (for example, int eh case of CCS added to CHP).\n if ecoinvent_eff == 1:\n return 1\n\n remind_locations = self.geo.ecoinvent_to_iam_location(ds[\"location\"])\n remind_eff = (\n self.iam_data.electricity_efficiencies.loc[\n dict(\n variables=self.iam_data.electricity_efficiency_labels[technology],\n region=remind_locations,\n )\n ]\n .mean()\n .values\n )\n\n # Sometimes, the efficiency factor is set to 1, when not value si available\n # Therefore, we should ignore that\n if remind_eff == 1:\n return 1\n\n # Sometimes, the efficiency factor from the IAM is nto defined\n # Hence, we filter for \"nan\" and return a scaling factor of 1.\n\n if np.isnan(remind_eff):\n return 1\n\n with open(\n DATA_DIR\n / \"logs/log power plant efficiencies change {} {} {}-{}.csv\".format(\n self.model, self.scenario, self.year, date.today()\n ),\n \"a\",\n ) as csv_file:\n writer = csv.writer(csv_file, delimiter=\";\", lineterminator=\"\\n\")\n\n writer.writerow([ds[\"name\"], ds[\"location\"], ecoinvent_eff, remind_eff])\n\n return ecoinvent_eff / remind_eff\n\n @staticmethod\n def update_ecoinvent_efficiency_parameter(ds, scaling_factor):\n \"\"\"\n Update the old efficiency value in the ecoinvent dataset by the newly calculated one.\n :param ds: dataset\n :type ds: dict\n :param scaling_factor: scaling factor (new efficiency / old efficiency)\n :type scaling_factor: float\n \"\"\"\n parameters = ds[\"parameters\"]\n possibles = [\"efficiency\", \"efficiency_oil_country\", \"efficiency_electrical\"]\n\n for key in possibles:\n if key in parameters:\n ds[\"parameters\"][key] /= scaling_factor\n\n def get_remind_mapping(self):\n \"\"\"\n Define filter functions that decide which wurst datasets to modify.\n :return: dictionary that contains filters and functions\n :rtype: dict\n \"\"\"\n\n return {\n tech: {\n \"eff_func\": self.find_fuel_efficiency_scaling_factor,\n \"technology filters\": self.powerplant_map[tech],\n \"fuel filters\": self.powerplant_fuels_map[tech],\n }\n for tech in self.iam_data.electricity_efficiency_labels.keys()\n }\n\n def update_electricity_efficiency(self):\n \"\"\"\n This method modifies each ecoinvent coal, gas,\n oil and biomass dataset using data from the REMIND model.\n Return a wurst database with modified datasets.\n\n :return: a wurst database, with rescaled electricity-producing datasets.\n :rtype: list\n \"\"\"\n\n technologies_map = self.get_remind_mapping()\n\n if not os.path.exists(DATA_DIR / \"logs\"):\n os.makedirs(DATA_DIR / \"logs\")\n\n with open(\n DATA_DIR\n / \"logs/log power plant efficiencies change {} {} {}-{}.csv\".format(\n self.model, self.scenario, self.year, date.today()\n ),\n \"w\",\n ) as csv_file:\n writer = csv.writer(csv_file, delimiter=\";\", lineterminator=\"\\n\")\n writer.writerow(\n [\"dataset name\", \"location\", \"original efficiency\", \"new efficiency\"]\n )\n\n print(\n \"Log of changes in power plants efficiencies saved in {}\".format(\n DATA_DIR / \"logs\"\n )\n )\n\n for remind_technology in technologies_map:\n dict_technology = technologies_map[remind_technology]\n print(\"Rescale inventories and emissions for\", remind_technology)\n\n datasets = [d for d in self.db\n if d[\"name\"] in dict_technology[\"technology filters\"]\n and d[\"unit\"] == \"kilowatt hour\"\n ]\n\n # no activities found? Check filters!\n assert len(datasets) > 0, \"No dataset found for {}\".format(remind_technology)\n for ds in datasets:\n # Modify using remind efficiency values:\n scaling_factor = dict_technology[\"eff_func\"](\n ds, dict_technology[\"fuel filters\"], remind_technology\n )\n self.update_ecoinvent_efficiency_parameter(ds, scaling_factor)\n\n # Rescale all the technosphere exchanges according to REMIND efficiency values\n wurst.change_exchanges_by_constant_factor(\n ds,\n float(scaling_factor),\n [],\n [ws.doesnt_contain_any(\"name\", self.emissions_map)],\n )\n\n # Update biosphere exchanges according to GAINS emission values\n for exc in ws.biosphere(\n ds, ws.either(*[ws.contains(\"name\", x) for x in self.emissions_map])\n ):\n remind_emission_label = self.emissions_map[exc[\"name\"]]\n\n remind_emission = self.iam_data.electricity_emissions.loc[\n dict(\n region=self.geo.iam_to_GAINS_region(\n self.geo.ecoinvent_to_iam_location(ds[\"location\"])\n ),\n pollutant=remind_emission_label,\n sector=self.iam_data.electricity_emission_labels[\n remind_technology\n ],\n )\n ].values.item(0)\n\n if exc[\"amount\"] == 0:\n wurst.rescale_exchange(\n exc, remind_emission / 1, remove_uncertainty=True\n )\n else:\n wurst.rescale_exchange(exc, remind_emission / exc[\"amount\"])\n\n return self.db\n\n def update_electricity_markets(self):\n \"\"\"\n Delete electricity markets. Create high, medium and low voltage market groups for electricity.\n Link electricity-consuming datasets to newly created market groups for electricity.\n Return a wurst database with modified datasets.\n\n :return: a wurst database with new market groups for electricity\n :rtype: list\n \"\"\"\n # We first need to delete 'market for electricity' and 'market group for electricity' datasets\n print(\"Remove old electricity datasets\")\n list_to_remove = [\n \"market group for electricity, high voltage\",\n \"market group for electricity, medium voltage\",\n \"market group for electricity, low voltage\",\n \"market for electricity, high voltage\",\n \"market for electricity, medium voltage\",\n \"market for electricity, low voltage\",\n \"electricity, high voltage, import\",\n \"electricity, high voltage, production mix\",\n ]\n\n # Writing log of deleted markets\n # We want to preserve special markets\n # for the cobalt and aluminium industries\n markets_to_delete = [\n [i[\"name\"], i[\"location\"]]\n for i in self.db\n if any(stop in i[\"name\"] for stop in list_to_remove)\n and \"industry\" not in i[\"name\"]\n ]\n\n if not os.path.exists(DATA_DIR / \"logs\"):\n os.makedirs(DATA_DIR / \"logs\")\n\n with open(\n DATA_DIR\n / \"logs/log deleted electricity markets {} {} {}-{}.csv\".format(\n self.model, self.scenario, self.year, date.today()\n ),\n \"w\",\n ) as csv_file:\n writer = csv.writer(csv_file, delimiter=\";\", lineterminator=\"\\n\")\n writer.writerow([\"dataset name\", \"location\"])\n for line in markets_to_delete:\n writer.writerow(line)\n\n self.db = [\n i for i in self.db if not any(stop in i[\"name\"] for stop in list_to_remove)\n or any(w for w in (\"cobalt\", \"aluminium\", \"coal mining\") if w in i[\"name\"])\n ]\n\n # We then need to create high voltage REMIND electricity markets\n print(\"Create high voltage markets.\")\n self.create_new_markets_high_voltage()\n print(\"Create medium voltage markets.\")\n self.create_new_markets_medium_voltage()\n print(\"Create low voltage markets.\")\n self.create_new_markets_low_voltage()\n\n # Finally, we need to relink all electricity-consuming activities to the new electricity markets\n print(\"Link activities to new electricity markets.\")\n self.relink_activities_to_new_markets()\n\n print(\n \"Log of deleted electricity markets saved in {}\".format(DATA_DIR / \"logs\")\n )\n print(\n \"Log of created electricity markets saved in {}\".format(DATA_DIR / \"logs\")\n )\n\n return self.db\n"
]
| [
[
"numpy.isnan",
"numpy.arange"
]
]
|
viridityzhu/ROMP | [
"82d72d099e4dcea8ec50f84f634e0e91011c2d84"
]
| [
"romp/lib/utils/util.py"
]
| [
"#encoding=utf-8\nimport h5py\nimport torch\nimport numpy as np\nimport json\nimport torch.nn.functional as F\nimport cv2\nimport math\nimport hashlib\nimport shutil\nimport pickle\nimport yaml\nimport csv\nimport platform\nimport os,sys\nimport glob\nfrom io import BytesIO\nfrom scipy.spatial.transform import Rotation as R\n\nTAG_CHAR = np.array([202021.25], np.float32)\n\ndef get_kp2d_on_org_img(kp2d, offset):\n assert kp2d.shape[1]>=2, print('Espected shape of kp2d is Kx2, while get {}'.formt(kp2d.shape))\n if torch.is_tensor(offset):\n offset = offset.detach().cpu().numpy()\n pad_size_h,pad_size_w, lt_h,rb_h,lt_w,rb_w,offset_h,size_h,offset_w,size_w,length = offset\n kp2d_onorg = np.ones_like(kp2d)\n kp2d_onorg[:,0] = (kp2d[:,0]+1)/2 * pad_size_w - offset_w+lt_w\n kp2d_onorg[:,1] = (kp2d[:,1]+1)/2 * pad_size_h - offset_h+lt_w\n return kp2d_onorg\n \n\nclass AverageMeter_Dict(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.dict_store = {}\n self.count = 0\n\n def update(self, val, n=1):\n for key,value in val.items():\n if key not in self.dict_store:\n self.dict_store[key] = []\n if torch.is_tensor(value):\n value = value.item()\n self.dict_store[key].append(value)\n self.count += n\n \n def sum(self):\n dict_sum = {}\n for k, v in self.dict_store.items():\n dict_sum[k] = round(float(sum(v)),2)\n return dict_sum\n\n def avg(self):\n dict_sum = self.sum()\n dict_avg = {}\n for k,v in dict_sum.items():\n dict_avg[k] = round(v/self.count,2)\n return dict_avg\n\n\nclass AverageMeter(object):\n \"\"\"Computes and stores the average and current value\"\"\"\n\n def __init__(self):\n self.reset()\n\n def reset(self):\n self.val = 0.\n self.avg = 0.\n self.sum = 0.\n self.count = 0.\n\n def update(self, val, n=1):\n self.val = val\n self.sum += val * n\n self.count += n\n self.avg = self.sum / self.count\n\n\ndef normalize_kps(kps,image_shape,resize=512,set_minus=True):\n kps[:,0] *= 1.0 * resize / image_shape[0]\n kps[:,1] *= 1.0 * resize / image_shape[1]\n kps[:,:2] = 2.0 * kps[:,:2] / resize - 1.0\n\n if kps.shape[1]>2 and set_minus:\n kps[kps[:,2]<0.1,:2] = -2.\n kps=kps[:,:2]\n return kps\n\n#______________IO__________________\n\n\ndef collect_image_list(image_folder=None, collect_subdirs=False, img_exts=None):\n \n def collect_image_from_subfolders(image_folder, file_list, collect_subdirs, img_exts):\n for path in glob.glob(os.path.join(image_folder,'*')):\n if os.path.isdir(path) and collect_subdirs:\n collect_image_from_subfolders(path, file_list, collect_subdirs, img_exts)\n elif os.path.splitext(path)[1] in img_exts:\n file_list.append(path)\n return file_list\n\n file_list = collect_image_from_subfolders(image_folder, [], collect_subdirs, img_exts)\n\n return file_list\n\n\ndef save_result_dict_tonpz(results, test_save_dir):\n for img_path, result_dict in results.items():\n if platform.system() == 'Windows':\n path_list = img_path.split('\\\\')\n else:\n path_list = img_path.split('/')\n file_name = '_'.join(path_list)\n file_name = '_'.join(os.path.splitext(file_name)).replace('.','') + '.npz'\n save_path = os.path.join(test_save_dir, file_name)\n # get the results: np.load('/path/to/person_overlap.npz',allow_pickle=True)['results'][()]\n np.savez(save_path, results=result_dict)\n\n\ndef fig2data ( fig ):\n \"\"\"\n @brief Convert a Matplotlib figure to a 4D numpy array with RGBA channels and return it\n @param fig a matplotlib figure\n @return a numpy 3D array of RGBA values\n \"\"\"\n # draw the renderer\n fig.canvas.draw ( )\n\n # Get the RGBA buffer from the figure\n w,h = fig.canvas.get_width_height()\n buf = np.fromstring ( fig.canvas.tostring_argb(), dtype=np.uint8 )\n buf.shape = ( w, h,4 )\n\n # canvas.tostring_argb give pixmap in ARGB mode. Roll the ALPHA channel to have it in RGBA mode\n buf = np.roll ( buf, 3, axis = 2 )\n return buf\n\ndef plt2np(plt):\n #็ณ่ฏท็ผๅฒๅฐๅ\n buffer_ = BytesIO()#using buffer,great way!\n #ไฟๅญๅจๅ
ๅญไธญ๏ผ่ไธๆฏๅจๆฌๅฐ็ฃ็๏ผๆณจๆ่ฟไธช้ป่ฎค่ฎคไธบไฝ ่ฆไฟๅญ็ๅฐฑๆฏpltไธญ็ๅ
ๅฎน\n plt.savefig(buffer_,format = 'png')\n buffer_.seek(0)\n #็จPILๆCV2ไปๅ
ๅญไธญ่ฏปๅ\n dataPIL = Image.open(buffer_)\n #่ฝฌๆขไธบnparrary๏ผPIL่ฝฌๆขๅฐฑ้ๅธธๅฟซไบ,dataๅณไธบๆ้\n data = np.asarray(dataPIL)\n\n buffer_.close()\n return data\n\ndef save_pkl(info,name='../data/info.pkl'):\n check_file_and_remake(name.replace(os.path.basename(name),''))\n if name[-4:] !='.pkl':\n name += '.pkl'\n with open(name,'wb') as outfile:\n pickle.dump(info, outfile, pickle.HIGHEST_PROTOCOL)\n\ndef save_yaml(dict_file,path):\n with open(path, 'w') as file:\n documents = yaml.dump(dict_file, file)\n\ndef read_pkl(name = '../data/info.pkl'):\n with open(name,'rb') as f:\n return pickle.load(f)\n\ndef read_pkl_coding(name = '../data/info.pkl'):\n with open(name, 'rb') as f:\n u = pickle._Unpickler(f)\n u.encoding = 'latin1'\n p = u.load()\n return p\n\ndef check_file_and_remake(path,remove=False):\n if remove:\n if os.path.isdir(path):\n shutil.rmtree(path)\n if not os.path.isdir(path):\n os.makedirs(path)\n\ndef save_h5(info,name):\n check_file_and_remake(name.replace(os.path.basename(name),''))\n if name[-3:] !='.h5':\n name += '.h5'\n f=h5py.File(name,'w')\n for item, value in info.items():\n f[item] = value\n f.close()\n\ndef read_h5(name):\n if name[-3:] !='.h5':\n name += '.h5'\n f=h5py.File(name,'r')\n info = {}\n for item, value in f.items():\n info[item] = np.array(value)\n f.close()\n return info\n\ndef save_obj(verts, faces, obj_mesh_name='mesh.obj'):\n #print('Saving:',obj_mesh_name)\n with open(obj_mesh_name, 'w') as fp:\n for v in verts:\n fp.write( 'v %f %f %f\\n' % ( v[0], v[1], v[2]) )\n\n for f in faces: # Faces are 1-based, not 0-based in obj files\n fp.write( 'f %d %d %d\\n' % (f[0] + 1, f[1] + 1, f[2] + 1) )\n\ndef save_obj_color(verts, faces, c, obj_mesh_name='mesh.obj'):\n #print('Saving:',obj_mesh_name)\n with open(obj_mesh_name, 'w') as fp:\n for v in verts:\n fp.write( 'v %f %f %f %f %f %f\\n' % ( v[0], v[1], v[2], c[0], c[1], c[2]) )\n\n for f in faces: # Faces are 1-based, not 0-based in obj files\n fp.write( 'f %d %d %d\\n' % (f[0] + 1, f[1] + 1, f[2] + 1) )\n\ndef save_json(dicts, name):\n json_str = json.dumps(dicts)\n with open(name, 'w') as json_file:\n json_file.write(json_str)\n\n\n#______________model tools__________________\ndef BHWC_to_BCHW(x):\n \"\"\"\n :param x: torch tensor, B x H x W x C\n :return: torch tensor, B x C x H x W\n \"\"\"\n return x.unsqueeze(1).transpose(1, -1).squeeze(-1)\n\n#______________interesting tools__________________\n\ndef wrap(func, *args, unsqueeze=False):\n \"\"\"\n ๅฏนpytorch็ๅฝๆฐ่ฟ่กๅฐ่ฃ
๏ผไฝฟๅ
ถๅฏไปฅ่ขซnparray่ฐ็จใ\n Wrap a torch function so it can be called with NumPy arrays.\n Input and return types are seamlessly converted.\n \"\"\"\n\n # Convert input types where applicable\n args = list(args)\n for i, arg in enumerate(args):\n if type(arg) == np.ndarray:\n args[i] = torch.from_numpy(arg)\n if unsqueeze:\n args[i] = args[i].unsqueeze(0)\n\n result = func(*args)\n\n # Convert output types where applicable\n if isinstance(result, tuple):\n result = list(result)\n for i, res in enumerate(result):\n if type(res) == torch.Tensor:\n if unsqueeze:\n res = res.squeeze(0)\n result[i] = res.numpy()\n return tuple(result)\n elif type(result) == torch.Tensor:\n if unsqueeze:\n result = result.squeeze(0)\n return result.numpy()\n else:\n return result\n\n\ndef write_words2img(img,height_use,words,line_length=20,line_height=36,width_min=1420,color=(0, 0 ,0),duan_space=True):\n font = ImageFont.truetype(\"/export/home/suny/shoes_attributes/data/song.ttf\", 28)\n\n words_list = [words[i:i+line_length] for i in range(0,len(words),line_length)]\n w,h = img.size\n\n if height_use==0:\n img=np.asarray(img)\n img_new = np.zeros((h,w+width_min,3),dtype=np.uint8)\n img_new[:,:,:] = 255\n try:\n img_new[:h,:w,:] = img\n except Exception as error:\n print(error)\n return None,height_use,False\n img = Image.fromarray(np.uint8(img_new))\n w+=width_min\n\n if h<height_use+line_height*len(words_list)+1:\n img=np.asarray(img)\n img_new = np.zeros((height_use+line_height*(len(words_list)+1),w,3),dtype=np.uint8)\n img_new[:,:,:] = 255\n img_new[:h,:w,:] = img\n img = Image.fromarray(np.uint8(img_new))\n\n draw = ImageDraw.Draw(img)\n\n words = str(words)\n\n for num, line in enumerate(words_list):\n if num==0 and duan_space:\n height_use += line_height\n draw.text((w-width_min+10,height_use),line, fill = (255,0,0),font=font)\n else:\n draw.text((w-width_min+10,height_use),line, fill = color,font=font)\n height_use += line_height\n\n return img,height_use,True\n\ndef shrink(leftTop, rightBottom, width, height):\n xl = -leftTop[0]\n xr = rightBottom[0] - width\n\n yt = -leftTop[1]\n yb = rightBottom[1] - height\n\n cx = (leftTop[0] + rightBottom[0]) / 2\n cy = (leftTop[1] + rightBottom[1]) / 2\n\n r = (rightBottom[0] - leftTop[0]) / 2\n\n sx = max(xl, 0) + max(xr, 0)\n sy = max(yt, 0) + max(yb, 0)\n\n if (xl <= 0 and xr <= 0) or (yt <= 0 and yb <=0):\n return leftTop, rightBottom\n elif leftTop[0] >= 0 and leftTop[1] >= 0 : # left top corner is in box\n l = min(yb, xr)\n r = r - l / 2\n cx = cx - l / 2\n cy = cy - l / 2\n elif rightBottom[0] <= width and rightBottom[1] <= height : # right bottom corner is in box\n l = min(yt, xl)\n r = r - l / 2\n cx = cx + l / 2\n cy = cy + l / 2\n elif leftTop[0] >= 0 and rightBottom[1] <= height : #left bottom corner is in box\n l = min(xr, yt)\n r = r - l / 2\n cx = cx - l / 2\n cy = cy + l / 2\n elif rightBottom[0] <= width and leftTop[1] >= 0 : #right top corner is in box\n l = min(xl, yb)\n r = r - l / 2\n cx = cx + l / 2\n cy = cy - l / 2\n elif xl < 0 or xr < 0 or yb < 0 or yt < 0:\n return leftTop, rightBottom\n elif sx >= sy:\n sx = max(xl, 0) + max(0, xr)\n sy = max(yt, 0) + max(0, yb)\n # cy = height / 2\n if yt >= 0 and yb >= 0:\n cy = height / 2\n elif yt >= 0:\n cy = cy + sy / 2\n else:\n cy = cy - sy / 2\n r = r - sy / 2\n\n if xl >= sy / 2 and xr >= sy / 2:\n pass\n elif xl < sy / 2:\n cx = cx - (sy / 2 - xl)\n else:\n cx = cx + (sy / 2 - xr)\n elif sx < sy:\n cx = width / 2\n r = r - sx / 2\n if yt >= sx / 2 and yb >= sx / 2:\n pass\n elif yt < sx / 2:\n cy = cy - (sx / 2 - yt)\n else:\n cy = cy + (sx / 2 - yb)\n\n\n return [cx - r, cy - r], [cx + r, cy + r]\n\ndef calc_aabb_batch(ptSets_batch):\n batch_size = ptSets_batch.shape[0]\n ptLeftTop = np.array([np.min(ptSets_batch[:,:,0],axis=1),np.min(ptSets_batch[:,:,1],axis=1)]).T\n ptRightBottom = np.array([np.max(ptSets_batch[:,:,0],axis=1),np.max(ptSets_batch[:,:,1],axis=1)]).T\n bbox = np.concatenate((ptLeftTop.reshape(batch_size,1,2),ptRightBottom.reshape(batch_size,1,2)),axis=1)\n return bbox\n'''\n calculate a obb for a set of points\n inputs:\n ptSets: a set of points\n return the center and 4 corners of a obb\n'''\ndef calc_obb(ptSets):\n ca = np.cov(ptSets,y = None,rowvar = 0,bias = 1)\n v, vect = np.linalg.eig(ca)\n tvect = np.transpose(vect)\n ar = np.dot(ptSets,np.linalg.inv(tvect))\n mina = np.min(ar,axis=0)\n maxa = np.max(ar,axis=0)\n diff = (maxa - mina)*0.5\n center = mina + diff\n corners = np.array([center+[-diff[0],-diff[1]],center+[diff[0],-diff[1]],center+[diff[0],diff[1]],center+[-diff[0],diff[1]]])\n corners = np.dot(corners, tvect)\n return corners[0], corners[1], corners[2], corners[3]\n\n\n\n\n#__________________transform tools_______________________\n\n\ndef transform_rot_representation(rot, input_type='mat',out_type='vec'):\n '''\n make transformation between different representation of 3D rotation\n input_type / out_type (np.array):\n 'mat': rotation matrix (3*3)\n 'quat': quaternion (4)\n 'vec': rotation vector (3)\n 'euler': Euler degrees in x,y,z (3)\n '''\n if input_type=='mat':\n r = R.from_matrix(rot)\n elif input_type=='quat':\n r = R.from_quat(rot)\n elif input_type =='vec':\n r = R.from_rotvec(rot)\n elif input_type =='euler':\n if rot.max()<4:\n rot = rot*180/np.pi\n r = R.from_euler('xyz',rot, degrees=True)\n \n if out_type=='mat':\n out = r.as_matrix()\n elif out_type=='quat':\n out = r.as_quat()\n elif out_type =='vec':\n out = r.as_rotvec()\n elif out_type =='euler':\n out = r.as_euler('xyz', degrees=False)\n return out\n\n\ndef compute_similarity_transform(S1, S2):\n '''\n Computes a similarity transform (sR, t) that takes\n a set of 3D points S1 (3 x N) closest to a set of 3D points S2,\n where R is an 3x3 rotation matrix, t 3x1 translation, s scale.\n i.e. solves the orthogonal Procrutes problem.\n '''\n transposed = False\n if S1.shape[0] != 3 and S1.shape[0] != 2:\n S1 = S1.T\n S2 = S2.T\n transposed = True\n assert(S2.shape[1] == S1.shape[1])\n\n # 1. Remove mean.\n mu1 = S1.mean(axis=1, keepdims=True)\n mu2 = S2.mean(axis=1, keepdims=True)\n X1 = S1 - mu1\n X2 = S2 - mu2\n\n # 2. Compute variance of X1 used for scale.\n var1 = np.sum(X1**2)\n\n # 3. The outer product of X1 and X2.\n K = X1.dot(X2.T)\n\n # 4. Solution that Maximizes trace(R'K) is R=U*V', where U, V are\n # singular vectors of K.\n U, s, Vh = np.linalg.svd(K)\n V = Vh.T\n # Construct Z that fixes the orientation of R to get det(R)=1.\n Z = np.eye(U.shape[0])\n Z[-1, -1] *= np.sign(np.linalg.det(U.dot(V.T)))\n # Construct R.\n R = V.dot(Z.dot(U.T))\n\n # 5. Recover scale.\n scale = np.trace(R.dot(K)) / var1\n\n # 6. Recover translation.\n t = mu2 - scale*(R.dot(mu1))\n\n # 7. Error:\n S1_hat = scale*R.dot(S1) + t\n\n if transposed:\n S1_hat = S1_hat.T\n\n return S1_hat\n\n\ndef batch_rodrigues(param):\n #param N x 3\n batch_size = param.shape[0]\n #ๆฒฟ็ฌฌไบ็ปด๏ผ3ไธชๆฐ๏ผ่ฟ่กๆฑไบๆฌก่ๆฐ๏ผ||x||๏ผไธ้ขๅฐฑๆฏ่ฟ่กๆ ๅๅ๏ผๆฏไธไธชๆฐ้คไปฅไปไปฌ็่ๆฐใ\n l1norm = torch.norm(param + 1e-8, p = 2, dim = 1)\n angle = torch.unsqueeze(l1norm, -1)\n normalized = torch.div(param, angle)\n angle = angle * 0.5\n #ไธ้ข็ฎๅบ็ๆฏไธไธชๅ้็้ฟๅบฆ๏ผsqrt(x**2+y**2+z**2)/2,ๆไปฅ่ฟไธช้ฟๅบฆ็็cos\n v_cos = torch.cos(angle)\n v_sin = torch.sin(angle)\n #็จๅๅ
็ป่กจ็คบไธ็ปดๆ่ฝฌ๏ผๆๆถ้ด็ไธไธรรรรรรรรร\n quat = torch.cat([v_cos, v_sin * normalized], dim = 1)\n\n return quat2mat(quat)\n\ndef quat2mat(quat):\n \"\"\"Convert quaternion coefficients to rotation matrix.\n ๆๅๅ
็ป็็ณปๆฐ่ฝฌๅๆๆ่ฝฌ็ฉ้ตใๅๅ
็ป่กจ็คบไธ็ปดๆ่ฝฌ\n Args:\n quat: size = [B, 4] 4 <===>(w, x, y, z)\n Returns:\n Rotation matrix corresponding to the quaternion -- size = [B, 3, 3]\n \"\"\"\n norm_quat = quat\n norm_quat = norm_quat/norm_quat.norm(p=2, dim=1, keepdim=True)\n w, x, y, z = norm_quat[:,0], norm_quat[:,1], norm_quat[:,2], norm_quat[:,3]\n\n B = quat.size(0)\n\n w2, x2, y2, z2 = w.pow(2), x.pow(2), y.pow(2), z.pow(2)\n wx, wy, wz = w*x, w*y, w*z\n xy, xz, yz = x*y, x*z, y*z\n\n rotMat = torch.stack([w2 + x2 - y2 - z2, 2*xy - 2*wz, 2*wy + 2*xz,\n 2*wz + 2*xy, w2 - x2 + y2 - z2, 2*yz - 2*wx,\n 2*xz - 2*wy, 2*wx + 2*yz, w2 - x2 - y2 + z2], dim=1).view(B, 3, 3)\n return rotMat\n\ndef batch_global_rigid_transformation(Rs, Js, parent, rotate_base = False,root_rot_mat =None):\n '''\n ่ฟ่กๆๅ ็ๅ
จๅฑๅๆงๅๆขใ\n '''\n N = Rs.shape[0]\n #็กฎๅฎๆ น่็น็ๆ่ฝฌๅๆขใ\n if rotate_base:\n np_rot_x = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]], dtype = np.float)\n np_rot_x = np.reshape(np.tile(np_rot_x, [N, 1]), [N, 3, 3])\n rot_x = torch.from_numpy(np_rot_x).float().cuda()\n root_rotation = torch.matmul(Rs[:, 0, :, :], rot_x)\n elif root_rot_mat is not None:\n np_rot_x = np.reshape(np.tile(root_rot_mat, [N, 1]), [N, 3, 3])\n rot_x =torch.from_numpy(np_rot_x).float().cuda()\n root_rotation = torch.matmul(Rs[:, 0, :, :], rot_x)\n else:\n root_rotation = Rs[:, 0, :, :]\n Js = torch.unsqueeze(Js, -1)\n\n def make_A(R, t):\n R_homo = F.pad(R, [0, 0, 0, 1, 0, 0])\n t_homo = torch.cat([t, torch.ones(N, 1, 1).cuda()], dim = 1)\n return torch.cat([R_homo, t_homo], 2)\n\n A0 = make_A(root_rotation, Js[:, 0])\n results = [A0]\n\n for i in range(1, parent.shape[0]):\n j_here = Js[:, i] - Js[:, parent[i]]\n A_here = make_A(Rs[:, i], j_here)\n res_here = torch.matmul(results[parent[i]], A_here)\n results.append(res_here)\n\n results = torch.stack(results, dim = 1)\n\n new_J = results[:, :, :3, 3]\n #print('result',results)\n Js_w0 = torch.cat([Js, torch.zeros(N, 24, 1, 1).cuda()], dim = 2)\n #print('js w ',Js_w0)\n init_bone = torch.matmul(results, Js_w0)\n #print('init_bone before padded',init_bone)\n init_bone = F.pad(init_bone, [3, 0, 0, 0, 0, 0, 0, 0])\n #print('init_bone padded',init_bone)\n A = results - init_bone\n #print('new_J:',new_J)\n\n return new_J, A\n\ndef batch_global_rigid_transformation_cpu(Rs, Js, parent, rotate_base = False,root_rot_mat =None):\n '''\n ่ฟ่กๆๅ ็ๅ
จๅฑๅๆงๅๆขใ\n '''\n N = Rs.shape[0]\n #็กฎๅฎๆ น่็น็ๆ่ฝฌๅๆขใ\n if rotate_base:\n np_rot_x = np.array([[1, 0, 0], [0, -1, 0], [0, 0, -1]], dtype = np.float)\n np_rot_x = np.reshape(np.tile(np_rot_x, [N, 1]), [N, 3, 3])\n rot_x =torch.from_numpy(np_rot_x).float()\n root_rotation = torch.matmul(Rs[:, 0, :, :], rot_x)\n elif root_rot_mat is not None:\n np_rot_x = np.reshape(np.tile(root_rot_mat, [N, 1]), [N, 3, 3])\n rot_x =torch.from_numpy(np_rot_x).float()\n root_rotation = torch.matmul(Rs[:, 0, :, :], rot_x)\n else:\n root_rotation = Rs[:, 0, :, :]\n Js = torch.unsqueeze(Js, -1)\n\n def make_A(R, t):\n R_homo = F.pad(R, [0, 0, 0, 1, 0, 0])\n t_homo = torch.cat([t, torch.ones(N, 1, 1)], dim = 1)\n return torch.cat([R_homo, t_homo], 2)\n\n A0 = make_A(root_rotation, Js[:, 0])\n results = [A0]\n\n for i in range(1, parent.shape[0]):\n j_here = Js[:, i] - Js[:, parent[i]]\n A_here = make_A(Rs[:, i], j_here)\n res_here = torch.matmul(results[parent[i]], A_here)\n results.append(res_here)\n\n results = torch.stack(results, dim = 1)\n\n new_J = results[:, :, :3, 3]\n Js_w0 = torch.cat([Js, torch.zeros(N, 24, 1, 1)], dim = 2)\n init_bone = torch.matmul(results, Js_w0)\n init_bone = F.pad(init_bone, [3, 0, 0, 0, 0, 0, 0, 0])\n A = results - init_bone\n\n return new_J, A\n\ndef batch_lrotmin(param):\n param = param[:,3:].contiguous()\n Rs = batch_rodrigues(param.view(-1, 3))\n e = torch.eye(3).float()\n Rs = Rs.sub(1.0, e)\n\n return Rs.view(-1, 23 * 9)\n\n\ndef rotation_matrix_to_angle_axis(rotation_matrix):\n \"\"\"\n This function is borrowed from https://github.com/kornia/kornia\n\n Convert 3x4 rotation matrix to Rodrigues vector\n\n Args:\n rotation_matrix (Tensor): rotation matrix.\n\n Returns:\n Tensor: Rodrigues vector transformation.\n\n Shape:\n - Input: :math:`(N, 3, 4)`\n - Output: :math:`(N, 3)`\n\n Example:\n >>> input = torch.rand(2, 3, 4) # Nx4x4\n >>> output = tgm.rotation_matrix_to_angle_axis(input) # Nx3\n \"\"\"\n if rotation_matrix.shape[1:] == (3,3):\n rot_mat = rotation_matrix.reshape(-1, 3, 3)\n hom = torch.tensor([0, 0, 1], dtype=torch.float32,\n device=rotation_matrix.device).reshape(1, 3, 1).expand(rot_mat.shape[0], -1, -1)\n rotation_matrix = torch.cat([rot_mat, hom], dim=-1)\n\n quaternion = rotation_matrix_to_quaternion(rotation_matrix)\n aa = quaternion_to_angle_axis(quaternion)\n aa[torch.isnan(aa)] = 0.0\n return aa\n\n\ndef quaternion_to_angle_axis(quaternion: torch.Tensor) -> torch.Tensor:\n \"\"\"\n This function is borrowed from https://github.com/kornia/kornia\n\n Convert quaternion vector to angle axis of rotation.\n\n Adapted from ceres C++ library: ceres-solver/include/ceres/rotation.h\n\n Args:\n quaternion (torch.Tensor): tensor with quaternions.\n\n Return:\n torch.Tensor: tensor with angle axis of rotation.\n\n Shape:\n - Input: :math:`(*, 4)` where `*` means, any number of dimensions\n - Output: :math:`(*, 3)`\n\n Example:\n >>> quaternion = torch.rand(2, 4) # Nx4\n >>> angle_axis = tgm.quaternion_to_angle_axis(quaternion) # Nx3\n \"\"\"\n if not torch.is_tensor(quaternion):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(quaternion)))\n\n if not quaternion.shape[-1] == 4:\n raise ValueError(\"Input must be a tensor of shape Nx4 or 4. Got {}\"\n .format(quaternion.shape))\n # unpack input and compute conversion\n q1: torch.Tensor = quaternion[..., 1]\n q2: torch.Tensor = quaternion[..., 2]\n q3: torch.Tensor = quaternion[..., 3]\n sin_squared_theta: torch.Tensor = q1 * q1 + q2 * q2 + q3 * q3\n\n sin_theta: torch.Tensor = torch.sqrt(sin_squared_theta)\n cos_theta: torch.Tensor = quaternion[..., 0]\n two_theta: torch.Tensor = 2.0 * torch.where(\n cos_theta < 0.0,\n torch.atan2(-sin_theta, -cos_theta),\n torch.atan2(sin_theta, cos_theta))\n\n k_pos: torch.Tensor = two_theta / sin_theta\n k_neg: torch.Tensor = 2.0 * torch.ones_like(sin_theta)\n k: torch.Tensor = torch.where(sin_squared_theta > 0.0, k_pos, k_neg)\n\n angle_axis: torch.Tensor = torch.zeros_like(quaternion)[..., :3]\n angle_axis[..., 0] += q1 * k\n angle_axis[..., 1] += q2 * k\n angle_axis[..., 2] += q3 * k\n return angle_axis\n\n\ndef rotation_matrix_to_quaternion(rotation_matrix, eps=1e-6):\n \"\"\"\n This function is borrowed from https://github.com/kornia/kornia\n\n Convert 3x4 rotation matrix to 4d quaternion vector\n\n This algorithm is based on algorithm described in\n https://github.com/KieranWynn/pyquaternion/blob/master/pyquaternion/quaternion.py#L201\n\n Args:\n rotation_matrix (Tensor): the rotation matrix to convert.\n\n Return:\n Tensor: the rotation in quaternion\n\n Shape:\n - Input: :math:`(N, 3, 4)`\n - Output: :math:`(N, 4)`\n\n Example:\n >>> input = torch.rand(4, 3, 4) # Nx3x4\n >>> output = tgm.rotation_matrix_to_quaternion(input) # Nx4\n \"\"\"\n if not torch.is_tensor(rotation_matrix):\n raise TypeError(\"Input type is not a torch.Tensor. Got {}\".format(\n type(rotation_matrix)))\n\n if len(rotation_matrix.shape) > 3:\n raise ValueError(\n \"Input size must be a three dimensional tensor. Got {}\".format(\n rotation_matrix.shape))\n if not rotation_matrix.shape[-2:] == (3, 4):\n raise ValueError(\n \"Input size must be a N x 3 x 4 tensor. Got {}\".format(\n rotation_matrix.shape))\n\n rmat_t = torch.transpose(rotation_matrix, 1, 2)\n\n mask_d2 = rmat_t[:, 2, 2] < eps\n\n mask_d0_d1 = rmat_t[:, 0, 0] > rmat_t[:, 1, 1]\n mask_d0_nd1 = rmat_t[:, 0, 0] < -rmat_t[:, 1, 1]\n\n t0 = 1 + rmat_t[:, 0, 0] - rmat_t[:, 1, 1] - rmat_t[:, 2, 2]\n q0 = torch.stack([rmat_t[:, 1, 2] - rmat_t[:, 2, 1],\n t0, rmat_t[:, 0, 1] + rmat_t[:, 1, 0],\n rmat_t[:, 2, 0] + rmat_t[:, 0, 2]], -1)\n t0_rep = t0.repeat(4, 1).t()\n\n t1 = 1 - rmat_t[:, 0, 0] + rmat_t[:, 1, 1] - rmat_t[:, 2, 2]\n q1 = torch.stack([rmat_t[:, 2, 0] - rmat_t[:, 0, 2],\n rmat_t[:, 0, 1] + rmat_t[:, 1, 0],\n t1, rmat_t[:, 1, 2] + rmat_t[:, 2, 1]], -1)\n t1_rep = t1.repeat(4, 1).t()\n\n t2 = 1 - rmat_t[:, 0, 0] - rmat_t[:, 1, 1] + rmat_t[:, 2, 2]\n q2 = torch.stack([rmat_t[:, 0, 1] - rmat_t[:, 1, 0],\n rmat_t[:, 2, 0] + rmat_t[:, 0, 2],\n rmat_t[:, 1, 2] + rmat_t[:, 2, 1], t2], -1)\n t2_rep = t2.repeat(4, 1).t()\n\n t3 = 1 + rmat_t[:, 0, 0] + rmat_t[:, 1, 1] + rmat_t[:, 2, 2]\n q3 = torch.stack([t3, rmat_t[:, 1, 2] - rmat_t[:, 2, 1],\n rmat_t[:, 2, 0] - rmat_t[:, 0, 2],\n rmat_t[:, 0, 1] - rmat_t[:, 1, 0]], -1)\n t3_rep = t3.repeat(4, 1).t()\n\n mask_c0 = mask_d2 * mask_d0_d1\n mask_c1 = mask_d2 * ~mask_d0_d1\n mask_c2 = ~mask_d2 * mask_d0_nd1\n mask_c3 = ~mask_d2 * ~mask_d0_nd1\n mask_c0 = mask_c0.view(-1, 1).type_as(q0)\n mask_c1 = mask_c1.view(-1, 1).type_as(q1)\n mask_c2 = mask_c2.view(-1, 1).type_as(q2)\n mask_c3 = mask_c3.view(-1, 1).type_as(q3)\n\n q = q0 * mask_c0 + q1 * mask_c1 + q2 * mask_c2 + q3 * mask_c3\n q /= torch.sqrt(t0_rep * mask_c0 + t1_rep * mask_c1 + # noqa\n t2_rep * mask_c2 + t3_rep * mask_c3) # noqa\n q *= 0.5\n return q\n\n#__________________intersection tools_______________________\n\n'''\n return whether two segment intersect\n'''\ndef line_intersect(sa, sb):\n al, ar, bl, br = sa[0], sa[1], sb[0], sb[1]\n assert al <= ar and bl <= br\n if al >= br or bl >= ar:\n return False\n return True\n\n'''\n return whether two rectangle intersect\n ra, rb left_top point, right_bottom point\n'''\ndef rectangle_intersect(ra, rb):\n ax = [ra[0][0], ra[1][0]]\n ay = [ra[0][1], ra[1][1]]\n\n bx = [rb[0][0], rb[1][0]]\n by = [rb[0][1], rb[1][1]]\n\n return line_intersect(ax, bx) and line_intersect(ay, by)\n\ndef get_intersected_rectangle(lt0, rb0, lt1, rb1):\n if not rectangle_intersect([lt0, rb0], [lt1, rb1]):\n return None, None\n\n lt = lt0.copy()\n rb = rb0.copy()\n\n lt[0] = max(lt[0], lt1[0])\n lt[1] = max(lt[1], lt1[1])\n\n rb[0] = min(rb[0], rb1[0])\n rb[1] = min(rb[1], rb1[1])\n return lt, rb\n\ndef get_union_rectangle(lt0, rb0, lt1, rb1):\n lt = lt0.copy()\n rb = rb0.copy()\n\n lt[0] = min(lt[0], lt1[0])\n lt[1] = min(lt[1], lt1[1])\n\n rb[0] = max(rb[0], rb1[0])\n rb[1] = max(rb[1], rb1[1])\n return lt, rb\n\ndef get_rectangle_area(lt, rb):\n return (rb[0] - lt[0]) * (rb[1] - lt[1])\n\ndef get_rectangle_intersect_ratio(lt0, rb0, lt1, rb1):\n (lt0, rb0), (lt1, rb1) = get_intersected_rectangle(lt0, rb0, lt1, rb1), get_union_rectangle(lt0, rb0, lt1, rb1)\n\n if lt0 is None:\n return 0.0\n else:\n return 1.0 * get_rectangle_area(lt0, rb0) / get_rectangle_area(lt1, rb1)\n"
]
| [
[
"numpy.dot",
"torch.transpose",
"numpy.savez",
"torch.sin",
"numpy.asarray",
"torch.cat",
"torch.zeros",
"numpy.max",
"torch.where",
"numpy.roll",
"numpy.linalg.svd",
"torch.norm",
"numpy.ones_like",
"torch.ones",
"torch.sqrt",
"numpy.linalg.eig",
"numpy.eye",
"numpy.uint8",
"torch.eye",
"torch.from_numpy",
"torch.tensor",
"numpy.zeros",
"torch.ones_like",
"torch.cos",
"torch.nn.functional.pad",
"torch.div",
"numpy.min",
"numpy.linalg.inv",
"torch.zeros_like",
"torch.is_tensor",
"torch.unsqueeze",
"numpy.cov",
"numpy.transpose",
"torch.stack",
"numpy.array",
"numpy.sum",
"torch.atan2",
"torch.isnan",
"numpy.tile",
"torch.matmul"
]
]
|
mjhajharia/pymc3 | [
"e03f5bf6a85ab350bf2ae3029dade7b9fc12dd07"
]
| [
"pymc/math.py"
]
| [
"# Copyright 2020 The PyMC Developers\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\nimport sys\nimport warnings\n\nfrom functools import partial, reduce\n\nimport aesara\nimport aesara.sparse\nimport aesara.tensor as at\nimport aesara.tensor.slinalg # pylint: disable=unused-import\nimport numpy as np\nimport scipy as sp\nimport scipy.sparse # pylint: disable=unused-import\n\nfrom aesara.graph.basic import Apply\nfrom aesara.graph.op import Op\n\n# pylint: disable=unused-import\nfrom aesara.tensor import (\n abs_,\n and_,\n ceil,\n clip,\n concatenate,\n constant,\n cos,\n cosh,\n dot,\n eq,\n erf,\n erfc,\n erfcinv,\n erfinv,\n exp,\n flatten,\n floor,\n ge,\n gt,\n le,\n log,\n log1pexp,\n logaddexp,\n logsumexp,\n lt,\n maximum,\n minimum,\n neq,\n ones_like,\n or_,\n prod,\n sgn,\n sigmoid,\n sin,\n sinh,\n sqr,\n sqrt,\n stack,\n sum,\n switch,\n tan,\n tanh,\n where,\n zeros_like,\n)\n\ntry:\n from aesara.tensor.basic import extract_diag\nexcept ImportError:\n from aesara.tensor.nlinalg import extract_diag\n\n\nfrom aesara.tensor.nlinalg import det, matrix_dot, matrix_inverse, trace\nfrom scipy.linalg import block_diag as scipy_block_diag\n\nfrom pymc.aesaraf import floatX, ix_, largest_common_dtype\n\n# pylint: enable=unused-import\n\n\ndef kronecker(*Ks):\n r\"\"\"Return the Kronecker product of arguments:\n :math:`K_1 \\otimes K_2 \\otimes ... \\otimes K_D`\n\n Parameters\n ----------\n Ks : Iterable of 2D array-like\n Arrays of which to take the product.\n\n Returns\n -------\n np.ndarray :\n Block matrix Kroncker product of the argument matrices.\n \"\"\"\n return reduce(at.slinalg.kron, Ks)\n\n\ndef cartesian(*arrays):\n \"\"\"Makes the Cartesian product of arrays.\n\n Parameters\n ----------\n arrays: N-D array-like\n N-D arrays where earlier arrays loop more slowly than later ones\n \"\"\"\n N = len(arrays)\n arrays_np = [np.asarray(x) for x in arrays]\n arrays_2d = [x[:, None] if np.asarray(x).ndim == 1 else x for x in arrays_np]\n arrays_integer = [np.arange(len(x)) for x in arrays_2d]\n product_integers = np.stack(np.meshgrid(*arrays_integer, indexing=\"ij\"), -1).reshape(-1, N)\n return np.concatenate(\n [array[product_integers[:, i]] for i, array in enumerate(arrays_2d)], axis=-1\n )\n\n\ndef kron_matrix_op(krons, m, op):\n r\"\"\"Apply op to krons and m in a way that reproduces ``op(kronecker(*krons), m)``\n\n Parameters\n -----------\n krons : list of square 2D array-like objects\n D square matrices :math:`[A_1, A_2, ..., A_D]` to be Kronecker'ed\n :math:`A = A_1 \\otimes A_2 \\otimes ... \\otimes A_D`\n Product of column dimensions must be :math:`N`\n m : NxM array or 1D array (treated as Nx1)\n Object that krons act upon\n\n Returns\n -------\n numpy array\n \"\"\"\n\n def flat_matrix_op(flat_mat, mat):\n Nmat = mat.shape[1]\n flat_shape = flat_mat.shape\n mat2 = flat_mat.reshape((Nmat, -1))\n return op(mat, mat2).T.reshape(flat_shape)\n\n def kron_vector_op(v):\n return reduce(flat_matrix_op, krons, v)\n\n if m.ndim == 1:\n m = m[:, None] # Treat 1D array as Nx1 matrix\n if m.ndim != 2: # Has not been tested otherwise\n raise ValueError(f\"m must have ndim <= 2, not {m.ndim}\")\n res = kron_vector_op(m)\n res_shape = res.shape\n return at.reshape(res, (res_shape[1], res_shape[0])).T\n\n\n# Define kronecker functions that work on 1D and 2D arrays\nkron_dot = partial(kron_matrix_op, op=at.dot)\nkron_solve_lower = partial(kron_matrix_op, op=at.slinalg.solve_lower_triangular)\nkron_solve_upper = partial(kron_matrix_op, op=at.slinalg.solve_upper_triangular)\n\n\ndef flat_outer(a, b):\n return at.outer(a, b).ravel()\n\n\ndef kron_diag(*diags):\n \"\"\"Returns diagonal of a kronecker product.\n\n Parameters\n ----------\n diags: 1D arrays\n The diagonals of matrices that are to be Kroneckered\n \"\"\"\n return reduce(flat_outer, diags)\n\n\ndef tround(*args, **kwargs):\n \"\"\"\n Temporary function to silence round warning in Aesara. Please remove\n when the warning disappears.\n \"\"\"\n kwargs[\"mode\"] = \"half_to_even\"\n return at.round(*args, **kwargs)\n\n\ndef logdiffexp(a, b):\n \"\"\"log(exp(a) - exp(b))\"\"\"\n return a + at.log1mexp(b - a)\n\n\ndef logdiffexp_numpy(a, b):\n \"\"\"log(exp(a) - exp(b))\"\"\"\n return a + log1mexp_numpy(b - a, negative_input=True)\n\n\ndef invlogit(x, eps=None):\n \"\"\"The inverse of the logit function, 1 / (1 + exp(-x)).\"\"\"\n if eps is not None:\n warnings.warn(\n \"pymc.math.invlogit no longer supports the ``eps`` argument and it will be ignored.\",\n DeprecationWarning,\n stacklevel=2,\n )\n return at.sigmoid(x)\n\n\ndef logbern(log_p):\n if np.isnan(log_p):\n raise FloatingPointError(\"log_p can't be nan.\")\n return np.log(np.random.uniform()) < log_p\n\n\ndef logit(p):\n return at.log(p / (floatX(1) - p))\n\n\ndef log1mexp(x, *, negative_input=False):\n r\"\"\"Return log(1 - exp(-x)).\n\n This function is numerically more stable than the naive approach.\n\n For details, see\n https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf\n\n References\n ----------\n .. [Machler2012] Martin Mรคchler (2012).\n \"Accurately computing `\\log(1-\\exp(- \\mid a \\mid))` Assessed by the Rmpfr package\"\n\n \"\"\"\n if not negative_input:\n warnings.warn(\n \"pymc.math.log1mexp will expect a negative input in a future \"\n \"version of PyMC.\\n To suppress this warning set `negative_input=True`\",\n FutureWarning,\n stacklevel=2,\n )\n x = -x\n\n return at.log1mexp(x)\n\n\ndef log1mexp_numpy(x, *, negative_input=False):\n \"\"\"Return log(1 - exp(x)).\n This function is numerically more stable than the naive approach.\n For details, see\n https://cran.r-project.org/web/packages/Rmpfr/vignettes/log1mexp-note.pdf\n \"\"\"\n x = np.asarray(x, dtype=\"float\")\n\n if not negative_input:\n warnings.warn(\n \"pymc.math.log1mexp_numpy will expect a negative input in a future \"\n \"version of PyMC.\\n To suppress this warning set `negative_input=True`\",\n FutureWarning,\n stacklevel=2,\n )\n x = -x\n\n out = np.empty_like(x)\n mask = x < -0.6931471805599453 # log(1/2)\n out[mask] = np.log1p(-np.exp(x[mask]))\n mask = ~mask\n out[mask] = np.log(-np.expm1(x[mask]))\n return out\n\n\ndef flatten_list(tensors):\n return at.concatenate([var.ravel() for var in tensors])\n\n\nclass LogDet(Op):\n r\"\"\"Compute the logarithm of the absolute determinant of a square\n matrix M, log(abs(det(M))) on the CPU. Avoids det(M) overflow/\n underflow.\n\n Notes\n -----\n Once PR #3959 (https://github.com/Theano/Theano/pull/3959/) by harpone is merged,\n this must be removed.\n \"\"\"\n\n def make_node(self, x):\n x = aesara.tensor.as_tensor_variable(x)\n o = aesara.tensor.scalar(dtype=x.dtype)\n return Apply(self, [x], [o])\n\n def perform(self, node, inputs, outputs, params=None):\n try:\n (x,) = inputs\n (z,) = outputs\n s = np.linalg.svd(x, compute_uv=False)\n log_det = np.sum(np.log(np.abs(s)))\n z[0] = np.asarray(log_det, dtype=x.dtype)\n except Exception:\n print(f\"Failed to compute logdet of {x}.\", file=sys.stdout)\n raise\n\n def grad(self, inputs, g_outputs):\n [gz] = g_outputs\n [x] = inputs\n return [gz * matrix_inverse(x).T]\n\n def __str__(self):\n return \"LogDet\"\n\n\nlogdet = LogDet()\n\n\ndef probit(p):\n return -sqrt(2.0) * erfcinv(2.0 * p)\n\n\ndef invprobit(x):\n return 0.5 * erfc(-x / sqrt(2.0))\n\n\ndef expand_packed_triangular(n, packed, lower=True, diagonal_only=False):\n r\"\"\"Convert a packed triangular matrix into a two dimensional array.\n\n Triangular matrices can be stored with better space efficiency by\n storing the non-zero values in a one-dimensional array. We number\n the elements by row like this (for lower or upper triangular matrices):\n\n [[0 - - -] [[0 1 2 3]\n [1 2 - -] [- 4 5 6]\n [3 4 5 -] [- - 7 8]\n [6 7 8 9]] [- - - 9]\n\n Parameters\n ----------\n n: int\n The number of rows of the triangular matrix.\n packed: aesara.vector\n The matrix in packed format.\n lower: bool, default=True\n If true, assume that the matrix is lower triangular.\n diagonal_only: bool\n If true, return only the diagonal of the matrix.\n \"\"\"\n if packed.ndim != 1:\n raise ValueError(\"Packed triangular is not one dimensional.\")\n if not isinstance(n, int):\n raise TypeError(\"n must be an integer\")\n\n if diagonal_only and lower:\n diag_idxs = np.arange(1, n + 1).cumsum() - 1\n return packed[diag_idxs]\n elif diagonal_only and not lower:\n diag_idxs = np.arange(2, n + 2)[::-1].cumsum() - n - 1\n return packed[diag_idxs]\n elif lower:\n out = at.zeros((n, n), dtype=aesara.config.floatX)\n idxs = np.tril_indices(n)\n return at.set_subtensor(out[idxs], packed)\n elif not lower:\n out = at.zeros((n, n), dtype=aesara.config.floatX)\n idxs = np.triu_indices(n)\n return at.set_subtensor(out[idxs], packed)\n\n\nclass BatchedDiag(Op):\n \"\"\"\n Fast BatchedDiag allocation\n \"\"\"\n\n __props__ = ()\n\n def make_node(self, diag):\n diag = at.as_tensor_variable(diag)\n if diag.type.ndim != 2:\n raise TypeError(\"data argument must be a matrix\", diag.type)\n\n return Apply(self, [diag], [at.tensor3(dtype=diag.dtype)])\n\n def perform(self, node, ins, outs, params=None):\n (C,) = ins\n (z,) = outs\n\n bc = C.shape[0]\n dim = C.shape[-1]\n Cd = np.zeros((bc, dim, dim), C.dtype)\n bidx = np.repeat(np.arange(bc), dim)\n didx = np.tile(np.arange(dim), bc)\n Cd[bidx, didx, didx] = C.flatten()\n z[0] = Cd\n\n def grad(self, inputs, gout):\n (gz,) = gout\n idx = at.arange(gz.shape[-1])\n return [gz[..., idx, idx]]\n\n def infer_shape(self, fgraph, nodes, shapes):\n return [(shapes[0][0],) + (shapes[0][1],) * 2]\n\n\ndef batched_diag(C):\n C = at.as_tensor(C)\n dim = C.shape[-1]\n if C.ndim == 2:\n # diag -> matrices\n return BatchedDiag()(C)\n elif C.ndim == 3:\n # matrices -> diag\n idx = at.arange(dim)\n return C[..., idx, idx]\n else:\n raise ValueError(\"Input should be 2 or 3 dimensional\")\n\n\nclass BlockDiagonalMatrix(Op):\n __props__ = (\"sparse\", \"format\")\n\n def __init__(self, sparse=False, format=\"csr\"):\n if format not in (\"csr\", \"csc\"):\n raise ValueError(f\"format must be one of: 'csr', 'csc', got {format}\")\n self.sparse = sparse\n self.format = format\n\n def make_node(self, *matrices):\n if not matrices:\n raise ValueError(\"no matrices to allocate\")\n matrices = list(map(at.as_tensor, matrices))\n if any(mat.type.ndim != 2 for mat in matrices):\n raise TypeError(\"all data arguments must be matrices\")\n if self.sparse:\n out_type = aesara.sparse.matrix(self.format, dtype=largest_common_dtype(matrices))\n else:\n out_type = aesara.tensor.matrix(dtype=largest_common_dtype(matrices))\n return Apply(self, matrices, [out_type])\n\n def perform(self, node, inputs, output_storage, params=None):\n dtype = largest_common_dtype(inputs)\n if self.sparse:\n output_storage[0][0] = sp.sparse.block_diag(inputs, self.format, dtype)\n else:\n output_storage[0][0] = scipy_block_diag(*inputs).astype(dtype)\n\n def grad(self, inputs, gout):\n shapes = at.stack([i.shape for i in inputs])\n index_end = shapes.cumsum(0)\n index_begin = index_end - shapes\n slices = [\n ix_(\n at.arange(index_begin[i, 0], index_end[i, 0]),\n at.arange(index_begin[i, 1], index_end[i, 1]),\n )\n for i in range(len(inputs))\n ]\n return [gout[0][slc] for slc in slices]\n\n def infer_shape(self, fgraph, nodes, shapes):\n first, second = zip(*shapes)\n return [(at.add(*first), at.add(*second))]\n\n\ndef block_diagonal(matrices, sparse=False, format=\"csr\"):\n r\"\"\"See scipy.sparse.block_diag or\n scipy.linalg.block_diag for reference\n\n Parameters\n ----------\n matrices: tensors\n format: str (default 'csr')\n must be one of: 'csr', 'csc'\n sparse: bool (default False)\n if True return sparse format\n\n Returns\n -------\n matrix\n \"\"\"\n if len(matrices) == 1: # graph optimization\n return matrices[0]\n return BlockDiagonalMatrix(sparse=sparse, format=format)(*matrices)\n"
]
| [
[
"numpy.linalg.svd",
"numpy.abs",
"numpy.meshgrid",
"numpy.triu_indices",
"numpy.isnan",
"numpy.empty_like",
"numpy.asarray",
"numpy.arange",
"scipy.sparse.block_diag",
"numpy.tril_indices",
"numpy.expm1",
"scipy.linalg.block_diag",
"numpy.random.uniform",
"numpy.exp",
"numpy.zeros"
]
]
|
Yangzhen0000/CDVD-TSP | [
"95adff7c0b827b7170619b58a3edcec03a9a137e"
]
| [
"code/model/motion_net.py"
]
| [
"import torch\nimport torch.nn as nn\n\ndef make_model(args):\n device = 'cpu' if args.cpu else 'cuda'\n return MotionNet()\n\n\nclass MotionNet(nn.Module):\n \"\"\"docstring for MotionNet\"\"\"\n def __init__(self):\n super(MotionNet, self).__init__()\n print(\"Creating MotionNet\")\n\n self.conv1 = nn.Sequential(\n nn.Conv2d(in_channels=6, out_channels=64, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv1_1 = nn.Sequential(\n nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv2 = nn.Sequential(\n nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv2_1 = nn.Sequential(\n nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv3 = nn.Sequential(\n nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv3_1 = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv4 = nn.Sequential(\n nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv4_1 = nn.Sequential(\n nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv5 = nn.Sequential(\n nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv5_1 = nn.Sequential(\n nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv6 = nn.Sequential(\n nn.Conv2d(in_channels=512, out_channels=1024, kernel_size=3, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.conv6_1 = nn.Sequential(\n nn.Conv2d(in_channels=1024, out_channels=1024, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.flow6 = nn.Conv2d(in_channels=1024, out_channels=2, kernel_size=3, stride=1, padding=1)\n self.upsample_flow6to5 = nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)\n self.deconv5 = nn.Sequential(\n nn.ConvTranspose2d(in_channels=1024, out_channels=512, kernel_size=4, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.xconv5 = nn.Sequential(\n nn.Conv2d(in_channels=512+2+512, out_channels=512, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.flow5 = nn.Conv2d(in_channels=512, out_channels=2, kernel_size=3, stride=1, padding=1)\n self.upsample_flow5to4 = nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)\n self.deconv4 = nn.Sequential(\n nn.ConvTranspose2d(in_channels=512, out_channels=256, kernel_size=4, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.xconv4 = nn.Sequential(\n nn.Conv2d(in_channels=256+2+512, out_channels=256, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.flow4 = nn.Conv2d(in_channels=256, out_channels=2, kernel_size=3, stride=1, padding=1)\n self.upsample_flow4to3 = nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)\n self.deconv3 = nn.Sequential(\n nn.ConvTranspose2d(in_channels=256, out_channels=128, kernel_size=4, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.xconv3 = nn.Sequential(\n nn.Conv2d(in_channels=128+2+256, out_channels=128, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.flow3 = nn.Conv2d(in_channels=128, out_channels=2, kernel_size=3, stride=1, padding=1)\n self.upsample_flow3to2 = nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)\n self.deconv2 = nn.Sequential(\n nn.ConvTranspose2d(in_channels=128, out_channels=64, kernel_size=4, stride=2, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.xconv2 = nn.Sequential(\n nn.Conv2d(in_channels=64+2+128, out_channels=64, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.flow2 = nn.Sequential(\n nn.Conv2d(in_channels=64, out_channels=2, kernel_size=3, stride=1, padding=1),\n nn.LeakyReLU(negative_slope=0.1)\n )\n self.flow = nn.ConvTranspose2d(in_channels=2, out_channels=2, kernel_size=4, stride=2, padding=1)\n\n\n def forward(self, tensor1, tensor2):\n frames = torch.cat([tensor1, tensor2], dim=1)\n conv1_feat = self.conv1(frames)\n conv1_1_feat = self.conv1_1(conv1_feat)\n conv2_feat = self.conv2(conv1_1_feat)\n conv2_1_feat = self.conv2_1(conv2_feat)\n conv3_feat = self.conv3(conv2_1_feat)\n conv3_1_feat = self.conv3_1(conv3_feat)\n conv4_feat = self.conv4(conv3_1_feat)\n conv4_1_feat = self.conv4_1(conv4_feat)\n conv5_feat = self.conv5(conv4_1_feat)\n conv5_1_feat = self.conv5_1(conv5_feat)\n conv6_feat = self.conv6(conv5_1_feat)\n conv6_1_feat = self.conv6_1(conv6_feat)\n\n flow6_feat = self.flow6(conv6_1_feat)\n upsample_flow6to5_feat = self.upsample_flow6to5(flow6_feat)\n deconv5_feat = self.deconv5(conv6_1_feat)\n concat_5_feat = torch.cat([deconv5_feat, upsample_flow6to5_feat, conv5_1_feat], dim=1)\n xconv5_feat = self.xconv5(concat_5_feat)\n\n flow5_feat = self.flow5(xconv5_feat)\n upsample_flow5to4_feat = self.upsample_flow5to4(flow5_feat)\n deconv4_feat = self.deconv4(xconv5_feat)\n concat_4_feat = torch.cat([deconv4_feat, upsample_flow5to4_feat, conv4_1_feat], dim=1)\n xconv4_feat = self.xconv4(concat_4_feat)\n\n flow4_feat = self.flow4(xconv4_feat)\n upsample_flow4to3_feat = self.upsample_flow4to3(flow4_feat)\n deconv3_feat = self.deconv3(xconv4_feat)\n concat_3_feat = torch.cat([deconv3_feat, upsample_flow4to3_feat, conv3_1_feat], dim=1)\n xconv3_feat = self.xconv3(concat_3_feat)\n\n flow3_feat = self.flow3(xconv3_feat)\n upsample_flow3to2_feat = self.upsample_flow3to2(flow3_feat)\n deconv2_feat = self.deconv2(xconv3_feat)\n concat_2_feat = torch.cat([deconv2_feat, upsample_flow3to2_feat, conv2_1_feat], dim=1)\n xconv2_feat = self.xconv2(concat_2_feat)\n\n flow2_feat = self.flow2(xconv2_feat)\n flow_out = self.flow(flow2_feat)\n\n return flow_out\n\n"
]
| [
[
"torch.nn.Conv2d",
"torch.nn.LeakyReLU",
"torch.nn.ConvTranspose2d",
"torch.cat"
]
]
|
NatureGeorge/pyRMSD | [
"9b45fcad944596a021823c9d5a5b73fcddbcd1fc"
]
| [
"pyRMSD/benchmark/BenchmarkNeighborOperations.py"
]
| [
"\"\"\"\nCreated on 10/08/2012\n\n@author: victor\n\"\"\"\nfrom __future__ import print_function\nimport time\nimport random\nimport numpy\nfrom pyRMSD.condensedMatrix import CondensedMatrix\nimport pyRMSD.benchmark.alias.condensedMatrix as PythonCondensedMatrix\nfrom pyRMSD.benchmark.alias.neighbourOps import choose_node_with_higher_cardinality,\\\n get_neighbors_for_node\n \nif __name__ == '__main__':\n \n print(\"Creating data...\")\n row_size = 20000\n matrix_elem_size = row_size*(row_size-1)/2\n contents = numpy.array(random.sample(xrange(matrix_elem_size+1),matrix_elem_size))\n float_contents = contents / float(max(contents))\n del contents\n matrix = CondensedMatrix(float_contents)\n matrix2 = PythonCondensedMatrix.CondensedMatrix(float_contents)\n remaining_nodes = range(row_size)\n\n print(\"======================================\")\n print(\"'get_neighbors_for_node' benchmark\")\n print(\"======================================\")\n time_start = time.time()\n neighbors1 = matrix.get_neighbors_for_node(1,remaining_nodes, 0.5)\n time_end = time.time()\n print(\"Fast Neighbor search for Fast matrix took %.3fs\"%(time_end-time_start))\n \n time_start = time.time()\n neighbors2 = matrix2.get_neighbors_for_node(1,remaining_nodes, 0.5)\n time_end = time.time()\n print(\"Slow Neighbor search for Slow matrix took %.3fs\"%(time_end-time_start))\n \n time_start = time.time()\n neighbors3 = get_neighbors_for_node(matrix, 1,remaining_nodes, 0.5)\n time_end = time.time()\n print(\"Slow Neighbor search for Fast matrix took %.3fs\"%(time_end-time_start))\n \n print(\"======================================\")\n print(\"'get_neighbors_for_node' validation\")\n print(\"======================================\")\n try:\n numpy.testing.assert_array_equal(neighbors1,neighbors2)\n numpy.testing.assert_array_equal(neighbors1,neighbors3)\n print(\"OK\")\n except Exception as message:\n print(message)\n print(\"KO\")\n \n print(\"================================================\")\n print(\"'choose_node_with_higher_cardinality' benchmark\")\n print(\"================================================\")\n time_start = time.time()\n neighbors1 = matrix.choose_node_with_higher_cardinality(remaining_nodes, 0.5)\n time_end = time.time()\n print(\"Fast Neighbor cardinality for Fast matrix took %.3fs\"%(time_end-time_start))\n \n time_start = time.time()\n neighbors2 = matrix2.choose_node_with_higher_cardinality(remaining_nodes, 0.5)\n time_end = time.time()\n print(\"Slow Neighbor cardinality for Slow matrix took %.3fs\"%(time_end-time_start))\n \n time_start = time.time()\n neighbors3 = choose_node_with_higher_cardinality(matrix,remaining_nodes, 0.5)\n time_end = time.time()\n print(\"Slow Neighbor cardinality for Fast matrix took %.3fs\"%(time_end-time_start))\n \n print(\"================================================\")\n print(\"'choose_node_with_higher_cardinality' validation\")\n print(\"================================================\")\n if(neighbors1 == neighbors2 and neighbors2 == neighbors3):\n print(\"OK\")\n else:\n print(\"KO\")\n"
]
| [
[
"numpy.testing.assert_array_equal"
]
]
|
bianzheng123/SimilaritySearchScript | [
"7fcfd7c161bd33e1f8135c1479eae3fc538f7fe1"
]
| [
"draw_curve/paper/config_compare.py"
]
| [
"import json\nimport matplotlib.pyplot as plt\n\n\ndef get_cluster_nn_classification(json_dir):\n x_arr = []\n y_arr = []\n with open(json_dir, 'r') as file:\n json_data = json.load(file)\n for ele in json_data:\n if ele['recall'] == 0.0:\n continue\n x_arr.append(ele['n_candidate'])\n y_arr.append(ele['recall'])\n return x_arr, y_arr\n\n\nmethod2category = {\n 'opq': 'baseline',\n 'pq': 'baseline',\n 'knn': 'nn',\n 'knn_random_projection': 'nn',\n 'e2lsh': 'count',\n 'knn_kmeans_multiple': 'nn'\n}\n\n# deep gist glove imagenet sift\ndataset_name = 'sift'\nn_cluster = 256\n\nmethod = 'knn_random_projection'\nn_classifier = 4\nspecific_name = 'model'\nspecific_val_l = ['one_block_512_dim', 'one_block_2048_dim', 'two_block_512_dim', 'two_block_1024_dim']\n\ndir_arr = []\nfor val in specific_val_l:\n cate = method2category[method]\n fname = '%s_%d_%s_%d_%s' % (dataset_name, n_cluster, cate, n_classifier, method)\n if cate == 'baseline':\n raise Exception('not support the category')\n fname = '{}_{}_{}'.format(fname, specific_name, val)\n print(fname)\n dir_arr.append(\"../%s/%s/result.json\" % (dataset_name, fname))\n\ncls_arr = []\nfor i in range(len(dir_arr)):\n cls_tmp = get_cluster_nn_classification(dir_arr[i])\n cls_arr.append(cls_tmp)\n\n# ็ฌฌไธไธชๆฏๆจชๅๆ ็ๅผ๏ผ็ฌฌไบไธชๆฏ็บตๅๆ ็ๅผ\n# plt.figure(num=3, figsize=(8, 5))\n# marker\n# o ๅๅ, v ๅไธ่ง, ^ ๆญฃไธ่ง, < ๅทฆไธ่ง, > ๅณไธ่ง, 8 ๅคงๅๅ, s ๆญฃๆนๅฝข, p ๅๅ, * ๆๅท, h ่ฑๅฝข, H ๅ
ญ้ขไฝ, D ๅคง่ฑๅฝข, d ็ฆ็่ฑๅฝข, P ๅ ๅท, X ไนๅท\n# ็ดซ่ฒ#b9529f ่่ฒ#3953a4 ็บข่ฒ#ed2024 #231f20 ๆทฑ็ปฟ่ฒ#098140 ๆต
็ปฟ่ฒ#7f8133 #0084ff\n# solid dotted\n\nmarker_l = ['H', 'D', 'P', '>', '*', 'X', 's', '<', '^', 'p', 'v']\ncolor_l = ['#b9529f', '#3953a4', '#ed2024', '#098140', '#231f20', '#7f8133', '#0084ff']\nfor i, val in enumerate(specific_val_l):\n label = val\n plt.plot(cls_arr[i][0], cls_arr[i][1], marker=marker_l[i], linestyle='solid',\n color=color_l[i],\n label=label)\n\nplt.xscale('log')\n# plt.xlim(1, 500000)\n\n# line, = plt.plot(curve[0], curve[1], marker='o', linestyle='solid', label='$M$: 2', color='#b9529f')\n\n# ไฝฟ็จ๏ฝ๏ฝ
๏ฝ๏ฝ
๏ฝ๏ฝ็ปๅถๅคๆกๆฒ็บฟ\n# plt.title('graph kmeans vs knn')\ntitle_ds_name = '%s %s' % (dataset_name, '10K' if 'small' in dataset_name else '1M')\nplt.legend(loc='upper left')\n\nplt.xlabel(\"Item\")\nplt.ylabel(\"Recall\")\nplt.grid(True, linestyle='-.')\n# plt.xticks([0, 0.1, 0.2, 0.3, 0.4])\n# plt.yticks([0.75, 0.8, 0.85])\nplt.show()\n"
]
| [
[
"matplotlib.pyplot.legend",
"matplotlib.pyplot.plot",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.grid",
"matplotlib.pyplot.xscale",
"matplotlib.pyplot.show",
"matplotlib.pyplot.ylabel"
]
]
|
zecevic-matej/gan_transforming_faces | [
"079662fc148d8a114d8e902d2df40a5ca50f0970"
]
| [
"pix2pix_script.py"
]
| [
"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport numpy as np\nimport argparse\nimport os\nimport json\nimport glob\nimport random\nimport collections\nimport math\nimport time\n\nconfig = {\n \"input_dir\": None,\n \"mode\": \"test\",\n \"output_dir\": None,\n \"checkpoint\": None,\n\n \"seed\": None,\n \"summary_freq\": 100,\n \"progress_freq\": 50,\n \"trace_freq\": 0,\n \"display_freq\": 0,\n \"save_freq\": 5000,\n \"aspect_ratio\": 1.0,\n \"batch_size\": 1,\n \"lr\": 0.0002,\n \"beta1\": 0.5,\n \"which_direction\": \"BtoA\",\n \"ngf\": 64,\n \"ndf\": 64,\n \"scale_size\": 286,\n \"l1_weight\": 100.0,\n \"gan_weight\": 1.0,\n \"flip\": False\n\n}\n\n# SETTINGS\nconfig[\"input_dir\"] = \"script_imgs/1st\"\nconfig[\"output_dir\"] = \"script_test\"\nconfig[\"checkpoint\"] = \"trump_train\"\n\na = config\n\nEPS = 1e-12\nCROP_SIZE = 256\n\nExamples = collections.namedtuple(\"Examples\", \"paths, inputs, targets, count, steps_per_epoch\")\nModel = collections.namedtuple(\"Model\", \"outputs, predict_real, predict_fake, discrim_loss, discrim_grads_and_vars, gen_loss_GAN, gen_loss_L1, gen_grads_and_vars, train\")\n\n\n# parser = argparse.ArgumentParser()\n# parser.add_argument(\"--input_dir\", help=\"path to folder containing images\")\n# parser.add_argument(\"--mode\", required=False, choices=[\"train\", \"test\", \"export\"])\n# parser.add_argument(\"--output_dir\", required=True, help=\"where to put output files\")\n# parser.add_argument(\"--seed\", type=int)\n# parser.add_argument(\"--checkpoint\", default=None, help=\"directory with checkpoint to resume training from or use for testing\")\n#\n# parser.add_argument(\"--max_steps\", type=int, help=\"number of training steps (0 to disable)\")\n# parser.add_argument(\"--max_epochs\", type=int, help=\"number of training epochs\")\n# parser.add_argument(\"--summary_freq\", type=int, default=100, help=\"update summaries every summary_freq steps\")\n# parser.add_argument(\"--progress_freq\", type=int, default=50, help=\"display progress every progress_freq steps\")\n# parser.add_argument(\"--trace_freq\", type=int, default=0, help=\"trace execution every trace_freq steps\")\n# parser.add_argument(\"--display_freq\", type=int, default=0, help=\"write current training images every display_freq steps\")\n# parser.add_argument(\"--save_freq\", type=int, default=5000, help=\"save model every save_freq steps, 0 to disable\")\n#\n# parser.add_argument(\"--separable_conv\", action=\"store_true\", help=\"use separable convolutions in the generator\")\n# parser.add_argument(\"--aspect_ratio\", type=float, default=1.0, help=\"aspect ratio of output images (width/height)\")\n# parser.add_argument(\"--lab_colorization\", action=\"store_true\", help=\"split input image into brightness (A) and color (B)\")\n# parser.add_argument(\"--batch_size\", type=int, default=1, help=\"number of images in batch\")\n# parser.add_argument(\"--which_direction\", type=str, default=\"AtoB\", choices=[\"AtoB\", \"BtoA\"])\n# parser.add_argument(\"--ngf\", type=int, default=64, help=\"number of generator filters in first conv layer\")\n# parser.add_argument(\"--ndf\", type=int, default=64, help=\"number of discriminator filters in first conv layer\")\n# parser.add_argument(\"--scale_size\", type=int, default=286, help=\"scale images to this size before cropping to 256x256\")\n# parser.add_argument(\"--flip\", dest=\"flip\", action=\"store_true\", help=\"flip images horizontally\")\n# parser.add_argument(\"--no_flip\", dest=\"flip\", action=\"store_false\", help=\"don't flip images horizontally\")\n# parser.set_defaults(flip=True)\n# parser.add_argument(\"--lr\", type=float, default=0.0002, help=\"initial learning rate for adam\")\n# parser.add_argument(\"--beta1\", type=float, default=0.5, help=\"momentum term of adam\")\n# parser.add_argument(\"--l1_weight\", type=float, default=100.0, help=\"weight on L1 term for generator gradient\")\n# parser.add_argument(\"--gan_weight\", type=float, default=1.0, help=\"weight on GAN term for generator gradient\")\n#\n# # export options\n# parser.add_argument(\"--output_filetype\", default=\"png\", choices=[\"png\", \"jpeg\"])\n\n#a = parser.parse_args()\n\n\n##################################\n## FUNCTION DEFINITIONS\n##################################\ndef create_model(inputs, targets):\n def create_discriminator(discrim_inputs, discrim_targets):\n n_layers = 3\n layers = []\n\n # 2x [batch, height, width, in_channels] => [batch, height, width, in_channels * 2]\n input = tf.concat([discrim_inputs, discrim_targets], axis=3)\n\n # layer_1: [batch, 256, 256, in_channels * 2] => [batch, 128, 128, ndf]\n with tf.variable_scope(\"layer_1\"):\n convolved = discrim_conv(input, a[\"ndf\"], stride=2)\n rectified = lrelu(convolved, 0.2)\n layers.append(rectified)\n\n # layer_2: [batch, 128, 128, ndf] => [batch, 64, 64, ndf * 2]\n # layer_3: [batch, 64, 64, ndf * 2] => [batch, 32, 32, ndf * 4]\n # layer_4: [batch, 32, 32, ndf * 4] => [batch, 31, 31, ndf * 8]\n for i in range(n_layers):\n with tf.variable_scope(\"layer_%d\" % (len(layers) + 1)):\n out_channels = a[\"ndf\"] * min(2**(i+1), 8)\n stride = 1 if i == n_layers - 1 else 2 # last layer here has stride 1\n convolved = discrim_conv(layers[-1], out_channels, stride=stride)\n normalized = batchnorm(convolved)\n rectified = lrelu(normalized, 0.2)\n layers.append(rectified)\n\n # layer_5: [batch, 31, 31, ndf * 8] => [batch, 30, 30, 1]\n with tf.variable_scope(\"layer_%d\" % (len(layers) + 1)):\n convolved = discrim_conv(rectified, out_channels=1, stride=1)\n output = tf.sigmoid(convolved)\n layers.append(output)\n\n return layers[-1]\n\n with tf.variable_scope(\"generator\"):\n out_channels = int(targets.get_shape()[-1])\n outputs = create_generator(inputs, out_channels)\n\n # create two copies of discriminator, one for real pairs and one for fake pairs\n # they share the same underlying variables\n with tf.name_scope(\"real_discriminator\"):\n with tf.variable_scope(\"discriminator\"):\n # 2x [batch, height, width, channels] => [batch, 30, 30, 1]\n predict_real = create_discriminator(inputs, targets)\n\n with tf.name_scope(\"fake_discriminator\"):\n with tf.variable_scope(\"discriminator\", reuse=True):\n # 2x [batch, height, width, channels] => [batch, 30, 30, 1]\n predict_fake = create_discriminator(inputs, outputs)\n\n with tf.name_scope(\"discriminator_loss\"):\n # minimizing -tf.log will try to get inputs to 1\n # predict_real => 1\n # predict_fake => 0\n discrim_loss = tf.reduce_mean(-(tf.log(predict_real + EPS) + tf.log(1 - predict_fake + EPS)))\n\n with tf.name_scope(\"generator_loss\"):\n # predict_fake => 1\n # abs(targets - outputs) => 0\n gen_loss_GAN = tf.reduce_mean(-tf.log(predict_fake + EPS))\n gen_loss_L1 = tf.reduce_mean(tf.abs(targets - outputs))\n gen_loss = gen_loss_GAN * a[\"gan_weight\"] + gen_loss_L1 * a[\"l1_weight\"]\n\n with tf.name_scope(\"discriminator_train\"):\n discrim_tvars = [var for var in tf.trainable_variables() if var.name.startswith(\"discriminator\")]\n discrim_optim = tf.train.AdamOptimizer(a[\"lr\"], a[\"beta1\"])\n discrim_grads_and_vars = discrim_optim.compute_gradients(discrim_loss, var_list=discrim_tvars)\n discrim_train = discrim_optim.apply_gradients(discrim_grads_and_vars)\n\n with tf.name_scope(\"generator_train\"):\n with tf.control_dependencies([discrim_train]):\n gen_tvars = [var for var in tf.trainable_variables() if var.name.startswith(\"generator\")]\n gen_optim = tf.train.AdamOptimizer(a[\"lr\"], a[\"beta1\"])\n gen_grads_and_vars = gen_optim.compute_gradients(gen_loss, var_list=gen_tvars)\n gen_train = gen_optim.apply_gradients(gen_grads_and_vars)\n\n ema = tf.train.ExponentialMovingAverage(decay=0.99)\n update_losses = ema.apply([discrim_loss, gen_loss_GAN, gen_loss_L1])\n\n global_step = tf.train.get_or_create_global_step()\n incr_global_step = tf.assign(global_step, global_step+1)\n\n return Model(\n predict_real=predict_real,\n predict_fake=predict_fake,\n discrim_loss=ema.average(discrim_loss),\n discrim_grads_and_vars=discrim_grads_and_vars,\n gen_loss_GAN=ema.average(gen_loss_GAN),\n gen_loss_L1=ema.average(gen_loss_L1),\n gen_grads_and_vars=gen_grads_and_vars,\n outputs=outputs,\n train=tf.group(update_losses, incr_global_step, gen_train),\n )\ndef create_generator(generator_inputs, generator_outputs_channels):\n layers = []\n\n # encoder_1: [batch, 256, 256, in_channels] => [batch, 128, 128, ngf]\n with tf.variable_scope(\"encoder_1\"):\n output = gen_conv(generator_inputs, a[\"ngf\"])\n layers.append(output)\n\n layer_specs = [\n a[\"ngf\"] * 2, # encoder_2: [batch, 128, 128, ngf] => [batch, 64, 64, ngf * 2]\n a[\"ngf\"] * 4, # encoder_3: [batch, 64, 64, ngf * 2] => [batch, 32, 32, ngf * 4]\n a[\"ngf\"] * 8, # encoder_4: [batch, 32, 32, ngf * 4] => [batch, 16, 16, ngf * 8]\n a[\"ngf\"] * 8, # encoder_5: [batch, 16, 16, ngf * 8] => [batch, 8, 8, ngf * 8]\n a[\"ngf\"] * 8, # encoder_6: [batch, 8, 8, ngf * 8] => [batch, 4, 4, ngf * 8]\n a[\"ngf\"] * 8, # encoder_7: [batch, 4, 4, ngf * 8] => [batch, 2, 2, ngf * 8]\n a[\"ngf\"] * 8, # encoder_8: [batch, 2, 2, ngf * 8] => [batch, 1, 1, ngf * 8]\n ]\n\n for out_channels in layer_specs:\n with tf.variable_scope(\"encoder_%d\" % (len(layers) + 1)):\n rectified = lrelu(layers[-1], 0.2)\n # [batch, in_height, in_width, in_channels] => [batch, in_height/2, in_width/2, out_channels]\n convolved = gen_conv(rectified, out_channels)\n output = batchnorm(convolved)\n layers.append(output)\n\n layer_specs = [\n (a[\"ngf\"] * 8, 0.5), # decoder_8: [batch, 1, 1, ngf * 8] => [batch, 2, 2, ngf * 8 * 2]\n (a[\"ngf\"] * 8, 0.5), # decoder_7: [batch, 2, 2, ngf * 8 * 2] => [batch, 4, 4, ngf * 8 * 2]\n (a[\"ngf\"] * 8, 0.5), # decoder_6: [batch, 4, 4, ngf * 8 * 2] => [batch, 8, 8, ngf * 8 * 2]\n (a[\"ngf\"] * 8, 0.0), # decoder_5: [batch, 8, 8, ngf * 8 * 2] => [batch, 16, 16, ngf * 8 * 2]\n (a[\"ngf\"] * 4, 0.0), # decoder_4: [batch, 16, 16, ngf * 8 * 2] => [batch, 32, 32, ngf * 4 * 2]\n (a[\"ngf\"] * 2, 0.0), # decoder_3: [batch, 32, 32, ngf * 4 * 2] => [batch, 64, 64, ngf * 2 * 2]\n (a[\"ngf\"], 0.0), # decoder_2: [batch, 64, 64, ngf * 2 * 2] => [batch, 128, 128, ngf * 2]\n ]\n\n num_encoder_layers = len(layers)\n for decoder_layer, (out_channels, dropout) in enumerate(layer_specs):\n skip_layer = num_encoder_layers - decoder_layer - 1\n with tf.variable_scope(\"decoder_%d\" % (skip_layer + 1)):\n if decoder_layer == 0:\n # first decoder layer doesn't have skip connections\n # since it is directly connected to the skip_layer\n input = layers[-1]\n else:\n input = tf.concat([layers[-1], layers[skip_layer]], axis=3)\n\n rectified = tf.nn.relu(input)\n # [batch, in_height, in_width, in_channels] => [batch, in_height*2, in_width*2, out_channels]\n output = gen_deconv(rectified, out_channels)\n output = batchnorm(output)\n\n if dropout > 0.0:\n output = tf.nn.dropout(output, keep_prob=1 - dropout)\n\n layers.append(output)\n\n # decoder_1: [batch, 128, 128, ngf * 2] => [batch, 256, 256, generator_outputs_channels]\n with tf.variable_scope(\"decoder_1\"):\n input = tf.concat([layers[-1], layers[0]], axis=3)\n rectified = tf.nn.relu(input)\n output = gen_deconv(rectified, generator_outputs_channels)\n output = tf.tanh(output)\n layers.append(output)\n\n return layers[-1]\ndef gen_conv(batch_input, out_channels):\n # [batch, in_height, in_width, in_channels] => [batch, out_height, out_width, out_channels]\n initializer = tf.random_normal_initializer(0, 0.02)\n return tf.layers.conv2d(batch_input, out_channels, kernel_size=4, strides=(2, 2), padding=\"same\", kernel_initializer=initializer)\n\n\ndef gen_deconv(batch_input, out_channels):\n # [batch, in_height, in_width, in_channels] => [batch, out_height, out_width, out_channels]\n initializer = tf.random_normal_initializer(0, 0.02)\n return tf.layers.conv2d_transpose(batch_input, out_channels, kernel_size=4, strides=(2, 2), padding=\"same\", kernel_initializer=initializer)\n\ndef lrelu(x, a):\n with tf.name_scope(\"lrelu\"):\n # adding these together creates the leak part and linear part\n # then cancels them out by subtracting/adding an absolute value term\n # leak: a*x/2 - a*abs(x)/2\n # linear: x/2 + abs(x)/2\n\n # this block looks like it has 2 inputs on the graph unless we do this\n x = tf.identity(x)\n return (0.5 * (1 + a)) * x + (0.5 * (1 - a)) * tf.abs(x)\n\n\ndef batchnorm(inputs):\n return tf.layers.batch_normalization(inputs, axis=3, epsilon=1e-5, momentum=0.1, training=True, gamma_initializer=tf.random_normal_initializer(1.0, 0.02))\ndef discrim_conv(batch_input, out_channels, stride):\n padded_input = tf.pad(batch_input, [[0, 0], [1, 1], [1, 1], [0, 0]], mode=\"CONSTANT\")\n return tf.layers.conv2d(padded_input, out_channels, kernel_size=4, strides=(stride, stride), padding=\"valid\", kernel_initializer=tf.random_normal_initializer(0, 0.02))\n\ndef preprocess(image):\n with tf.name_scope(\"preprocess\"):\n # [0, 1] => [-1, 1]\n return image * 2 - 1\ndef deprocess(image):\n with tf.name_scope(\"deprocess\"):\n # [-1, 1] => [0, 1]\n return (image + 1) / 2\n\ndef append_index(filesets, step=False):\n index_path = os.path.join(a[\"output_dir\"], \"index.html\")\n if os.path.exists(index_path):\n index = open(index_path, \"a\")\n else:\n index = open(index_path, \"w\")\n index.write(\"<html><body><table><tr>\")\n if step:\n index.write(\"<th>step</th>\")\n index.write(\"<th>name</th><th>input</th><th>output</th><th>target</th></tr>\")\n\n for fileset in filesets:\n index.write(\"<tr>\")\n\n if step:\n index.write(\"<td>%d</td>\" % fileset[\"step\"])\n index.write(\"<td>%s</td>\" % fileset[\"name\"])\n\n for kind in [\"inputs\", \"outputs\", \"targets\"]:\n index.write(\"<td><img src='images/%s'></td>\" % fileset[kind])\n\n index.write(\"</tr>\")\n return index_path\ndef save_images(fetches, step=None):\n image_dir = os.path.join(a[\"output_dir\"], \"images\")\n if not os.path.exists(image_dir):\n os.makedirs(image_dir)\n\n filesets = []\n for i, in_path in enumerate(fetches[\"paths\"]):\n name, _ = os.path.splitext(os.path.basename(in_path.decode(\"utf8\")))\n fileset = {\"name\": name, \"step\": step}\n for kind in [\"inputs\", \"outputs\", \"targets\"]:\n filename = name + \"-\" + kind + \".png\"\n if step is not None:\n filename = \"%08d-%s\" % (step, filename)\n fileset[kind] = filename\n out_path = os.path.join(image_dir, filename)\n contents = fetches[kind][i]\n with open(out_path, \"wb\") as f:\n f.write(contents)\n filesets.append(fileset)\n return filesets\ndef load_examples():\n if a[\"input_dir\"] is None or not os.path.exists(a[\"input_dir\"]):\n raise Exception(\"input_dir does not exist\")\n\n input_paths = glob.glob(os.path.join(a[\"input_dir\"], \"*.jpg\"))\n decode = tf.image.decode_jpeg\n if len(input_paths) == 0:\n input_paths = glob.glob(os.path.join(a[\"input_dir\"], \"*.png\"))\n decode = tf.image.decode_png\n\n if len(input_paths) == 0:\n raise Exception(\"input_dir contains no image files\")\n\n def get_name(path):\n name, _ = os.path.splitext(os.path.basename(path))\n return name\n\n # if the image names are numbers, sort by the value rather than asciibetically\n # having sorted inputs means that the outputs are sorted in test mode\n if all(get_name(path).isdigit() for path in input_paths):\n input_paths = sorted(input_paths, key=lambda path: int(get_name(path)))\n else:\n input_paths = sorted(input_paths)\n\n with tf.name_scope(\"load_images\"):\n path_queue = tf.train.string_input_producer(input_paths, shuffle=a[\"mode\"] == \"train\")\n reader = tf.WholeFileReader()\n paths, contents = reader.read(path_queue)\n raw_input = decode(contents)\n raw_input = tf.image.convert_image_dtype(raw_input, dtype=tf.float32)\n\n assertion = tf.assert_equal(tf.shape(raw_input)[2], 3, message=\"image does not have 3 channels\")\n with tf.control_dependencies([assertion]):\n raw_input = tf.identity(raw_input)\n\n raw_input.set_shape([None, None, 3])\n\n # break apart image pair and move to range [-1, 1]\n width = tf.shape(raw_input)[1] # [height, width, channels]\n a_images = preprocess(raw_input[:,:width//2,:])\n b_images = preprocess(raw_input[:,width//2:,:])\n\n if a[\"which_direction\"] == \"AtoB\":\n inputs, targets = [a_images, b_images]\n elif a[\"which_direction\"] == \"BtoA\":\n inputs, targets = [b_images, a_images]\n else:\n raise Exception(\"invalid direction\")\n\n # synchronize seed for image operations so that we do the same operations to both\n # input and output images\n seed = random.randint(0, 2**31 - 1)\n def transform(image):\n r = image\n if a[\"flip\"]:\n r = tf.image.random_flip_left_right(r, seed=seed)\n\n # area produces a nice downscaling, but does nearest neighbor for upscaling\n # assume we're going to be doing downscaling here\n r = tf.image.resize_images(r, [a[\"scale_size\"], a[\"scale_size\"]], method=tf.image.ResizeMethod.AREA)\n\n offset = tf.cast(tf.floor(tf.random_uniform([2], 0, a[\"scale_size\"] - CROP_SIZE + 1, seed=seed)), dtype=tf.int32)\n if a[\"scale_size\"] > CROP_SIZE:\n r = tf.image.crop_to_bounding_box(r, offset[0], offset[1], CROP_SIZE, CROP_SIZE)\n elif a[\"scale_size\"] < CROP_SIZE:\n raise Exception(\"scale size cannot be less than crop size\")\n return r\n\n with tf.name_scope(\"input_images\"):\n input_images = transform(inputs)\n\n with tf.name_scope(\"target_images\"):\n target_images = transform(targets)\n\n paths_batch, inputs_batch, targets_batch = tf.train.batch([paths, input_images, target_images], batch_size=a[\"batch_size\"])\n steps_per_epoch = int(math.ceil(len(input_paths) / a[\"batch_size\"]))\n\n return Examples(\n paths=paths_batch,\n inputs=inputs_batch,\n targets=targets_batch,\n count=len(input_paths),\n steps_per_epoch=steps_per_epoch,\n )\n\n\n##################################\n## MAIN\n##################################\na[\"seed\"] = random.randint(0, 2 ** 31 - 1)\n\ntf.set_random_seed(a[\"seed\"])\nnp.random.seed(a[\"seed\"])\nrandom.seed(a[\"seed\"])\n\nif not os.path.exists(a[\"output_dir\"]):\n os.makedirs(a[\"output_dir\"])\n\nif a[\"checkpoint\"] is None:\n raise Exception(\"checkpoint required for test mode\")\n\n# load some options from the checkpoint\noptions = {\"which_direction\", \"ngf\", \"ndf\", \"lab_colorization\"}\n# with open(os.path.join(a[\"checkpoint\"], \"options.json\")) as f:\n# for key, val in json.loads(f.read()).items():\n# if key in options:\n# print(\"loaded\", key, \"=\", val)\n# setattr(a, key, val)\n\n# disable these features in test mode\na[\"scale_size\"] = CROP_SIZE\na[\"flip\"] = False\n\n# output parameter setting\nfor k in a:\n print(k, \"=\", a[k])\n\n#with open(os.path.join(a[\"output_dir\"], \"options.json\"), \"w\") as f:\n# f.write(json.dumps(vars(a), sort_keys=True, indent=4))\n\nexamples = load_examples()\nprint(\"examples count = %d\" % examples.count)\n\n# inputs and targets are [batch_size, height, width, channels]\nmodel = create_model(examples.inputs, examples.targets)\n\ninputs = deprocess(examples.inputs)\ntargets = deprocess(examples.targets)\noutputs = deprocess(model.outputs)\n\n\ndef convert(image):\n if a[\"aspect_ratio\"] != 1.0:\n # upscale to correct aspect ratio\n size = [CROP_SIZE, int(round(CROP_SIZE * a[\"aspect_ratio\"]))]\n image = tf.image.resize_images(image, size=size, method=tf.image.ResizeMethod.BICUBIC)\n\n return tf.image.convert_image_dtype(image, dtype=tf.uint8, saturate=True)\n\n\n# reverse any processing on images so they can be written to disk or displayed to user\nwith tf.name_scope(\"convert_inputs\"):\n converted_inputs = convert(inputs)\n\nwith tf.name_scope(\"convert_targets\"):\n converted_targets = convert(targets)\n\nwith tf.name_scope(\"convert_outputs\"):\n converted_outputs = convert(outputs)\n\nwith tf.name_scope(\"encode_images\"):\n display_fetches = {\n \"paths\": examples.paths,\n \"inputs\": tf.map_fn(tf.image.encode_png, converted_inputs, dtype=tf.string, name=\"input_pngs\"),\n \"targets\": tf.map_fn(tf.image.encode_png, converted_targets, dtype=tf.string, name=\"target_pngs\"),\n \"outputs\": tf.map_fn(tf.image.encode_png, converted_outputs, dtype=tf.string, name=\"output_pngs\"),\n }\n\n# summaries\nwith tf.name_scope(\"inputs_summary\"):\n tf.summary.image(\"inputs\", converted_inputs)\n\nwith tf.name_scope(\"targets_summary\"):\n tf.summary.image(\"targets\", converted_targets)\n\nwith tf.name_scope(\"outputs_summary\"):\n tf.summary.image(\"outputs\", converted_outputs)\n\nwith tf.name_scope(\"predict_real_summary\"):\n tf.summary.image(\"predict_real\", tf.image.convert_image_dtype(model.predict_real, dtype=tf.uint8))\n\nwith tf.name_scope(\"predict_fake_summary\"):\n tf.summary.image(\"predict_fake\", tf.image.convert_image_dtype(model.predict_fake, dtype=tf.uint8))\n\ntf.summary.scalar(\"discriminator_loss\", model.discrim_loss)\ntf.summary.scalar(\"generator_loss_GAN\", model.gen_loss_GAN)\ntf.summary.scalar(\"generator_loss_L1\", model.gen_loss_L1)\n\nfor var in tf.trainable_variables():\n tf.summary.histogram(var.op.name + \"/values\", var)\n\nfor grad, var in model.discrim_grads_and_vars + model.gen_grads_and_vars:\n tf.summary.histogram(var.op.name + \"/gradients\", grad)\n\nwith tf.name_scope(\"parameter_count\"):\n parameter_count = tf.reduce_sum([tf.reduce_prod(tf.shape(v)) for v in tf.trainable_variables()])\n\nsaver = tf.train.Saver(max_to_keep=1)\n\nlogdir = a[\"output_dir\"] if (a[\"trace_freq\"] > 0 or a[\"summary_freq\"] > 0) else None\nsv = tf.train.Supervisor(logdir=logdir, save_summaries_secs=0, saver=None)\nwith sv.managed_session() as sess:\n print(\"parameter_count =\", sess.run(parameter_count))\n\n if a[\"checkpoint\"] is not None:\n print(\"loading model from checkpoint\")\n checkpoint = tf.train.latest_checkpoint(a[\"checkpoint\"])\n saver.restore(sess, checkpoint)\n\n max_steps = 2**32\n # if a[\"max_epochs\"] is not None:\n # max_steps = examples.steps_per_epoch * a[\"max_epochs\"]\n # if a[\"max_steps\"] is not None:\n # max_steps = a[\"max_steps\"]\n\n # testing\n # at most, process the test data once\n start = time.time()\n max_steps = min(examples.steps_per_epoch, max_steps)\n for step in range(max_steps):\n results = sess.run(display_fetches)\n filesets = save_images(results)\n for i, f in enumerate(filesets):\n print(\"evaluated image\", f[\"name\"])\n index_path = append_index(filesets)\n print(\"wrote index at\", index_path)\n print(\"rate\", (time.time() - start) / max_steps)\n\n\n####\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\n#%matpltlib\nsess = tf.Session()\nsaver = tf.train.import_meta_graph(\"trump_train/model-270000.meta\")\nsaver.restore(sess, tf.train.latest_checkpoint(\"./trump_train/\"))\nop = sess.graph.get_tensor_by_name(\"deprocess_2/add:0\")\nb = sess.graph.get_tensor_by_name(\"batch:1\")\nimport scipy.ndimage\nimport numpy as np\nim = scipy.ndimage.imread(\"script_imgs/3rd/frame0_b.png\")\nim2 = np.reshape(np.array([im,im,im]), (1,256,256,3))\nfeed = {b: im2}\nimport cv2\nimport cv\ncim = cv2.cvtColor(im, cv.CV_GRAY2RGB)\ncim2 = (cim.astype(np.float32)/255).astype(np.float32)\ncim3 = np.reshape(cim2 * 2 - 1, (1,256,256,3))\nop4 = sess.graph.get_tensor_by_name(\"convert_outputs/convert_image:0\")\nresult = sess.run(op4, feed)\nplt.imshow(np.reshape(result, (256,256,3)))\ncim4 = np.concatenate((cim3, cim3, cim3, cim3))\n\n# for multiple images\nresults = []\nfor i in range(4):\n im = np.reshape(cim4[i],(1,256,256,3))\n feed[b] = im\n r = sess.run(op4, feed)\n results.append(np.reshape(r, (256,256,3)))\n print(\"finished \", i)"
]
| [
[
"tensorflow.concat",
"tensorflow.control_dependencies",
"numpy.concatenate",
"tensorflow.train.ExponentialMovingAverage",
"tensorflow.tanh",
"tensorflow.map_fn",
"tensorflow.layers.conv2d_transpose",
"tensorflow.pad",
"tensorflow.train.AdamOptimizer",
"tensorflow.train.batch",
"tensorflow.group",
"tensorflow.summary.scalar",
"tensorflow.image.random_flip_left_right",
"numpy.reshape",
"tensorflow.summary.image",
"tensorflow.WholeFileReader",
"tensorflow.train.import_meta_graph",
"tensorflow.train.get_or_create_global_step",
"tensorflow.name_scope",
"tensorflow.Session",
"tensorflow.trainable_variables",
"tensorflow.train.Saver",
"tensorflow.random_normal_initializer",
"tensorflow.nn.dropout",
"tensorflow.layers.conv2d",
"tensorflow.shape",
"tensorflow.image.resize_images",
"tensorflow.identity",
"tensorflow.train.string_input_producer",
"tensorflow.set_random_seed",
"numpy.array",
"tensorflow.summary.histogram",
"tensorflow.nn.relu",
"tensorflow.train.latest_checkpoint",
"numpy.random.seed",
"tensorflow.image.crop_to_bounding_box",
"tensorflow.assign",
"tensorflow.sigmoid",
"tensorflow.train.Supervisor",
"tensorflow.image.convert_image_dtype",
"tensorflow.log",
"tensorflow.variable_scope",
"tensorflow.random_uniform",
"tensorflow.abs"
]
]
|
ysglh/tensorflow_for_- | [
"6c3c766dcabff3b5fa41dbfd491c9e8062a77b07"
]
| [
"tensorflow/contrib/autograph/impl/conversion.py"
]
| [
"# Copyright 2016 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\"\"\"Core conversion logic, serves as main point of access.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport imp\n\nimport gast\n\nfrom tensorflow.contrib.autograph import operators\nfrom tensorflow.contrib.autograph import utils\nfrom tensorflow.contrib.autograph.converters import asserts\nfrom tensorflow.contrib.autograph.converters import break_statements\nfrom tensorflow.contrib.autograph.converters import builtin_functions\nfrom tensorflow.contrib.autograph.converters import call_trees\nfrom tensorflow.contrib.autograph.converters import conditional_expressions\nfrom tensorflow.contrib.autograph.converters import continue_statements\nfrom tensorflow.contrib.autograph.converters import control_flow\nfrom tensorflow.contrib.autograph.converters import decorators\nfrom tensorflow.contrib.autograph.converters import directives\nfrom tensorflow.contrib.autograph.converters import error_handlers\nfrom tensorflow.contrib.autograph.converters import lists\nfrom tensorflow.contrib.autograph.converters import logical_expressions\nfrom tensorflow.contrib.autograph.converters import name_scopes\nfrom tensorflow.contrib.autograph.converters import return_statements\nfrom tensorflow.contrib.autograph.converters import side_effect_guards\nfrom tensorflow.contrib.autograph.converters import slices\nfrom tensorflow.contrib.autograph.core import config\nfrom tensorflow.contrib.autograph.core import converter\nfrom tensorflow.contrib.autograph.core import errors\nfrom tensorflow.contrib.autograph.pyct import ast_util\nfrom tensorflow.contrib.autograph.pyct import inspect_utils\nfrom tensorflow.contrib.autograph.pyct import origin_info\nfrom tensorflow.contrib.autograph.pyct import parser\nfrom tensorflow.contrib.autograph.pyct import qual_names\nfrom tensorflow.contrib.autograph.pyct import transformer\nfrom tensorflow.python.util import tf_inspect\n\n\n# TODO(mdan): Might we not need any renaming at all?\n\n\ndef is_whitelisted_for_graph(o):\n \"\"\"Check whether an entity is whitelisted for use in graph mode.\n\n Examples of whitelisted entities include all members of the tensorflow\n package.\n\n Args:\n o: A Python entity.\n Returns:\n Boolean\n \"\"\"\n m = tf_inspect.getmodule(o)\n for prefix, in config.DEFAULT_UNCOMPILED_MODULES:\n if m.__name__.startswith(prefix):\n return True\n return False\n\n\ndef entity_to_graph(o, program_ctx, arg_values, arg_types):\n \"\"\"Compile a Python entity into equivalent TensorFlow.\n\n The function will also recursively compile all the entities that `o`\n references, updating `dependency_cache`.\n\n This function is reentrant, and relies on dependency_cache to avoid\n generating duplicate code.\n\n Args:\n o: A Python entity.\n program_ctx: A ProgramContext object.\n arg_values: A dict containing value hints for symbols like function\n parameters.\n arg_types: A dict containing type hints for symbols like function\n parameters.\n\n Returns:\n A tuple (ast, new_name, namespace):\n * ast: An AST representing an entity with interface equivalent to `o`,\n but which when executed it creates TF a graph.\n * new_name: The symbol name under which the new entity can be found.\n * namespace: A dict mapping all symbols visible to the converted entity,\n keyed by their symbol name.\n\n Raises:\n ValueError: if the entity type is not supported.\n \"\"\"\n if tf_inspect.isclass(o):\n node, name, ns = class_to_graph(o, program_ctx)\n elif tf_inspect.isfunction(o):\n # TODO(mdan): This is not a reliable mechanism.\n # The most reliable way is to check the source code, the AST will contain\n # a Lambda node instead of a FunctionDef\n if o.__name__ == '<lambda>':\n raise NotImplementedError(\n 'lambda functions are not yet supported; declare the function'\n ' using def instead: %s' % o)\n else:\n node, name, ns = function_to_graph(o, program_ctx, arg_values, arg_types)\n elif tf_inspect.ismethod(o):\n node, name, ns = function_to_graph(o, program_ctx, arg_values, arg_types)\n else:\n raise ValueError(\n 'Entity \"%s\" has unsupported type \"%s\". Only functions and classes are '\n 'supported for now.' % (o, type(o)))\n\n program_ctx.add_to_cache(o, node)\n if program_ctx.recursive:\n while True:\n candidate = None\n for obj in program_ctx.name_map.keys():\n if obj not in program_ctx.dependency_cache:\n candidate = obj\n break\n if candidate is None:\n break\n if (hasattr(candidate, 'im_class') and\n getattr(candidate, 'im_class') not in program_ctx.partial_types):\n # Class members are converted with their objects, unless they're\n # only converted partially.\n continue\n entity_to_graph(candidate, program_ctx, {}, {})\n\n return node, name, ns\n\n\ndef class_to_graph(c, program_ctx):\n \"\"\"Specialization of `entity_to_graph` for classes.\"\"\"\n converted_members = {}\n method_filter = lambda m: tf_inspect.isfunction(m) or tf_inspect.ismethod(m)\n members = tf_inspect.getmembers(c, predicate=method_filter)\n if not members:\n raise ValueError('Cannot convert %s: it has no member methods.' % c)\n\n class_namespace = {}\n for _, m in members:\n # Only convert the members that are directly defined by the class.\n if inspect_utils.getdefiningclass(m, c) is not c:\n continue\n node, _, namespace = function_to_graph(\n m,\n program_ctx=program_ctx,\n arg_values={},\n arg_types={'self': (c.__name__, c)},\n owner_type=c)\n if class_namespace is None:\n class_namespace = namespace\n else:\n class_namespace.update(namespace)\n converted_members[m] = node\n namer = program_ctx.new_namer(class_namespace)\n class_name = namer.compiled_class_name(c.__name__, c)\n\n # TODO(mdan): This needs to be explained more thoroughly.\n # Process any base classes: if the sueprclass if of a whitelisted type, an\n # absolute import line is generated. Otherwise, it is marked for conversion\n # (as a side effect of the call to namer.compiled_class_name() followed by\n # program_ctx.update_name_map(namer)).\n output_nodes = []\n renames = {}\n bases = []\n for base in c.__bases__:\n if isinstance(object, base):\n bases.append('object')\n continue\n if is_whitelisted_for_graph(base):\n alias = namer.new_symbol(base.__name__, ())\n output_nodes.append(\n gast.ImportFrom(\n module=base.__module__,\n names=[gast.alias(name=base.__name__, asname=alias)],\n level=0))\n else:\n # This will trigger a conversion into a class with this name.\n alias = namer.compiled_class_name(base.__name__, base)\n bases.append(alias)\n renames[qual_names.QN(base.__name__)] = qual_names.QN(alias)\n program_ctx.update_name_map(namer)\n\n # Generate the definition of the converted class.\n output_nodes.append(\n gast.ClassDef(\n class_name,\n bases=bases,\n keywords=[],\n body=list(converted_members.values()),\n decorator_list=[]))\n node = gast.Module(output_nodes)\n\n # Make a final pass to replace references to the class or its base classes.\n # Most commonly, this occurs when making super().__init__() calls.\n # TODO(mdan): Making direct references to superclass' superclass will fail.\n node = qual_names.resolve(node)\n renames[qual_names.QN(c.__name__)] = qual_names.QN(class_name)\n node = ast_util.rename_symbols(node, renames)\n\n return node, class_name, class_namespace\n\n\ndef _add_reserved_symbol(namespace, name, entity):\n if name not in namespace:\n namespace[name] = entity\n elif namespace[name] != entity:\n raise ValueError('The name \"%s\" is reserved and may not be used.' % name)\n\n\nag_internal = None\n\n\ndef _add_self_references(namespace, autograph_module):\n \"\"\"Adds namespace references to the module that exposes the api itself.\"\"\"\n global ag_internal\n if ag_internal is None:\n # Craft a module that exposes parts of the external API as well as certain\n # internal modules.\n ag_internal = imp.new_module('autograph')\n ag_internal.converted_call = autograph_module.converted_call\n ag_internal.utils = utils\n ag_internal.rewrite_graph_construction_error = (\n errors.rewrite_graph_construction_error)\n # TODO(mdan): Add safeguards against name clashes.\n # We don't want to create a submodule because we want the operators to be\n # accessible as ag__.<operator>\n ag_internal.__dict__.update(operators.__dict__)\n\n _add_reserved_symbol(namespace, 'ag__', ag_internal)\n\n\ndef function_to_graph(f, program_ctx, arg_values, arg_types, owner_type=None):\n \"\"\"Specialization of `entity_to_graph` for callable functions.\"\"\"\n\n node, source = parser.parse_entity(f)\n node = node.body[0]\n origin_info.resolve(node, source, f)\n namespace = inspect_utils.getnamespace(f)\n _add_self_references(namespace, program_ctx.autograph_module)\n namer = program_ctx.new_namer(namespace)\n\n entity_info = transformer.EntityInfo(\n source_code=source,\n source_file='<fragment>',\n namespace=namespace,\n arg_values=arg_values,\n arg_types=arg_types,\n owner_type=owner_type)\n context = converter.EntityContext(namer, entity_info, program_ctx)\n node = node_to_graph(node, context)\n\n # TODO(mdan): This somewhat duplicates the call rename logic in call_treest.py\n new_name, did_rename = namer.compiled_function_name(f.__name__, f, owner_type)\n if not did_rename:\n new_name = f.__name__\n if node.name != f.__name__:\n raise NotImplementedError('Strange corner case. Send us offending code!')\n\n node.name = new_name\n program_ctx.update_name_map(namer)\n # TODO(mdan): Use this at compilation.\n\n return node, new_name, namespace\n\n\ndef node_to_graph(node, context):\n \"\"\"Convert Python code to equivalent TF graph mode code.\n\n Args:\n node: AST, the code to convert.\n context: converter.EntityContext\n\n Returns:\n A tuple (node, deps):\n * node: A Python ast node, representing the converted code.\n * deps: A set of strings, the fully qualified names of entity\n dependencies that this node has.\n \"\"\"\n # TODO(mdan): Insert list_comprehensions somewhere.\n\n node = converter.standard_analysis(node, context, is_initial=True)\n # Past this point, line numbers are no longer accurate so we ignore the\n # source.\n # TODO(mdan): Is it feasible to reconstruct intermediate source code?\n context.info.source_code = None\n\n node = converter.apply_(node, context, decorators)\n node = converter.apply_(node, context, directives)\n node = converter.apply_(node, context, break_statements)\n node = converter.apply_(node, context, asserts)\n # Note: sequencing continue canonicalization before for loop one avoids\n # dealing with the extra loop increment operation that the for\n # canonicalization creates.\n node = converter.apply_(node, context, continue_statements)\n context.info.namespace['len'] = len\n node = converter.apply_(node, context, return_statements)\n node = converter.apply_(node, context, lists)\n node = converter.apply_(node, context, slices)\n node = converter.apply_(node, context, builtin_functions)\n node = converter.apply_(node, context, call_trees)\n node = converter.apply_(node, context, control_flow)\n node = converter.apply_(node, context, conditional_expressions)\n node = converter.apply_(node, context, logical_expressions)\n node = converter.apply_(node, context, side_effect_guards)\n node = converter.apply_(node, context, name_scopes)\n node = converter.apply_(node, context, error_handlers)\n return node\n"
]
| [
[
"tensorflow.python.util.tf_inspect.isclass",
"tensorflow.python.util.tf_inspect.ismethod",
"tensorflow.contrib.autograph.pyct.inspect_utils.getnamespace",
"tensorflow.python.util.tf_inspect.getmodule",
"tensorflow.contrib.autograph.pyct.origin_info.resolve",
"tensorflow.contrib.autograph.core.converter.standard_analysis",
"tensorflow.contrib.autograph.pyct.parser.parse_entity",
"tensorflow.contrib.autograph.core.converter.apply_",
"tensorflow.python.util.tf_inspect.isfunction",
"tensorflow.python.util.tf_inspect.getmembers",
"tensorflow.contrib.autograph.pyct.qual_names.resolve",
"tensorflow.contrib.autograph.pyct.qual_names.QN",
"tensorflow.contrib.autograph.pyct.transformer.EntityInfo",
"tensorflow.contrib.autograph.core.converter.EntityContext",
"tensorflow.contrib.autograph.pyct.ast_util.rename_symbols",
"tensorflow.contrib.autograph.pyct.inspect_utils.getdefiningclass"
]
]
|
fabiomaia/msc | [
"43e3a8e17786c2c3246768f29be60d6c93f52527"
]
| [
"src/plot_vgg16.py"
]
| [
"import os\nimport re\nimport argparse\nimport csv\nimport json\nimport itertools\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport helpers\n\n\ndef truncate(f):\n return float(\"{:.2e}\".format(f))\n\n\ndef truncate_floats(stats):\n for stat in stats:\n for h in stat['hyperparameters']:\n if isinstance(stat['hyperparameters'][h], float):\n stat['hyperparameters'][h] = truncate(stat['hyperparameters'][h])\n stat['hyperparameters']['extract'] = int(stat['hyperparameters']['extract'])\n stat['hyperparameters']['freeze'] = int(stat['hyperparameters']['freeze'])\n stat['train_acc'][-1] = truncate(stat['train_acc'][-1])\n stat['val_acc'][-1] = truncate(stat['val_acc'][-1])\n stat['test_acc'] = truncate(stat['test_acc'])\n stat['auc'] = truncate(stat['auc'])\n stat['classification_report']['weighted avg']['precision'] = truncate(stat['classification_report']['weighted avg']['precision'])\n stat['classification_report']['weighted avg']['recall'] = truncate(stat['classification_report']['weighted avg']['recall'])\n stat['classification_report']['weighted avg']['f1-score'] = truncate(stat['classification_report']['weighted avg']['f1-score'])\n return stats\n\n\ndef tabulate(stats, target_file):\n assert len(stats) > 0\n\n \"\"\"\n \\begin{center}\n \\begin{tabular}{ |c|c|c| }\n \\hline\n cell1 & cell2 & cell3 \\\\\n cell4 & cell5 & cell6 \\\\\n cell7 & cell8 & cell9 \\\\\n \\hline\n \\end{tabular}\n \\end{center}\n \"\"\"\n\n # Build header\n latex = '\\\\begin{table}[ht]\\n'\n latex += '\\\\centering\\n'\n latex += '\\\\begin{tabular}{ '\n latex += '|c|c|c|c|c|c|c|c|c|c|'\n latex += ' }\\n'\n latex += '\\\\hline\\n'\n latex += '$e$ & $f$ & $\\lambda$ & $A_{train}$ & $A_{val}$ & $A_{test}$ & Precision & Recall & F1-Score \\\\\\\\\\n'\n latex += '\\\\hline\\n'\n\n # Build body\n for stat in stats:\n extract = stat['hyperparameters']['extract']\n freeze = stat['hyperparameters']['freeze']\n lambd = stat['hyperparameters']['lambda']\n train_acc = stat['train_acc'][-1]\n val_acc = stat['val_acc'][-1]\n test_acc = stat['test_acc']\n precision = stat['classification_report']['weighted avg']['precision']\n recall = stat['classification_report']['weighted avg']['recall']\n f1 = stat['classification_report']['weighted avg']['f1-score']\n\n latex += f\"{extract} & {freeze} & {lambd} & {train_acc} & {val_acc} & {test_acc} & {precision} & {recall} & {f1} \\\\\\\\\\n\"\n\n def _mean_std(stats):\n m = truncate(np.mean(stats))\n s = truncate(np.std(stats))\n return m, s\n\n mean_train_acc, std_train_acc = _mean_std([stat['train_acc'][-1] for stat in stats])\n mean_val_acc, std_val_acc = _mean_std([stat['val_acc'][-1] for stat in stats])\n mean_test_acc, std_test_acc = _mean_std([stat['test_acc'] for stat in stats])\n mean_precision, std_precision = _mean_std([stat['classification_report']['weighted avg']['precision'] for stat in stats])\n mean_recall, std_recall = _mean_std([stat['classification_report']['weighted avg']['recall'] for stat in stats])\n mean_f1, std_f1 = _mean_std([stat['classification_report']['weighted avg']['f1-score'] for stat in stats])\n\n latex += '\\\\hline\\n'\n latex += f\" & & & ${mean_train_acc}\\pm{std_train_acc}$ & ${mean_val_acc}\\pm{std_val_acc}$ & ${mean_test_acc}\\pm{std_test_acc}$ & ${mean_precision}\\pm{std_precision}$ & ${mean_recall}\\pm{std_recall}$ & ${mean_f1}\\pm{std_f1}$ \\\\\\\\\\n\"\n latex += '\\\\hline\\n'\n latex += '\\\\end{tabular}\\n'\n latex += '\\\\caption{Foobar}\\n'\n latex += '\\\\label{table:foobar}\\n'\n latex += '\\\\end{table}\\n'\n\n with open(target_file, 'w') as f:\n f.write(latex)\n\n\ndef plot_accuracy_vs_lambda(stats, target_file):\n fig, ax = plt.subplots(1, 1, constrained_layout=True)\n\n x = np.array([stat['hyperparameters']['lambda'] for stat in stats])\n y1 = np.array([stat['train_acc'][-1] for stat in stats])\n y2 = np.array([stat['val_acc'][-1] for stat in stats])\n y3 = np.array([stat['test_acc'] for stat in stats])\n x, y1, y2, y3 = zip(*sorted(zip(x, y1, y2, y3)))\n x = np.array(x)\n y1 = np.array(y1)\n y2 = np.array(y2)\n y3 = np.array(y3)\n\n ax.plot(x, y1, '.b-', label=\"$A_{train}$\")\n ax.plot(x, y2, '.r-', label=\"$A_{val}$\")\n #ax.plot(x, y3, '.g-', label=\"$A_{test}$\")\n ax.legend()\n ax.grid(True)\n\n ax.set_xscale(\"log\")\n ax.set_yscale(\"linear\")\n ax.set_xlabel(\"$\\lambda$\")\n ax.set_ylabel(\"Accuracy\")\n\n plt.savefig(target_file)\n plt.close()\n\n\ndef plot_training(stat, target_file):\n fig, ax = plt.subplots(1, 2, constrained_layout=True, figsize=(11, 4))\n\n x = np.array(list(range(1, len(stat['train_acc']))))\n y1 = np.array(stat['train_acc'])\n y2 = np.array(stat['val_acc'])\n y3 = np.array(stat['train_loss'])\n y4 = np.array(stat['val_loss'])\n x, y1, y2, y3, y4 = zip(*sorted(zip(x, y1, y2, y3, y4)))\n x = np.array(x)\n y1 = np.array(y1)\n y2 = np.array(y2)\n y3 = np.array(y3)\n y4 = np.array(y4)\n\n ax[0].plot(x, y1, '.b-', label=\"$A_{train}$\")\n ax[0].plot(x, y2, '.r-', label=\"$A_{val}$\")\n ax[0].legend()\n ax[0].grid(True)\n ax[0].set_xscale(\"linear\")\n ax[0].set_yscale(\"linear\")\n ax[0].set_xlabel(\"Epoch\")\n ax[0].set_ylabel(\"Accuracy\")\n\n ax[1].plot(x, y3, '.b-', label=\"$J_{train}$\")\n ax[1].plot(x, y4, '.r-', label=\"$J_{val}$\")\n ax[1].legend()\n ax[1].grid(True)\n ax[1].set_xscale(\"linear\")\n ax[1].set_yscale(\"linear\")\n ax[1].set_xlabel(\"Epoch\")\n ax[1].set_ylabel(\"Cost\")\n\n plt.savefig(target_file)\n plt.close()\n\n\ndef plot_confusion_matrix(stat, target_file):\n cm = np.array(stat['confusion_matrix'])\n\n plt.figure()\n plt.imshow(cm, interpolation='nearest', cmap=plt.cm.Blues)\n plt.colorbar()\n\n classes = ['Non-melanoma', 'Melanoma']\n tick_marks = np.arange(len(classes))\n\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = 'd'\n thresh = cm.max() / 2.\n\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n plt.savefig(target_file)\n plt.close()\n\n\ndef plot_accuracy_vs_freeze(stats, target_file):\n lambdas = sorted(list(set([stat['hyperparameters']['lambda'] for stat in stats])))\n\n rows = 2\n cols = int(len(lambdas)/rows)\n fig, axs = plt.subplots(rows, cols, constrained_layout=True, figsize=(10, 5))\n\n for i in range(rows):\n for j in range(cols):\n idx = i*cols+j\n l2 = lambdas[idx]\n stats_filtered = list(filter(lambda s: s['hyperparameters']['lambda'] == l2, stats))\n\n x = np.array([stat['hyperparameters']['freeze'] for stat in stats_filtered])\n y2 = np.array([stat['test_acc'] for stat in stats_filtered])\n x, y2 = zip(*sorted(zip(x, y2)))\n x = np.array(x)\n y2 = np.array(y2)\n\n ax = axs[i,j]\n ax.set_title(f'$\\lambda = {l2}$')\n ax.set_xscale(\"linear\")\n ax.set_yscale(\"linear\")\n ax.set_xlabel('$f$')\n ax.set_ylabel('$Accuracy$')\n ax.set_xticks([0,3,6,10,14,18])\n ax.plot(x, y2, '.g-', label=\"$A_{test}$\")\n\n plt.savefig(target_file)\n plt.close()\n\n\ndef main(experiments):\n # Read stats\n stats = []\n for d in os.listdir(experiments):\n d = os.path.join(experiments, d)\n if os.path.isdir(d):\n with open(os.path.join(d, 'stats.json')) as f: stats.append(json.loads(f.read()))\n stats = truncate_floats(stats)\n\n # Individual plots\n for stat in stats:\n plot_training(stat, os.path.join(experiments, stat['id'], 'training.png'))\n plot_confusion_matrix(stat, os.path.join(experiments, stat['id'], 'confusion_matrix.png'))\n\n # All results grouped and sorted by (extract,freeze,lambda)\n #stats_all = sorted(stats, key=lambda x: (x['hyperparameters']['extract'], x['hyperparameters']['freeze'], x['hyperparameters']['lambda']), reverse=True)\n stats_all = sorted(stats, key=lambda x: x['hyperparameters']['mfraction'], reverse=True)\n tabulate(stats_all, os.path.join(experiments, 'table_all.tex'))\n\n # Total feature extraction with no fine tuning\n stats_total = list(filter(lambda x: x['hyperparameters']['extract'] == x['hyperparameters']['freeze'] == 18, stats))\n tabulate(stats_total, os.path.join(experiments, 'table_total.tex'))\n plot_accuracy_vs_lambda(stats_total, os.path.join(experiments, 'lambda_total.png'))\n\n # Total feature extraction with fine tuning overall study\n stats_finetuning = list(filter(lambda x: x['hyperparameters']['extract'] == 18 and x['hyperparameters']['freeze'] < 18, stats))\n plot_accuracy_vs_freeze(stats_finetuning, os.path.join(experiments, 'freeze_finetuning.png'))\n # Total feature extraction with fine tuning 14\n stats_finetuning14 = list(filter(lambda x: x['hyperparameters']['extract'] == 18 and x['hyperparameters']['freeze'] == 14, stats))\n tabulate(stats_finetuning14, os.path.join(experiments, 'table_finetuning_14.tex'))\n plot_accuracy_vs_lambda(stats_finetuning14, os.path.join(experiments, 'lambda_finetuning_14.png'))\n # Total feature extraction with fine tuning 10\n stats_finetuning10 = list(filter(lambda x: x['hyperparameters']['extract'] == 18 and x['hyperparameters']['freeze'] == 10, stats))\n tabulate(stats_finetuning10, os.path.join(experiments, 'table_finetuning_10.tex'))\n plot_accuracy_vs_lambda(stats_finetuning10, os.path.join(experiments, 'lambda_finetuning_10.png'))\n # Total feature extraction with fine tuning 6\n stats_finetuning6 = list(filter(lambda x: x['hyperparameters']['extract'] == 18 and x['hyperparameters']['freeze'] == 6, stats))\n tabulate(stats_finetuning6, os.path.join(experiments, 'table_finetuning_6.tex'))\n plot_accuracy_vs_lambda(stats_finetuning6, os.path.join(experiments, 'lambda_finetuning_6.png'))\n # Total feature extraction with fine tuning 3\n stats_finetuning3 = list(filter(lambda x: x['hyperparameters']['extract'] == 18 and x['hyperparameters']['freeze'] == 3, stats))\n tabulate(stats_finetuning3, os.path.join(experiments, 'table_finetuning_3.tex'))\n plot_accuracy_vs_lambda(stats_finetuning3, os.path.join(experiments, 'lambda_finetuning_3.png'))\n # Total feature extraction with fine tuning 0\n stats_finetuning0 = list(filter(lambda x: x['hyperparameters']['extract'] == 18 and x['hyperparameters']['freeze'] == 0, stats))\n tabulate(stats_finetuning0, os.path.join(experiments, 'table_finetuning_0.tex'))\n plot_accuracy_vs_lambda(stats_finetuning0, os.path.join(experiments, 'lambda_finetuning_0.png'))\n\n # Partial feature extraction\n stats_partial = list(filter(lambda x: x['hyperparameters']['extract'] < 18, stats))\n tabulate(stats_partial, os.path.join(experiments, 'table_partial.tex'))\n plot_accuracy_vs_lambda(stats_partial, os.path.join(experiments, 'lambda_partial.png'))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--experiments', type=helpers.is_dir, required=True)\n args = parser.parse_args()\n main(args.experiments)\n"
]
| [
[
"matplotlib.pyplot.imshow",
"matplotlib.pyplot.yticks",
"matplotlib.pyplot.tight_layout",
"matplotlib.pyplot.subplots",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.colorbar",
"matplotlib.pyplot.ylabel",
"numpy.std",
"numpy.mean",
"matplotlib.pyplot.close",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.xticks",
"numpy.array",
"matplotlib.pyplot.figure"
]
]
|
CaFeCoKe/Scream_Detection | [
"3dcaba5c14c225221220aae33c09aac0b846873c"
]
| [
"demo.py"
]
| [
"import sys\nimport numpy as np\n\nimport pyaudio\n\nimport pyqtgraph as pg\nfrom PyQt5 import QtCore, uic\nfrom PyQt5.QtGui import *\nfrom PyQt5.QtWidgets import *\n\nimport librosa\n\nimport torch\nfrom torch import nn\nimport torch.nn.functional as F\n\nSAMPLING_RATE = 22050 # ์์ฑ๋ฐ์ดํฐ์ ์ํ๋ง ๋ ์ดํธ\nCHUNK_SIZE = 22050 # ์์ฑ๋ฐ์ดํฐ๋ฅผ ๋ถ๋ฌ์ฌ ๋ ํ๋ฒ์ 22050๊ฐ์ ์ ์๋ฅผ ๋ถ๋ฌ์ด\nform_class = uic.loadUiType(\"22.ui\")[0]\n\n\ndef feature_engineering_mel_spectrum(signal, sampling_rate, n_mels):\n cur_frame_temp = signal\n\n # Mel Spectrograme ์ถ์ถ\n mel_spectrum_temp = librosa.feature.melspectrogram(\n y=cur_frame_temp,\n sr=sampling_rate,\n n_mels=n_mels,\n n_fft=2048,\n hop_length=512,\n )\n # power -> dB๋ก ๋ณํ\n mel_spectrum_temp = librosa.core.power_to_db(mel_spectrum_temp)\n feature_vector = mel_spectrum_temp\n feature_vector = feature_vector[np.newaxis, :, :, np.newaxis]\n return feature_vector\n\n\nclass MicrophoneRecorder():\n def __init__(self, signal):\n self.signal = signal\n self.p = pyaudio.PyAudio() # Pyaudio ์ธ์คํด์คํ\n # ์์ฑ ๋ฐ์ดํฐ ์คํธ๋ฆผ ์ด๊ธฐ\n self.stream = self.p.open(\n format=pyaudio.paFloat32, # ๋นํธ ๊น์ด = 32bit float\n channels=1,\n rate=SAMPLING_RATE,\n input=True,\n frames_per_buffer=CHUNK_SIZE\n )\n\n def read(self):\n data = self.stream.read(CHUNK_SIZE, False) # ์์ฑ ๋ฐ์ดํฐ๋ฅผ ๋ฌธ์์ด๋ก ๋ฐํ\n y = np.fromstring(data, 'float32') # ๋ฌธ์์ด -> 32bit float ๋ํ์ด ๋ฐฐ์ด\n self.signal.emit(y) # GUI๋ก ๊ฐ ์ ๋ฌ\n\n # ์คํธ๋ฆผ ์ข
๋ฃ\n def close(self):\n print('๋ฉ์ถค')\n self.stream.stop_stream()\n self.stream.close()\n self.p.terminate()\n\n\nclass MyWindow(QMainWindow, form_class):\n read_collected = QtCore.pyqtSignal(np.ndarray) # emit์ผ๋ก GUI๋ก ์ ๋ฌ ๋ ๊ฐ๋ค์ ๋งค๊ฐ๋ณ์ ๋ณ์ํ์ ๊ธฐ๋ก\n\n def __init__(self, model):\n super(MyWindow, self).__init__()\n self.setupUi(self)\n self.read_collected.connect(self.update) # ์๊ทธ๋ ๋ฐ ์ฌ๋กฏ ์ค์ \n\n self.model = model\n\n # Bargraph\n pg.setConfigOptions(background='w', foreground='k') # key-value ํํ๋ก ์ฌ๋ฌ๊ฐ ์ธ์ ์ฌ์ฉ ๊ฐ๋ฅ.\n\n self.pw1 = pg.PlotWidget(title=\"BarGraph\")\n self.pw1.showGrid(x=True, y=True)\n\n self.graph_box.addWidget(self.pw1) # pw1์ ์์ ฏ์ผ๋ก ๋ฑ๋ก\n self.pw1.setGeometry(4, 1, 10, 5) # x, y, width, height\n\n ticks = [list(zip(range(2), ('Environmental sound', 'Scream sound')))]\n xax = self.pw1.getAxis('bottom') # bottom์ด๋ผ๋ AxisItem ๋ฐํ\n xax.setTicks(ticks) # ํ์ํ ๋๊ธ์ ๋ช
์์ ์ผ๋ก ๊ฒฐ์ \n self.show()\n\n def update(self, chunk):\n x = np.arange(2)\n\n # Mel_spcectrogram์ Tensorํ\n feature_vector = feature_engineering_mel_spectrum(chunk, SAMPLING_RATE, 64)\n feature_vector = torch.tensor(feature_vector).float()\n feature_vector = feature_vector.squeeze(3).unsqueeze(1)\n \n # ๋ชจ๋ธ์ Tensor ์
๋ ฅ\n y_softmax = float(\n torch.sigmoid(self.model(feature_vector)).detach().numpy()\n )\n\n if y_softmax > 0.5:\n pixmap = QPixmap(\"img/scream.png\")\n self.label_5.setPixmap(QPixmap(pixmap))\n else:\n pixmap = QPixmap(\"img/normal.png\")\n self.label_5.setPixmap(QPixmap(pixmap))\n\n self.pw1.clear()\n barchart = pg.BarGraphItem(\n x=x, height=[1 - y_softmax, y_softmax], width=1, brush=(159, 191, 229)\n )\n self.pw1.addItem(barchart)\n\n\nclass CNN_model(nn.Module):\n def __init__(self):\n super(CNN_model, self).__init__()\n\n # Convolution Layer\n self.conv1 = nn.Conv2d(1, 32, (64, 1))\n self.conv2 = nn.Conv2d(32, 64, (1, 9), stride=4)\n\n # Nomalization Layer\n self.batch1 = nn.BatchNorm2d(32)\n self.batch2 = nn.BatchNorm2d(64)\n\n # fully connected layer\n self.fc1 = nn.Linear(64*1*9, 1)\n\n # ํ์ฑํ ํจ์ ReLU\n self.relu = nn.ReLU()\n\n def forward(self, x):\n\n # Conv -> Nomalization -> ReLU -> Dropout\n x = self.conv1(x)\n x = self.batch1(x)\n x = self.relu(x)\n x = F.dropout2d(x, p=0.3, training=self.training)\n\n # Conv -> Nomalization -> ReLU -> Dropout\n x = self.conv2(x)\n x = self.batch2(x)\n x = self.relu(x)\n x = F.dropout2d(x, p=0.3, training=self.training)\n\n # Flatten -> Fully-connected\n x = x.view(-1, 64*1*9)\n x = self.fc1(x)\n\n return x\n\n\nmodel_dir = './test.pth'\n\nmodel = CNN_model()\nmodel.load_state_dict(torch.load(model_dir, map_location='cpu'))\n\napp = QApplication(sys.argv)\nmyWindow = MyWindow(model=model)\nmic = MicrophoneRecorder(myWindow.read_collected)\n\n# 1์ด๋ง๋ค ๋ง์ดํฌ ์
๋ ฅ ์คํ\ninterval = SAMPLING_RATE / CHUNK_SIZE\nt = QtCore.QTimer()\nt.setInterval(interval)\nt.timeout.connect(mic.read)\nt.start()\n\nmyWindow.show()\nsys.exit(app.exec_())"
]
| [
[
"torch.nn.functional.dropout2d",
"torch.load",
"numpy.arange",
"torch.nn.Conv2d",
"torch.tensor",
"torch.nn.Linear",
"numpy.fromstring",
"torch.nn.BatchNorm2d",
"torch.nn.ReLU"
]
]
|
boat-ocean/open_spiel | [
"38941dee3beb52ffdb134b66f420a758634d9a20"
]
| [
"open_spiel/python/algorithms/rcfr_test.py"
]
| [
"# Copyright 2019 DeepMind Technologies Ltd. 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 itertools\n\nfrom absl.testing import absltest\nfrom absl.testing import parameterized\n\nimport numpy as np\n# Note: this import needs to come before Tensorflow to fix a malloc error.\nimport pyspiel # pylint: disable=g-bad-import-order\nimport tensorflow.compat.v1 as tf\n\nfrom open_spiel.python.algorithms import rcfr\n\n# Temporarily disable TF2 behavior while the code is not updated.\ntf.disable_v2_behavior()\n\ntf.enable_eager_execution()\n\n_GAME = pyspiel.load_game('kuhn_poker')\n_BOOLEANS = [False, True]\n\n\ndef _new_model():\n return rcfr.DeepRcfrModel(\n _GAME,\n num_hidden_layers=1,\n num_hidden_units=13,\n num_hidden_factors=1,\n use_skip_connections=True)\n\n\nclass RcfrTest(parameterized.TestCase, tf.test.TestCase):\n\n def setUp(self):\n super(RcfrTest, self).setUp()\n tf.random.set_random_seed(42)\n\n def test_with_one_hot_action_features_single_state_vector(self):\n information_state_features = [1., 2., 3.]\n features = rcfr.with_one_hot_action_features(\n information_state_features,\n legal_actions=[0, 1],\n num_distinct_actions=3)\n self.assertAllEqual([\n [1., 2., 3., 1., 0., 0.],\n [1., 2., 3., 0., 1., 0.],\n ], features)\n\n features = rcfr.with_one_hot_action_features(\n information_state_features,\n legal_actions=[1, 2],\n num_distinct_actions=3)\n self.assertAllEqual([\n [1., 2., 3., 0., 1., 0.],\n [1., 2., 3., 0., 0., 1.],\n ], features)\n\n def test_with_one_hot_action_features_batch(self):\n info_state_features = [[1., 2., 3.], [4., 5., 6.]]\n features = rcfr.with_one_hot_action_features(\n info_state_features, legal_actions=[0, 1], num_distinct_actions=3)\n\n self.assertAllEqual([\n [1., 2., 3., 1., 0., 0.],\n [4., 5., 6., 1., 0., 0.],\n [1., 2., 3., 0., 1., 0.],\n [4., 5., 6., 0., 1., 0.],\n ], features)\n\n features = rcfr.with_one_hot_action_features(\n info_state_features, legal_actions=[1, 2], num_distinct_actions=3)\n\n self.assertAllEqual([\n [1., 2., 3., 0., 1., 0.],\n [4., 5., 6., 0., 1., 0.],\n [1., 2., 3., 0., 0., 1.],\n [4., 5., 6., 0., 0., 1.],\n ], features)\n\n def test_with_one_hot_action_features_error(self):\n info_state_features = tf.ones([1, 1, 1])\n\n with self.assertRaises(ValueError):\n rcfr.with_one_hot_action_features(\n info_state_features, legal_actions=[0, 1], num_distinct_actions=3)\n\n def test_sequence_features(self):\n state = _GAME.new_initial_state()\n while state.is_chance_node():\n state.apply_action(state.legal_actions()[0])\n assert len(state.legal_actions()) == 2\n features = rcfr.sequence_features(state, 3)\n\n x = state.information_state_tensor()\n self.assertAllEqual([x + [1, 0, 0], x + [0, 1, 0]], features)\n\n def test_num_features(self):\n assert rcfr.num_features(_GAME) == 13\n\n def test_root_state_wrapper_num_sequences(self):\n root_state_wrapper = rcfr.RootStateWrapper(_GAME.new_initial_state())\n assert root_state_wrapper.num_player_sequences[0] == 12\n assert root_state_wrapper.num_player_sequences[1] == 12\n\n def test_root_state_wrapper_sequence_indices(self):\n root_state_wrapper = rcfr.RootStateWrapper(_GAME.new_initial_state())\n self.assertAllEqual(\n {\n # Info state string -> initial sequence index map for player 1.\n '0': 0,\n '0pb': 2,\n '1': 4,\n '1pb': 6,\n '2': 8,\n '2pb': 10,\n # Info state string -> initial sequence index map for player 2.\n '1p': 0,\n '1b': 2,\n '2p': 4,\n '2b': 6,\n '0p': 8,\n '0b': 10,\n },\n root_state_wrapper.info_state_to_sequence_idx)\n\n def test_root_state_wrapper_sequence_features(self):\n root_state_wrapper = rcfr.RootStateWrapper(_GAME.new_initial_state())\n\n p1_info_state_features = [\n [1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.],\n [1., 0., 1., 0., 0., 1., 0., 0., 1., 0., 0.],\n [1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0.],\n [1., 0., 0., 1., 0., 1., 0., 0., 1., 0., 0.],\n [1., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0.],\n [1., 0., 0., 0., 1., 1., 0., 0., 1., 0., 0.],\n ]\n p2_info_state_features = [\n [0., 1., 0., 1., 0., 1., 0., 0., 0., 0., 0.],\n [0., 1., 0., 1., 0., 0., 1., 0., 0., 0., 0.],\n [0., 1., 0., 0., 1., 1., 0., 0., 0., 0., 0.],\n [0., 1., 0., 0., 1., 0., 1., 0., 0., 0., 0.],\n [0., 1., 1., 0., 0., 1., 0., 0., 0., 0., 0.],\n [0., 1., 1., 0., 0., 0., 1., 0., 0., 0., 0.],\n ]\n action_features = [[1., 0.], [0., 1.]]\n expected_p1_sequence_features = [\n p1_info_state_features[0] + action_features[0],\n p1_info_state_features[0] + action_features[1],\n p1_info_state_features[1] + action_features[0],\n p1_info_state_features[1] + action_features[1],\n p1_info_state_features[2] + action_features[0],\n p1_info_state_features[2] + action_features[1],\n p1_info_state_features[3] + action_features[0],\n p1_info_state_features[3] + action_features[1],\n p1_info_state_features[4] + action_features[0],\n p1_info_state_features[4] + action_features[1],\n p1_info_state_features[5] + action_features[0],\n p1_info_state_features[5] + action_features[1],\n ]\n expected_p2_sequence_features = [\n p2_info_state_features[0] + action_features[0],\n p2_info_state_features[0] + action_features[1],\n p2_info_state_features[1] + action_features[0],\n p2_info_state_features[1] + action_features[1],\n p2_info_state_features[2] + action_features[0],\n p2_info_state_features[2] + action_features[1],\n p2_info_state_features[3] + action_features[0],\n p2_info_state_features[3] + action_features[1],\n p2_info_state_features[4] + action_features[0],\n p2_info_state_features[4] + action_features[1],\n p2_info_state_features[5] + action_features[0],\n p2_info_state_features[5] + action_features[1],\n ]\n expected_sequence_features = [\n expected_p1_sequence_features, expected_p2_sequence_features\n ]\n\n self.assertAllEqual(expected_sequence_features,\n root_state_wrapper.sequence_features)\n\n def test_root_state_wrapper_sequence_terminal_values(self):\n root_state_wrapper = rcfr.RootStateWrapper(_GAME.new_initial_state())\n\n expected_terminal_values = {}\n no_call_histories_p1_win = [\n '2, 0, 0, 0', '2, 0, 1, 0', '0, 1, 1, 0', '1, 2, 1, 0', '1, 0, 1, 0',\n '1, 0, 0, 0', '2, 1, 1, 0', '2, 1, 0, 0', '0, 2, 1, 0'\n ]\n for h in no_call_histories_p1_win:\n expected_terminal_values[h] = [1., -1.]\n\n no_call_histories_p2_win = [\n '0, 2, 0, 1, 0', '0, 1, 0, 0', '0, 1, 0, 1, 0', '0, 2, 0, 0',\n '1, 2, 0, 0', '2, 0, 0, 1, 0', '1, 2, 0, 1, 0', '2, 1, 0, 1, 0',\n '1, 0, 0, 1, 0'\n ]\n for h in no_call_histories_p2_win:\n expected_terminal_values[h] = [-1., 1.]\n\n call_histories_p1_win = [\n '1, 0, 1, 1', '2, 1, 1, 1', '2, 1, 0, 1, 1', '2, 0, 0, 1, 1',\n '1, 0, 0, 1, 1', '2, 0, 1, 1'\n ]\n for h in call_histories_p1_win:\n expected_terminal_values[h] = [2., -2.]\n\n call_histories_p2_win = [\n '0, 2, 0, 1, 1', '0, 1, 0, 1, 1', '0, 1, 1, 1', '1, 2, 1, 1',\n '1, 2, 0, 1, 1', '0, 2, 1, 1'\n ]\n for h in call_histories_p2_win:\n expected_terminal_values[h] = [-2., 2.]\n\n self.assertAllEqual(\n expected_terminal_values,\n {k: v.tolist() for k, v in root_state_wrapper.terminal_values.items()})\n\n def test_normalized_by_sum(self):\n self.assertAllClose(\n rcfr.normalized_by_sum([1., 2., 3., 4.]), [0.1, 0.2, 0.3, 0.4])\n\n def test_counterfactual_regrets_and_reach_weights_value_error(self):\n root = rcfr.RootStateWrapper(_GAME.new_initial_state())\n\n # Initialize arbitrary weights to generate an arbitrary profile.\n sequence_weights1_with_a_missing_sequence = [\n 0.4967141530112327,\n 0.0,\n 0.6476885381006925,\n 1.5230298564080254,\n 0.0,\n 0.0,\n 1.5792128155073915,\n 0.7674347291529088,\n 0.0,\n 0.5425600435859647,\n 0.0,\n # 0.0,\n ]\n # Ensure this player's policy is fully mixed so that each of player 1's\n # information states are reached.\n sequence_weights2 = [\n 0.24196227156603412,\n 0.1,\n 0.1,\n 0.1,\n 0.1,\n 0.3142473325952739,\n 0.1,\n 0.1,\n 1.465648768921554,\n 0.1,\n 0.06752820468792384,\n 0.1,\n ]\n\n with self.assertRaises(ValueError):\n root.counterfactual_regrets_and_reach_weights(\n 0, 1, sequence_weights1_with_a_missing_sequence, sequence_weights2)\n\n def test_counterfactual_regrets_and_reach_weights(self):\n root = rcfr.RootStateWrapper(_GAME.new_initial_state())\n\n # Initialize arbitrary weights to generate an arbitrary profile.\n sequence_weights1 = [\n 0.4967141530112327,\n 0.0,\n 0.6476885381006925,\n 1.5230298564080254,\n 0.0,\n 0.0,\n 1.5792128155073915,\n 0.7674347291529088,\n 0.0,\n 0.5425600435859647,\n 0.0,\n 0.0,\n ]\n sequence_weights2 = [\n 0.24196227156603412,\n 0.0,\n 0.0,\n 0.0,\n 0.0,\n 0.3142473325952739,\n 0.0,\n 0.0,\n 1.465648768921554,\n 0.0,\n 0.06752820468792384,\n 0.0,\n ]\n\n # These expected regrets and sequence weights were computed for the given\n # sequence weights.\n expected_regrets_given_sequence_weights = [\n 0.,\n 0.283604,\n 0.116937,\n -0.049729,\n -0.06892,\n 0.06892,\n 0.054506,\n -0.112161,\n -0.083333,\n 0.,\n 0.,\n 0.,\n ]\n expected_reach_weights_given_sequence_weights = [\n 2.,\n 0.,\n 1.,\n 1.,\n 0.,\n 2.,\n 1.,\n 1.,\n 2.,\n 0.,\n 2.,\n 0.,\n ]\n\n regrets, weights = root.counterfactual_regrets_and_reach_weights(\n 0, 1, sequence_weights1, sequence_weights2)\n\n self.assertAllClose(regrets, expected_regrets_given_sequence_weights)\n self.assertAllClose(weights, expected_reach_weights_given_sequence_weights)\n\n def test_all_states(self):\n states = rcfr.all_states(\n _GAME.new_initial_state(),\n depth_limit=-1,\n include_terminals=False,\n include_chance_states=False)\n self.assertLen(list(states), 24)\n\n states = rcfr.all_states(\n _GAME.new_initial_state(),\n depth_limit=-1,\n include_terminals=True,\n include_chance_states=False)\n self.assertLen(list(states), 54)\n\n states = rcfr.all_states(\n _GAME.new_initial_state(),\n depth_limit=-1,\n include_terminals=False,\n include_chance_states=True)\n self.assertLen(list(states), 28)\n\n states = rcfr.all_states(\n _GAME.new_initial_state(),\n depth_limit=-1,\n include_terminals=True,\n include_chance_states=True)\n self.assertLen(list(states), 58)\n\n def test_sequence_weights_to_tabular_profile(self):\n root = rcfr.RootStateWrapper(_GAME.new_initial_state())\n\n def policy_fn(state):\n \"\"\"Generates a policy profile by treating sequence indices as weights.\"\"\"\n info_state = state.information_state_string()\n sequence_offset = root.info_state_to_sequence_idx[info_state]\n num_actions = len(state.legal_actions())\n return rcfr.normalized_by_sum(\n list(range(sequence_offset, sequence_offset + num_actions)))\n\n profile = rcfr.sequence_weights_to_tabular_profile(root.root, policy_fn)\n\n expected_profile = {\n # Player 1\n '0': [(0, 0.), (1, 1.)], # Sequences 0 and 1 (sums to 1)\n '0pb': [(0, 0.4), (1, 0.6)], # Sequences 2 and 3 (sums to 5)\n # Sequences 4 and 5 (sums to 9)\n '1': [(0, 0.44444444444444442), (1, 0.55555555555555558)],\n # Sequences 6 and 7 (sums to 13)\n '1pb': [(0, 0.46153846153846156), (1, 0.53846153846153844)],\n # Sequences 8 and 9 (sums to 17)\n '2': [(0, 0.47058823529411764), (1, 0.52941176470588236)],\n # Sequences 10 and 11 (sums to 21)\n '2pb': [(0, 0.47619047619047616), (1, 0.52380952380952384)],\n\n # Player 2\n '1p': [(0, 0.), (1, 1.)], # Sequences 0 and 1 (sums to 1)\n '1b': [(0, 0.4), (1, 0.6)], # Sequences 2 and 3 (sums to 5)\n # Sequences 4 and 5 (sums to 9)\n '2p': [(0, 0.44444444444444442), (1, 0.55555555555555558)],\n # Sequences 6 and 7 (sums to 13)\n '2b': [(0, 0.46153846153846156), (1, 0.53846153846153844)],\n # Sequences 8 and 9 (sums to 17)\n '0p': [(0, 0.47058823529411764), (1, 0.52941176470588236)],\n # Sequences 10 and 11 (sums to 21)\n '0b': [(0, 0.47619047619047616), (1, 0.52380952380952384)],\n }\n self.assertAllClose(profile, expected_profile)\n\n def test_cfr(self):\n root = rcfr.RootStateWrapper(_GAME.new_initial_state())\n num_half_iterations = 6\n\n cumulative_regrets = [np.zeros(n) for n in root.num_player_sequences]\n cumulative_reach_weights = [np.zeros(n) for n in root.num_player_sequences]\n\n average_profile = root.sequence_weights_to_tabular_profile(\n cumulative_reach_weights)\n self.assertGreater(pyspiel.nash_conv(_GAME, average_profile), 0.91)\n\n regret_player = 0\n for _ in range(num_half_iterations):\n reach_weights_player = 1 if regret_player == 0 else 0\n\n regrets, reach = root.counterfactual_regrets_and_reach_weights(\n regret_player, reach_weights_player, *rcfr.relu(cumulative_regrets))\n\n cumulative_regrets[regret_player] += regrets\n cumulative_reach_weights[reach_weights_player] += reach\n\n regret_player = reach_weights_player\n\n average_profile = root.sequence_weights_to_tabular_profile(\n cumulative_reach_weights)\n self.assertLess(pyspiel.nash_conv(_GAME, average_profile), 0.27)\n\n def test_rcfr_functions(self):\n models = [_new_model() for _ in range(_GAME.num_players())]\n root = rcfr.RootStateWrapper(_GAME.new_initial_state())\n\n num_half_iterations = 4\n num_epochs = 100\n\n cumulative_regrets = [np.zeros(n) for n in root.num_player_sequences]\n cumulative_reach_weights = [np.zeros(n) for n in root.num_player_sequences]\n\n average_profile = root.sequence_weights_to_tabular_profile(\n cumulative_reach_weights)\n self.assertGreater(pyspiel.nash_conv(_GAME, average_profile), 0.91)\n\n regret_player = 0\n sequence_weights = [\n model(root.sequence_features[player]).numpy()\n for player, model in enumerate(models)\n ]\n\n for _ in range(num_half_iterations):\n reach_weights_player = 1 if regret_player == 0 else 0\n\n sequence_weights[reach_weights_player] = models[reach_weights_player](\n root.sequence_features[reach_weights_player]).numpy()\n\n regrets, seq_probs = root.counterfactual_regrets_and_reach_weights(\n regret_player, reach_weights_player, *sequence_weights)\n\n cumulative_regrets[regret_player] += regrets\n cumulative_reach_weights[reach_weights_player] += seq_probs\n\n data = tf.data.Dataset.from_tensor_slices(\n (root.sequence_features[regret_player],\n tf.expand_dims(cumulative_regrets[regret_player], axis=1)))\n data = data.shuffle(12)\n data = data.batch(12)\n data = data.repeat(num_epochs)\n\n optimizer = tf.keras.optimizers.Adam(lr=0.005, amsgrad=True)\n\n for x, y in data:\n optimizer.minimize(\n lambda: tf.losses.huber_loss(y, models[regret_player](x)), # pylint: disable=cell-var-from-loop\n models[regret_player].trainable_variables)\n\n regret_player = reach_weights_player\n\n average_profile = root.sequence_weights_to_tabular_profile(\n cumulative_reach_weights)\n\n self.assertLess(pyspiel.nash_conv(_GAME, average_profile), 0.91)\n\n @parameterized.parameters(list(itertools.product(_BOOLEANS, _BOOLEANS)))\n def test_rcfr(self, bootstrap, truncate_negative):\n num_epochs = 100\n num_iterations = 2\n models = [_new_model() for _ in range(_GAME.num_players())]\n\n patient = rcfr.RcfrSolver(\n _GAME, models, bootstrap=bootstrap, truncate_negative=truncate_negative)\n\n def _train(model, data):\n data = data.shuffle(12)\n data = data.batch(12)\n data = data.repeat(num_epochs)\n\n optimizer = tf.keras.optimizers.Adam(lr=0.005, amsgrad=True)\n\n for x, y in data:\n optimizer.minimize(\n lambda: tf.losses.huber_loss(y, model(x)), # pylint: disable=cell-var-from-loop\n model.trainable_variables)\n\n average_policy = patient.average_policy()\n self.assertGreater(pyspiel.nash_conv(_GAME, average_policy), 0.91)\n\n for _ in range(num_iterations):\n patient.evaluate_and_update_policy(_train)\n\n average_policy = patient.average_policy()\n self.assertLess(pyspiel.nash_conv(_GAME, average_policy), 0.91)\n\n def test_reservior_buffer_insert(self):\n buffer_size = 10\n patient = rcfr.ReservoirBuffer(buffer_size)\n\n x_buffer = []\n for i in range(buffer_size):\n patient.insert(i)\n x_buffer.append(i)\n assert patient.num_elements == len(x_buffer)\n self.assertAllEqual(x_buffer, patient.buffer)\n\n assert patient.num_available_spaces() == 0\n\n for i in range(buffer_size):\n patient.insert(buffer_size + i)\n assert patient.num_elements == buffer_size\n\n def test_reservior_buffer_insert_all(self):\n buffer_size = 10\n patient = rcfr.ReservoirBuffer(buffer_size)\n\n x_buffer = list(range(buffer_size))\n patient.insert_all(x_buffer)\n assert patient.num_elements == buffer_size\n self.assertAllEqual(x_buffer, patient.buffer)\n\n assert patient.num_available_spaces() == 0\n\n x_buffer = list(range(buffer_size, 2 * buffer_size))\n patient.insert_all(x_buffer)\n assert patient.num_elements == buffer_size\n\n def test_rcfr_with_buffer(self):\n buffer_size = 12\n num_epochs = 100\n num_iterations = 2\n models = [_new_model() for _ in range(_GAME.num_players())]\n\n patient = rcfr.ReservoirRcfrSolver(_GAME, models, buffer_size=buffer_size)\n\n def _train(model, data):\n data = data.shuffle(12)\n data = data.batch(12)\n data = data.repeat(num_epochs)\n\n optimizer = tf.keras.optimizers.Adam(lr=0.005, amsgrad=True)\n\n for x, y in data:\n optimizer.minimize(\n lambda: tf.losses.huber_loss(y, model(x)), # pylint: disable=cell-var-from-loop\n model.trainable_variables)\n\n average_policy = patient.average_policy()\n self.assertGreater(pyspiel.nash_conv(_GAME, average_policy), 0.91)\n\n for _ in range(num_iterations):\n patient.evaluate_and_update_policy(_train)\n\n average_policy = patient.average_policy()\n self.assertLess(pyspiel.nash_conv(_GAME, average_policy), 0.91)\n\n\nif __name__ == '__main__':\n absltest.main()\n"
]
| [
[
"tensorflow.compat.v1.ones",
"tensorflow.compat.v1.keras.optimizers.Adam",
"tensorflow.compat.v1.expand_dims",
"tensorflow.compat.v1.disable_v2_behavior",
"tensorflow.compat.v1.random.set_random_seed",
"tensorflow.compat.v1.enable_eager_execution",
"numpy.zeros"
]
]
|
JoyHuYY1412/CADR-FixMatch | [
"e226b43951a25384ae9074ea56a8a6316f1d31be"
]
| [
"scripts/inspect_dataset.py"
]
| [
"#!/usr/bin/env python\n\n\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# https://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\"\"\"Script to inspect a dataset, in particular label distribution.\n\"\"\"\n\nimport numpy as np\nimport tensorflow as tf\nfrom absl import app\nfrom absl import flags\nfrom tqdm import trange\n\nfrom libml import data, utils\n\nflags.DEFINE_integer('batch', 64, 'Batch size.')\nflags.DEFINE_integer('samples', 1 << 16, 'Number of samples to load.')\n\nFLAGS = flags.FLAGS\n\n\ndef main(argv):\n utils.setup_main()\n del argv\n utils.setup_tf()\n nbatch = FLAGS.samples // FLAGS.batch\n dataset = data.DATASETS()[FLAGS.dataset]()\n groups = [('labeled', dataset.train_labeled),\n ('unlabeled', dataset.train_unlabeled),\n ('test', dataset.test.repeat())]\n groups = [(name, ds.batch(FLAGS.batch).prefetch(16).make_one_shot_iterator().get_next())\n for name, ds in groups]\n with tf.train.MonitoredSession() as sess:\n for group, train_data in groups:\n stats = np.zeros(dataset.nclass, np.int32)\n minmax = [], []\n for _ in trange(nbatch, leave=False, unit='img', unit_scale=FLAGS.batch, desc=group):\n v = sess.run(train_data)['label']\n for u in v:\n stats[u] += 1\n minmax[0].append(v.min())\n minmax[1].append(v.max())\n print(group)\n print(' Label range', min(minmax[0]), max(minmax[1]))\n print(' Stats', ' '.join(['%.2f' % (100 * x) for x in (stats / stats.max())]))\n\n\nif __name__ == '__main__':\n app.run(main)\n"
]
| [
[
"tensorflow.train.MonitoredSession",
"numpy.zeros"
]
]
|
ethanscho/tensorflow-edge | [
"bea7f4e570a854827276c1215f4bbada90fabc9b"
]
| [
"edge/semantic_segmentation/model.py"
]
| [
"\nimport numpy as np\nimport tensorflow as tf\n\nclass Model(object):\n def __init__(self, model_filepath):\n # The file path of model\n self.model_filepath = model_filepath\n # Initialize the model\n self.load_graph(model_filepath = self.model_filepath)\n\n def load_graph(self, model_filepath):\n '''\n Lode trained model.\n '''\n print('Loading model...')\n self.graph = tf.Graph()\n self.sess = tf.InteractiveSession(graph = self.graph)\n\n with tf.gfile.GFile(model_filepath, 'rb') as f:\n graph_def = tf.GraphDef()\n graph_def.ParseFromString(f.read())\n\n print('Check out the input placeholders:')\n # nodes = [n.name + ' => ' + n.op for n in graph_def.node if n.op in ('Placeholder')]\n # for node in nodes:\n # print(node)\n\n graph_nodes=[n for n in graph_def.node]\n names = []\n for t in graph_nodes:\n names.append(t.name)\n print(names)\n\n # Define input tensor\n self.input = tf.placeholder(np.float32, shape = [None, 513, 513, 3], name='Input')\n\n tf.import_graph_def(graph_def, {'Input': self.input})\n print('Model loading complete!')\n\n # Get layer names\n layers = [op.name for op in self.graph.get_operations()]\n for layer in layers:\n print(layer)\n\n '''\n # Check out the weights of the nodes\n weight_nodes = [n for n in graph_def.node if n.op == 'Const']\n for n in weight_nodes:\n print(\"Name of the node - %s\" % n.name)\n print(\"Value - \" )\n print(tensor_util.MakeNdarray(n.attr['value'].tensor))\n '''\n\n def predict(self, data):\n #output_tensor = self.graph.get_tensor_by_name(\"import/Output:0\")\n output_tensor = self.graph.get_tensor_by_name(\"import/ResizeBilinear_1:0\")\n output = self.sess.run(output_tensor, feed_dict = {self.input: data})\n\n return output"
]
| [
[
"tensorflow.Graph",
"tensorflow.import_graph_def",
"tensorflow.InteractiveSession",
"tensorflow.gfile.GFile",
"tensorflow.placeholder",
"tensorflow.GraphDef"
]
]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.